Files

Return to Package Diff Home.
Brought to you by Intrinsic.

Package Diff: three @ 0.136.0 .. 0.137.0

build/three.cjs

@@ -0,0 +1,36748 @@
+/**
+ * @license
+ * Copyright 2010-2022 Three.js Authors
+ * SPDX-License-Identifier: MIT
+ */
+'use strict';
+
+Object.defineProperty(exports, '__esModule', { value: true });
+
+const REVISION = '137';
+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 FlatShading = 1;
+const SmoothShading = 2;
+const NoBlending = 0;
+const NormalBlending = 1;
+const AdditiveBlending = 2;
+const SubtractiveBlending = 3;
+const MultiplyBlending = 4;
+const CustomBlending = 5;
+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 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 UVMapping = 300;
+const CubeReflectionMapping = 301;
+const CubeRefractionMapping = 302;
+const EquirectangularReflectionMapping = 303;
+const EquirectangularRefractionMapping = 304;
+const CubeUVReflectionMapping = 306;
+const CubeUVRefractionMapping = 307;
+const RepeatWrapping = 1000;
+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 AlphaFormat = 1021;
+const RGBAFormat = 1023;
+const LuminanceFormat = 1024;
+const LuminanceAlphaFormat = 1025;
+const DepthFormat = 1026;
+const DepthStencilFormat = 1027;
+const RedFormat = 1028;
+const RedIntegerFormat = 1029;
+const RGFormat = 1030;
+const RGIntegerFormat = 1031;
+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 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 LoopOnce = 2200;
+const LoopRepeat = 2201;
+const LoopPingPong = 2202;
+const InterpolateDiscrete = 2300;
+const InterpolateLinear = 2301;
+const InterpolateSmooth = 2302;
+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 LinearEncoding = 3000;
+const sRGBEncoding = 3001;
+const BasicDepthPacking = 3200;
+const RGBADepthPacking = 3201;
+const TangentSpaceNormalMap = 0;
+const ObjectSpaceNormalMap = 1;
+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 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 _SRGBAFormat = 1035; // fallback for WebGL 1
+
+/**
+ * https://github.com/mrdoob/eventdispatcher.js/
+ */
+class EventDispatcher {
+ addEventListener(type, listener) {
+ if (this._listeners === undefined) this._listeners = {};
+ const listeners = this._listeners;
+
+ if (listeners[type] === undefined) {
+ listeners[type] = [];
+ }
+
+ if (listeners[type].indexOf(listener) === -1) {
+ listeners[type].push(listener);
+ }
+ }
+
+ hasEventListener(type, listener) {
+ if (this._listeners === undefined) return false;
+ const listeners = this._listeners;
+ return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
+ }
+
+ removeEventListener(type, listener) {
+ if (this._listeners === undefined) return;
+ const listeners = this._listeners;
+ const listenerArray = listeners[type];
+
+ if (listenerArray !== undefined) {
+ const index = listenerArray.indexOf(listener);
+
+ if (index !== -1) {
+ listenerArray.splice(index, 1);
+ }
+ }
+ }
+
+ dispatchEvent(event) {
+ if (this._listeners === undefined) return;
+ const listeners = this._listeners;
+ const listenerArray = listeners[event.type];
+
+ if (listenerArray !== undefined) {
+ event.target = this; // Make a copy, in case listeners are removed while iterating.
+
+ const array = listenerArray.slice(0);
+
+ for (let i = 0, l = array.length; i < l; i++) {
+ array[i].call(this, event);
+ }
+
+ event.target = null;
+ }
+ }
+
+}
+
+const _lut = [];
+
+for (let i = 0; i < 256; i++) {
+ _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
+}
+
+let _seed = 1234567;
+const DEG2RAD = Math.PI / 180;
+const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
+
+function generateUUID() {
+ const d0 = Math.random() * 0xffffffff | 0;
+ const d1 = Math.random() * 0xffffffff | 0;
+ const d2 = Math.random() * 0xffffffff | 0;
+ const d3 = Math.random() * 0xffffffff | 0;
+ const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
+
+ return uuid.toUpperCase();
+}
+
+function clamp(value, min, max) {
+ return Math.max(min, Math.min(max, value));
+} // compute euclidian modulo of m % n
+// https://en.wikipedia.org/wiki/Modulo_operation
+
+
+function euclideanModulo(n, m) {
+ return (n % m + m) % m;
+} // Linear mapping from range <a1, a2> to range <b1, b2>
+
+
+function mapLinear(x, a1, a2, b1, b2) {
+ return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
+} // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
+
+
+function inverseLerp(x, y, value) {
+ if (x !== y) {
+ return (value - x) / (y - x);
+ } else {
+ return 0;
+ }
+} // https://en.wikipedia.org/wiki/Linear_interpolation
+
+
+function lerp(x, y, t) {
+ return (1 - t) * x + t * y;
+} // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
+
+
+function damp(x, y, lambda, dt) {
+ return lerp(x, y, 1 - Math.exp(-lambda * dt));
+} // https://www.desmos.com/calculator/vcsjnyz7x4
+
+
+function pingpong(x, length = 1) {
+ return length - Math.abs(euclideanModulo(x, length * 2) - length);
+} // http://en.wikipedia.org/wiki/Smoothstep
+
+
+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);
+}
+
+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);
+} // Random integer from <low, high> interval
+
+
+function randInt(low, high) {
+ return low + Math.floor(Math.random() * (high - low + 1));
+} // Random float from <low, high> interval
+
+
+function randFloat(low, high) {
+ return low + Math.random() * (high - low);
+} // Random float from <-range/2, range/2> interval
+
+
+function randFloatSpread(range) {
+ return range * (0.5 - Math.random());
+} // Deterministic pseudo-random float in the interval [ 0, 1 ]
+
+
+function seededRandom(s) {
+ if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
+
+ _seed = _seed * 16807 % 2147483647;
+ return (_seed - 1) / 2147483646;
+}
+
+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) {
+ // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
+ // 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'
+ // angles are in radians
+ 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:
+ console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
+ }
+}
+
+var MathUtils = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ DEG2RAD: DEG2RAD,
+ RAD2DEG: RAD2DEG,
+ generateUUID: generateUUID,
+ clamp: clamp,
+ euclideanModulo: euclideanModulo,
+ mapLinear: mapLinear,
+ inverseLerp: inverseLerp,
+ lerp: lerp,
+ damp: damp,
+ pingpong: pingpong,
+ smoothstep: smoothstep,
+ smootherstep: smootherstep,
+ randInt: randInt,
+ randFloat: randFloat,
+ randFloatSpread: randFloatSpread,
+ seededRandom: seededRandom,
+ degToRad: degToRad,
+ radToDeg: radToDeg,
+ isPowerOfTwo: isPowerOfTwo,
+ ceilPowerOfTwo: ceilPowerOfTwo,
+ floorPowerOfTwo: floorPowerOfTwo,
+ setQuaternionFromProperEuler: setQuaternionFromProperEuler
+});
+
+class Vector2 {
+ constructor(x = 0, y = 0) {
+ this.x = x;
+ this.y = y;
+ }
+
+ get width() {
+ return this.x;
+ }
+
+ set width(value) {
+ this.x = value;
+ }
+
+ get height() {
+ return this.y;
+ }
+
+ set height(value) {
+ this.y = value;
+ }
+
+ set(x, y) {
+ this.x = x;
+ this.y = y;
+ return this;
+ }
+
+ setScalar(scalar) {
+ this.x = scalar;
+ this.y = scalar;
+ return this;
+ }
+
+ setX(x) {
+ this.x = x;
+ return this;
+ }
+
+ setY(y) {
+ this.y = y;
+ return this;
+ }
+
+ 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;
+ }
+
+ getComponent(index) {
+ switch (index) {
+ case 0:
+ return this.x;
+
+ case 1:
+ return this.y;
+
+ default:
+ throw new Error('index is out of range: ' + index);
+ }
+ }
+
+ clone() {
+ return new this.constructor(this.x, this.y);
+ }
+
+ copy(v) {
+ this.x = v.x;
+ this.y = v.y;
+ return this;
+ }
+
+ add(v, w) {
+ if (w !== undefined) {
+ console.warn('THREE.Vector2: .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;
+ }
+
+ addScalar(s) {
+ this.x += s;
+ this.y += s;
+ return this;
+ }
+
+ addVectors(a, b) {
+ this.x = a.x + b.x;
+ this.y = a.y + b.y;
+ return this;
+ }
+
+ addScaledVector(v, s) {
+ this.x += v.x * s;
+ this.y += v.y * s;
+ return this;
+ }
+
+ sub(v, w) {
+ if (w !== undefined) {
+ console.warn('THREE.Vector2: .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;
+ }
+
+ subScalar(s) {
+ this.x -= s;
+ this.y -= s;
+ return this;
+ }
+
+ subVectors(a, b) {
+ this.x = a.x - b.x;
+ this.y = a.y - b.y;
+ return this;
+ }
+
+ multiply(v) {
+ this.x *= v.x;
+ this.y *= v.y;
+ return this;
+ }
+
+ multiplyScalar(scalar) {
+ this.x *= scalar;
+ this.y *= scalar;
+ return this;
+ }
+
+ divide(v) {
+ this.x /= v.x;
+ this.y /= v.y;
+ return this;
+ }
+
+ divideScalar(scalar) {
+ return this.multiplyScalar(1 / scalar);
+ }
+
+ 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;
+ }
+
+ min(v) {
+ this.x = Math.min(this.x, v.x);
+ this.y = Math.min(this.y, v.y);
+ return this;
+ }
+
+ max(v) {
+ this.x = Math.max(this.x, v.x);
+ this.y = Math.max(this.y, v.y);
+ return this;
+ }
+
+ clamp(min, max) {
+ // assumes min < max, componentwise
+ this.x = Math.max(min.x, Math.min(max.x, this.x));
+ this.y = Math.max(min.y, Math.min(max.y, this.y));
+ return this;
+ }
+
+ clampScalar(minVal, maxVal) {
+ this.x = Math.max(minVal, Math.min(maxVal, this.x));
+ this.y = Math.max(minVal, Math.min(maxVal, this.y));
+ return this;
+ }
+
+ clampLength(min, max) {
+ const length = this.length();
+ return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
+ }
+
+ floor() {
+ this.x = Math.floor(this.x);
+ this.y = Math.floor(this.y);
+ return this;
+ }
+
+ ceil() {
+ this.x = Math.ceil(this.x);
+ this.y = Math.ceil(this.y);
+ return this;
+ }
+
+ round() {
+ this.x = Math.round(this.x);
+ this.y = Math.round(this.y);
+ return this;
+ }
+
+ roundToZero() {
+ 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() {
+ this.x = -this.x;
+ this.y = -this.y;
+ return this;
+ }
+
+ dot(v) {
+ return this.x * v.x + this.y * v.y;
+ }
+
+ cross(v) {
+ return this.x * v.y - this.y * v.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() {
+ // computes the angle in radians with respect to the positive x-axis
+ const angle = Math.atan2(-this.y, -this.x) + Math.PI;
+ return angle;
+ }
+
+ distanceTo(v) {
+ return Math.sqrt(this.distanceToSquared(v));
+ }
+
+ distanceToSquared(v) {
+ const dx = this.x - v.x,
+ dy = this.y - v.y;
+ return dx * dx + dy * dy;
+ }
+
+ manhattanDistanceTo(v) {
+ return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
+ }
+
+ setLength(length) {
+ return this.normalize().multiplyScalar(length);
+ }
+
+ lerp(v, alpha) {
+ this.x += (v.x - this.x) * alpha;
+ this.y += (v.y - this.y) * alpha;
+ return this;
+ }
+
+ lerpVectors(v1, v2, alpha) {
+ this.x = v1.x + (v2.x - v1.x) * alpha;
+ this.y = v1.y + (v2.y - v1.y) * alpha;
+ return this;
+ }
+
+ equals(v) {
+ return v.x === this.x && v.y === this.y;
+ }
+
+ fromArray(array, offset = 0) {
+ this.x = array[offset];
+ this.y = array[offset + 1];
+ return this;
+ }
+
+ toArray(array = [], offset = 0) {
+ array[offset] = this.x;
+ array[offset + 1] = this.y;
+ return array;
+ }
+
+ fromBufferAttribute(attribute, index, offset) {
+ if (offset !== undefined) {
+ console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
+ }
+
+ this.x = attribute.getX(index);
+ this.y = attribute.getY(index);
+ return this;
+ }
+
+ 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;
+ }
+
+ random() {
+ this.x = Math.random();
+ this.y = Math.random();
+ return this;
+ }
+
+ *[Symbol.iterator]() {
+ yield this.x;
+ yield this.y;
+ }
+
+}
+
+Vector2.prototype.isVector2 = true;
+
+class Matrix3 {
+ constructor() {
+ this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
+
+ if (arguments.length > 0) {
+ console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
+ }
+ }
+
+ 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;
+ }
+
+ identity() {
+ this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
+ return this;
+ }
+
+ 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;
+ }
+
+ extractBasis(xAxis, yAxis, zAxis) {
+ xAxis.setFromMatrix3Column(this, 0);
+ yAxis.setFromMatrix3Column(this, 1);
+ zAxis.setFromMatrix3Column(this, 2);
+ return this;
+ }
+
+ 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;
+ }
+
+ multiply(m) {
+ return this.multiplyMatrices(this, m);
+ }
+
+ premultiply(m) {
+ return this.multiplyMatrices(m, this);
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ transpose() {
+ let tmp;
+ const 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(matrix4) {
+ return this.setFromMatrix4(matrix4).invert().transpose();
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ scale(sx, sy) {
+ const te = this.elements;
+ te[0] *= sx;
+ te[3] *= sx;
+ te[6] *= sx;
+ te[1] *= sy;
+ te[4] *= sy;
+ te[7] *= sy;
+ return this;
+ }
+
+ rotate(theta) {
+ const c = Math.cos(theta);
+ const s = Math.sin(theta);
+ const te = this.elements;
+ const a11 = te[0],
+ a12 = te[3],
+ a13 = te[6];
+ const a21 = te[1],
+ a22 = te[4],
+ a23 = te[7];
+ te[0] = c * a11 + s * a21;
+ te[3] = c * a12 + s * a22;
+ te[6] = c * a13 + s * a23;
+ te[1] = -s * a11 + c * a21;
+ te[4] = -s * a12 + c * a22;
+ te[7] = -s * a13 + c * a23;
+ return this;
+ }
+
+ translate(tx, ty) {
+ const te = this.elements;
+ te[0] += tx * te[2];
+ te[3] += tx * te[5];
+ te[6] += tx * te[8];
+ te[1] += ty * te[2];
+ te[4] += ty * te[5];
+ te[7] += ty * te[8];
+ return this;
+ }
+
+ equals(matrix) {
+ const te = this.elements;
+ const me = matrix.elements;
+
+ for (let i = 0; i < 9; i++) {
+ if (te[i] !== me[i]) return false;
+ }
+
+ return true;
+ }
+
+ fromArray(array, offset = 0) {
+ for (let i = 0; i < 9; i++) {
+ this.elements[i] = array[i + offset];
+ }
+
+ return this;
+ }
+
+ 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;
+ }
+
+ clone() {
+ return new this.constructor().fromArray(this.elements);
+ }
+
+}
+
+Matrix3.prototype.isMatrix3 = true;
+
+function arrayNeedsUint32(array) {
+ // assumes larger values usually on last
+ for (let i = array.length - 1; i >= 0; --i) {
+ if (array[i] > 65535) return true;
+ }
+
+ return false;
+}
+
+const TYPED_ARRAYS = {
+ Int8Array: Int8Array,
+ Uint8Array: Uint8Array,
+ Uint8ClampedArray: Uint8ClampedArray,
+ Int16Array: Int16Array,
+ Uint16Array: Uint16Array,
+ Int32Array: Int32Array,
+ Uint32Array: Uint32Array,
+ Float32Array: Float32Array,
+ Float64Array: Float64Array
+};
+
+function getTypedArray(type, buffer) {
+ return new TYPED_ARRAYS[type](buffer);
+}
+
+function createElementNS(name) {
+ return document.createElementNS('http://www.w3.org/1999/xhtml', name);
+}
+
+const _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,
+ 'rebeccapurple': 0x663399,
+ '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
+};
+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;
+}
+
+function SRGBToLinear(c) {
+ return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
+}
+
+function LinearToSRGB(c) {
+ return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
+}
+
+class Color {
+ constructor(r, g, b) {
+ if (g === undefined && b === undefined) {
+ // r is THREE.Color, hex or string
+ return this.set(r);
+ }
+
+ return this.setRGB(r, g, b);
+ }
+
+ set(value) {
+ if (value && value.isColor) {
+ this.copy(value);
+ } else if (typeof value === 'number') {
+ this.setHex(value);
+ } else if (typeof value === 'string') {
+ this.setStyle(value);
+ }
+
+ return this;
+ }
+
+ setScalar(scalar) {
+ this.r = scalar;
+ this.g = scalar;
+ this.b = scalar;
+ return this;
+ }
+
+ setHex(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(r, g, b) {
+ this.r = r;
+ this.g = g;
+ this.b = b;
+ return this;
+ }
+
+ setHSL(h, s, l) {
+ // h,s,l ranges are in 0.0 - 1.0
+ 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);
+ }
+
+ return this;
+ }
+
+ setStyle(style) {
+ function handleAlpha(string) {
+ if (string === undefined) return;
+
+ if (parseFloat(string) < 1) {
+ console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
+ }
+ }
+
+ let m;
+
+ if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
+ // rgb / hsl
+ 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)) {
+ // rgb(255,0,0) rgba(255,0,0,0.5)
+ 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;
+ handleAlpha(color[4]);
+ return this;
+ }
+
+ if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
+ // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
+ 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;
+ handleAlpha(color[4]);
+ return this;
+ }
+
+ break;
+
+ case 'hsl':
+ case 'hsla':
+ if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
+ // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
+ const h = parseFloat(color[1]) / 360;
+ const s = parseInt(color[2], 10) / 100;
+ const l = parseInt(color[3], 10) / 100;
+ handleAlpha(color[4]);
+ return this.setHSL(h, s, l);
+ }
+
+ break;
+ }
+ } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
+ // hex color
+ const hex = m[1];
+ const size = hex.length;
+
+ if (size === 3) {
+ // #ff0
+ this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
+ this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
+ this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
+ return this;
+ } else if (size === 6) {
+ // #ff0000
+ this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
+ this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
+ this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
+ return this;
+ }
+ }
+
+ if (style && style.length > 0) {
+ return this.setColorName(style);
+ }
+
+ return this;
+ }
+
+ setColorName(style) {
+ // color keywords
+ const hex = _colorKeywords[style.toLowerCase()];
+
+ if (hex !== undefined) {
+ // red
+ this.setHex(hex);
+ } else {
+ // unknown color
+ console.warn('THREE.Color: Unknown color ' + style);
+ }
+
+ return this;
+ }
+
+ clone() {
+ return new this.constructor(this.r, this.g, this.b);
+ }
+
+ copy(color) {
+ this.r = color.r;
+ this.g = color.g;
+ this.b = color.b;
+ return this;
+ }
+
+ copySRGBToLinear(color) {
+ this.r = SRGBToLinear(color.r);
+ this.g = SRGBToLinear(color.g);
+ this.b = SRGBToLinear(color.b);
+ return this;
+ }
+
+ copyLinearToSRGB(color) {
+ this.r = LinearToSRGB(color.r);
+ this.g = LinearToSRGB(color.g);
+ this.b = LinearToSRGB(color.b);
+ return this;
+ }
+
+ convertSRGBToLinear() {
+ this.copySRGBToLinear(this);
+ return this;
+ }
+
+ convertLinearToSRGB() {
+ this.copyLinearToSRGB(this);
+ return this;
+ }
+
+ getHex() {
+ return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
+ }
+
+ getHexString() {
+ return ('000000' + this.getHex().toString(16)).slice(-6);
+ }
+
+ getHSL(target) {
+ // h,s,l ranges are in 0.0 - 1.0
+ const r = this.r,
+ g = this.g,
+ b = this.b;
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ let hue, saturation;
+ const lightness = (min + max) / 2.0;
+
+ 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;
+ }
+
+ getStyle() {
+ return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
+ }
+
+ offsetHSL(h, s, l) {
+ this.getHSL(_hslA);
+ _hslA.h += h;
+ _hslA.s += s;
+ _hslA.l += l;
+ this.setHSL(_hslA.h, _hslA.s, _hslA.l);
+ return this;
+ }
+
+ add(color) {
+ this.r += color.r;
+ this.g += color.g;
+ this.b += color.b;
+ return this;
+ }
+
+ addColors(color1, color2) {
+ this.r = color1.r + color2.r;
+ this.g = color1.g + color2.g;
+ this.b = color1.b + color2.b;
+ return this;
+ }
+
+ addScalar(s) {
+ this.r += s;
+ this.g += s;
+ this.b += s;
+ return this;
+ }
+
+ 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;
+ }
+
+ multiply(color) {
+ this.r *= color.r;
+ this.g *= color.g;
+ this.b *= color.b;
+ return this;
+ }
+
+ multiplyScalar(s) {
+ this.r *= s;
+ this.g *= s;
+ this.b *= s;
+ return this;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ equals(c) {
+ return c.r === this.r && c.g === this.g && c.b === this.b;
+ }
+
+ fromArray(array, offset = 0) {
+ this.r = array[offset];
+ this.g = array[offset + 1];
+ this.b = array[offset + 2];
+ return this;
+ }
+
+ toArray(array = [], offset = 0) {
+ array[offset] = this.r;
+ array[offset + 1] = this.g;
+ array[offset + 2] = this.b;
+ return array;
+ }
+
+ fromBufferAttribute(attribute, index) {
+ this.r = attribute.getX(index);
+ this.g = attribute.getY(index);
+ this.b = attribute.getZ(index);
+
+ if (attribute.normalized === true) {
+ // assuming Uint8Array
+ this.r /= 255;
+ this.g /= 255;
+ this.b /= 255;
+ }
+
+ return this;
+ }
+
+ toJSON() {
+ return this.getHex();
+ }
+
+}
+
+Color.NAMES = _colorKeywords;
+Color.prototype.isColor = true;
+Color.prototype.r = 1;
+Color.prototype.g = 1;
+Color.prototype.b = 1;
+
+let _canvas;
+
+class ImageUtils {
+ static getDataURL(image) {
+ if (/^data:/i.test(image.src)) {
+ return image.src;
+ }
+
+ if (typeof HTMLCanvasElement == 'undefined') {
+ return image.src;
+ }
+
+ let canvas;
+
+ if (image instanceof HTMLCanvasElement) {
+ canvas = image;
+ } else {
+ if (_canvas === undefined) _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;
+ }
+
+ if (canvas.width > 2048 || canvas.height > 2048) {
+ console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
+ return canvas.toDataURL('image/jpeg', 0.6);
+ } else {
+ return canvas.toDataURL('image/png');
+ }
+ }
+
+ 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 {
+ // assuming float
+ data[i] = SRGBToLinear(data[i]);
+ }
+ }
+
+ return {
+ data: data,
+ width: image.width,
+ height: image.height
+ };
+ } else {
+ console.warn('THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.');
+ return image;
+ }
+ }
+
+}
+
+let textureId = 0;
+
+class Texture extends EventDispatcher {
+ constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
+ super();
+ Object.defineProperty(this, 'id', {
+ value: textureId++
+ });
+ this.uuid = generateUUID();
+ this.name = '';
+ this.image = image;
+ this.mipmaps = [];
+ this.mapping = mapping;
+ 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; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
+ // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
+ //
+ // Also changing the encoding after already used by a Material will not automatically make the Material
+ // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
+
+ this.encoding = encoding;
+ this.userData = {};
+ this.version = 0;
+ this.onUpdate = null;
+ this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
+
+ this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
+ }
+
+ updateMatrix() {
+ this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+ copy(source) {
+ this.name = source.name;
+ this.image = source.image;
+ this.mipmaps = source.mipmaps.slice(0);
+ this.mapping = source.mapping;
+ 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.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.encoding = source.encoding;
+ this.userData = JSON.parse(JSON.stringify(source.userData));
+ return this;
+ }
+
+ toJSON(meta) {
+ const isRootObject = meta === undefined || typeof meta === 'string';
+
+ if (!isRootObject && meta.textures[this.uuid] !== undefined) {
+ return meta.textures[this.uuid];
+ }
+
+ const output = {
+ metadata: {
+ version: 4.5,
+ type: 'Texture',
+ generator: 'Texture.toJSON'
+ },
+ uuid: this.uuid,
+ name: this.name,
+ mapping: this.mapping,
+ repeat: [this.repeat.x, this.repeat.y],
+ offset: [this.offset.x, this.offset.y],
+ center: [this.center.x, this.center.y],
+ rotation: this.rotation,
+ wrap: [this.wrapS, this.wrapT],
+ format: this.format,
+ type: this.type,
+ encoding: this.encoding,
+ minFilter: this.minFilter,
+ magFilter: this.magFilter,
+ anisotropy: this.anisotropy,
+ flipY: this.flipY,
+ premultiplyAlpha: this.premultiplyAlpha,
+ unpackAlignment: this.unpackAlignment
+ };
+
+ if (this.image !== undefined) {
+ // TODO: Move to THREE.Image
+ const image = this.image;
+
+ if (image.uuid === undefined) {
+ image.uuid = generateUUID(); // UGH
+ }
+
+ if (!isRootObject && meta.images[image.uuid] === undefined) {
+ let url;
+
+ if (Array.isArray(image)) {
+ // process array of images e.g. CubeTexture
+ url = [];
+
+ for (let i = 0, l = image.length; i < l; i++) {
+ // check cube texture with data textures
+ if (image[i].isDataTexture) {
+ url.push(serializeImage(image[i].image));
+ } else {
+ url.push(serializeImage(image[i]));
+ }
+ }
+ } else {
+ // process single image
+ url = serializeImage(image);
+ }
+
+ meta.images[image.uuid] = {
+ uuid: image.uuid,
+ url: url
+ };
+ }
+
+ output.image = image.uuid;
+ }
+
+ if (JSON.stringify(this.userData) !== '{}') output.userData = this.userData;
+
+ if (!isRootObject) {
+ meta.textures[this.uuid] = output;
+ }
+
+ return output;
+ }
+
+ dispose() {
+ this.dispatchEvent({
+ type: 'dispose'
+ });
+ }
+
+ 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;
+ }
+
+ set needsUpdate(value) {
+ if (value === true) this.version++;
+ }
+
+}
+
+Texture.DEFAULT_IMAGE = undefined;
+Texture.DEFAULT_MAPPING = UVMapping;
+Texture.prototype.isTexture = true;
+
+function serializeImage(image) {
+ if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
+ // default images
+ return ImageUtils.getDataURL(image);
+ } else {
+ if (image.data) {
+ // images of DataTexture
+ return {
+ data: Array.prototype.slice.call(image.data),
+ width: image.width,
+ height: image.height,
+ type: image.data.constructor.name
+ };
+ } else {
+ console.warn('THREE.Texture: Unable to serialize Texture.');
+ return {};
+ }
+ }
+}
+
+class Vector4 {
+ constructor(x = 0, y = 0, z = 0, w = 1) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ this.w = w;
+ }
+
+ get width() {
+ return this.z;
+ }
+
+ set width(value) {
+ this.z = value;
+ }
+
+ get height() {
+ return this.w;
+ }
+
+ set height(value) {
+ this.w = value;
+ }
+
+ set(x, y, z, w) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ this.w = w;
+ return this;
+ }
+
+ setScalar(scalar) {
+ this.x = scalar;
+ this.y = scalar;
+ this.z = scalar;
+ this.w = scalar;
+ return this;
+ }
+
+ setX(x) {
+ this.x = x;
+ return this;
+ }
+
+ setY(y) {
+ this.y = y;
+ return this;
+ }
+
+ setZ(z) {
+ this.z = z;
+ return this;
+ }
+
+ setW(w) {
+ this.w = w;
+ return this;
+ }
+
+ 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;
+ }
+
+ 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);
+ }
+ }
+
+ clone() {
+ return new this.constructor(this.x, this.y, this.z, this.w);
+ }
+
+ copy(v) {
+ this.x = v.x;
+ this.y = v.y;
+ this.z = v.z;
+ this.w = v.w !== undefined ? v.w : 1;
+ return this;
+ }
+
+ add(v, w) {
+ if (w !== undefined) {
+ console.warn('THREE.Vector4: .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(s) {
+ this.x += s;
+ this.y += s;
+ this.z += s;
+ this.w += s;
+ return this;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ sub(v, w) {
+ if (w !== undefined) {
+ console.warn('THREE.Vector4: .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;
+ }
+
+ subScalar(s) {
+ this.x -= s;
+ this.y -= s;
+ this.z -= s;
+ this.w -= s;
+ return this;
+ }
+
+ 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;
+ }
+
+ multiply(v) {
+ this.x *= v.x;
+ this.y *= v.y;
+ this.z *= v.z;
+ this.w *= v.w;
+ return this;
+ }
+
+ multiplyScalar(scalar) {
+ this.x *= scalar;
+ this.y *= scalar;
+ this.z *= scalar;
+ this.w *= scalar;
+ return this;
+ }
+
+ 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;
+ }
+
+ divideScalar(scalar) {
+ return this.multiplyScalar(1 / scalar);
+ }
+
+ setAxisAngleFromQuaternion(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);
+ const 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(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)
+ let angle, x, y, z; // variables for result
+
+ const 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;
+ 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) {
+ // 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
+
+
+ let 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(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;
+ }
+
+ 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;
+ }
+
+ clamp(min, max) {
+ // assumes min < max, componentwise
+ this.x = Math.max(min.x, Math.min(max.x, this.x));
+ this.y = Math.max(min.y, Math.min(max.y, this.y));
+ this.z = Math.max(min.z, Math.min(max.z, this.z));
+ this.w = Math.max(min.w, Math.min(max.w, this.w));
+ return this;
+ }
+
+ clampScalar(minVal, maxVal) {
+ this.x = Math.max(minVal, Math.min(maxVal, this.x));
+ this.y = Math.max(minVal, Math.min(maxVal, this.y));
+ this.z = Math.max(minVal, Math.min(maxVal, this.z));
+ this.w = Math.max(minVal, Math.min(maxVal, this.w));
+ return this;
+ }
+
+ clampLength(min, max) {
+ const length = this.length();
+ return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ roundToZero() {
+ 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() {
+ this.x = -this.x;
+ this.y = -this.y;
+ this.z = -this.z;
+ this.w = -this.w;
+ return this;
+ }
+
+ dot(v) {
+ return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.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(length) {
+ return this.normalize().multiplyScalar(length);
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ equals(v) {
+ return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ fromBufferAttribute(attribute, index, offset) {
+ if (offset !== undefined) {
+ console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
+ }
+
+ this.x = attribute.getX(index);
+ this.y = attribute.getY(index);
+ this.z = attribute.getZ(index);
+ this.w = attribute.getW(index);
+ return this;
+ }
+
+ 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;
+
+/*
+ In options, we can specify:
+ * Texture parameters for an auto-generated target texture
+ * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
+*/
+
+class WebGLRenderTarget extends EventDispatcher {
+ constructor(width, height, options = {}) {
+ super();
+ this.width = width;
+ this.height = height;
+ this.depth = 1;
+ this.scissor = new Vector4(0, 0, width, height);
+ this.scissorTest = false;
+ this.viewport = new Vector4(0, 0, width, height);
+ this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
+ this.texture.isRenderTargetTexture = true;
+ this.texture.image = {
+ width: width,
+ height: height,
+ depth: 1
+ };
+ this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
+ this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
+ this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
+ this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
+ this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
+ this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
+ }
+
+ setTexture(texture) {
+ texture.image = {
+ width: this.width,
+ height: this.height,
+ depth: this.depth
+ };
+ this.texture = texture;
+ }
+
+ setSize(width, height, depth = 1) {
+ if (this.width !== width || this.height !== height || this.depth !== depth) {
+ this.width = width;
+ this.height = height;
+ this.depth = depth;
+ this.texture.image.width = width;
+ this.texture.image.height = height;
+ this.texture.image.depth = depth;
+ this.dispose();
+ }
+
+ this.viewport.set(0, 0, width, height);
+ this.scissor.set(0, 0, width, height);
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+ copy(source) {
+ this.width = source.width;
+ this.height = source.height;
+ this.depth = source.depth;
+ this.viewport.copy(source.viewport);
+ this.texture = source.texture.clone(); // ensure image object is not shared, see #20328
+
+ this.texture.image = Object.assign({}, source.texture.image);
+ this.depthBuffer = source.depthBuffer;
+ this.stencilBuffer = source.stencilBuffer;
+ this.depthTexture = source.depthTexture;
+ return this;
+ }
+
+ dispose() {
+ this.dispatchEvent({
+ type: 'dispose'
+ });
+ }
+
+}
+
+WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
+
+class WebGLMultipleRenderTargets extends WebGLRenderTarget {
+ constructor(width, height, count) {
+ super(width, height);
+ const texture = this.texture;
+ this.texture = [];
+
+ for (let i = 0; i < count; i++) {
+ this.texture[i] = texture.clone();
+ }
+ }
+
+ 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.texture.length; i < il; i++) {
+ this.texture[i].image.width = width;
+ this.texture[i].image.height = height;
+ this.texture[i].image.depth = depth;
+ }
+
+ this.dispose();
+ }
+
+ this.viewport.set(0, 0, width, height);
+ this.scissor.set(0, 0, width, height);
+ return this;
+ }
+
+ copy(source) {
+ this.dispose();
+ this.width = source.width;
+ this.height = source.height;
+ this.depth = source.depth;
+ this.viewport.set(0, 0, this.width, this.height);
+ this.scissor.set(0, 0, this.width, this.height);
+ this.depthBuffer = source.depthBuffer;
+ this.stencilBuffer = source.stencilBuffer;
+ this.depthTexture = source.depthTexture;
+ this.texture.length = 0;
+
+ for (let i = 0, il = source.texture.length; i < il; i++) {
+ this.texture[i] = source.texture[i].clone();
+ }
+
+ return this;
+ }
+
+}
+
+WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
+
+class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
+ constructor(width, height, options = {}) {
+ super(width, height, options);
+ this.samples = 4;
+ this.ignoreDepthForMultisampleCopy = options.ignoreDepth !== undefined ? options.ignoreDepth : true;
+ this.useRenderToTexture = options.useRenderToTexture !== undefined ? options.useRenderToTexture : false;
+ this.useRenderbuffer = this.useRenderToTexture === false;
+ }
+
+ copy(source) {
+ super.copy.call(this, source);
+ this.samples = source.samples;
+ this.useRenderToTexture = source.useRenderToTexture;
+ this.useRenderbuffer = source.useRenderbuffer;
+ return this;
+ }
+
+}
+
+WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
+
+class Quaternion {
+ constructor(x = 0, y = 0, z = 0, w = 1) {
+ this._x = x;
+ this._y = y;
+ this._z = z;
+ this._w = w;
+ }
+
+ static slerp(qa, qb, qm, t) {
+ console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
+ return qm.slerpQuaternions(qa, qb, t);
+ }
+
+ static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
+ // fuzz-free, array-based Quaternion SLERP operation
+ let x0 = src0[srcOffset0 + 0],
+ y0 = src0[srcOffset0 + 1],
+ z0 = src0[srcOffset0 + 2],
+ w0 = src0[srcOffset0 + 3];
+ const x1 = src1[srcOffset1 + 0],
+ y1 = src1[srcOffset1 + 1],
+ z1 = src1[srcOffset1 + 2],
+ w1 = src1[srcOffset1 + 3];
+
+ if (t === 0) {
+ dst[dstOffset + 0] = x0;
+ dst[dstOffset + 1] = y0;
+ dst[dstOffset + 2] = z0;
+ dst[dstOffset + 3] = w0;
+ return;
+ }
+
+ if (t === 1) {
+ dst[dstOffset + 0] = x1;
+ dst[dstOffset + 1] = y1;
+ dst[dstOffset + 2] = z1;
+ dst[dstOffset + 3] = w1;
+ return;
+ }
+
+ if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
+ let s = 1 - t;
+ const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
+ dir = cos >= 0 ? 1 : -1,
+ sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
+
+ if (sqrSin > Number.EPSILON) {
+ const sin = Math.sqrt(sqrSin),
+ len = Math.atan2(sin, cos * dir);
+ s = Math.sin(s * len) / sin;
+ t = Math.sin(t * len) / sin;
+ }
+
+ const tDir = t * dir;
+ x0 = x0 * s + x1 * tDir;
+ y0 = y0 * s + y1 * tDir;
+ z0 = z0 * s + z1 * tDir;
+ w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
+
+ if (s === 1 - 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;
+ }
+
+ 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;
+ }
+
+ get x() {
+ return this._x;
+ }
+
+ set x(value) {
+ this._x = value;
+
+ this._onChangeCallback();
+ }
+
+ get y() {
+ return this._y;
+ }
+
+ set y(value) {
+ this._y = value;
+
+ this._onChangeCallback();
+ }
+
+ get z() {
+ return this._z;
+ }
+
+ set z(value) {
+ this._z = value;
+
+ this._onChangeCallback();
+ }
+
+ get w() {
+ return this._w;
+ }
+
+ set w(value) {
+ this._w = value;
+
+ this._onChangeCallback();
+ }
+
+ set(x, y, z, w) {
+ this._x = x;
+ this._y = y;
+ this._z = z;
+ this._w = w;
+
+ this._onChangeCallback();
+
+ return this;
+ }
+
+ clone() {
+ return new this.constructor(this._x, this._y, this._z, this._w);
+ }
+
+ copy(quaternion) {
+ this._x = quaternion.x;
+ this._y = quaternion.y;
+ this._z = quaternion.z;
+ this._w = quaternion.w;
+
+ this._onChangeCallback();
+
+ return this;
+ }
+
+ setFromEuler(euler, update) {
+ if (!(euler && euler.isEuler)) {
+ throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
+ }
+
+ const x = euler._x,
+ y = euler._y,
+ z = euler._z,
+ order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
+ // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
+ // content/SpinCalc.m
+
+ 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:
+ console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
+ }
+
+ if (update !== false) this._onChangeCallback();
+ return this;
+ }
+
+ setFromAxisAngle(axis, angle) {
+ // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
+ // assumes axis is normalized
+ 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;
+ }
+
+ setFromRotationMatrix(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)
+ 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.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) {
+ const 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) {
+ const 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 {
+ const 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._onChangeCallback();
+
+ return this;
+ }
+
+ setFromUnitVectors(vFrom, vTo) {
+ // assumes direction vectors vFrom and vTo are normalized
+ let r = vFrom.dot(vTo) + 1;
+
+ if (r < Number.EPSILON) {
+ // vFrom and vTo point in opposite directions
+ 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 {
+ // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
+ 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();
+ }
+
+ angleTo(q) {
+ return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
+ }
+
+ 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;
+ }
+
+ identity() {
+ return this.set(0, 0, 0, 1);
+ }
+
+ invert() {
+ // quaternion is assumed to have unit length
+ return this.conjugate();
+ }
+
+ conjugate() {
+ this._x *= -1;
+ this._y *= -1;
+ this._z *= -1;
+
+ this._onChangeCallback();
+
+ return this;
+ }
+
+ dot(v) {
+ return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._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 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;
+ }
+
+ this._onChangeCallback();
+
+ return this;
+ }
+
+ multiply(q, p) {
+ if (p !== undefined) {
+ console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
+ return this.multiplyQuaternions(q, p);
+ }
+
+ return this.multiplyQuaternions(this, q);
+ }
+
+ premultiply(q) {
+ return this.multiplyQuaternions(q, this);
+ }
+
+ multiplyQuaternions(a, b) {
+ // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
+ 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;
+ }
+
+ slerp(qb, t) {
+ if (t === 0) return this;
+ if (t === 1) return this.copy(qb);
+ const x = this._x,
+ y = this._y,
+ z = this._z,
+ w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
+
+ let 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;
+ }
+
+ const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
+
+ if (sqrSinHalfTheta <= Number.EPSILON) {
+ const s = 1 - t;
+ this._w = s * w + t * this._w;
+ this._x = s * x + t * this._x;
+ this._y = s * y + t * this._y;
+ this._z = s * z + t * this._z;
+ this.normalize();
+
+ this._onChangeCallback();
+
+ return this;
+ }
+
+ const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
+ const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
+ const 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._onChangeCallback();
+
+ return this;
+ }
+
+ slerpQuaternions(qa, qb, t) {
+ return this.copy(qa).slerp(qb, t);
+ }
+
+ random() {
+ // Derived from http://planning.cs.uiuc.edu/node198.html
+ // Note, this source uses w, x, y, z ordering,
+ // so we swap the order below.
+ const u1 = Math.random();
+ const sqrt1u1 = Math.sqrt(1 - u1);
+ const sqrtu1 = Math.sqrt(u1);
+ const u2 = 2 * Math.PI * Math.random();
+ const u3 = 2 * Math.PI * Math.random();
+ return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
+ }
+
+ equals(quaternion) {
+ return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ _onChange(callback) {
+ this._onChangeCallback = callback;
+ return this;
+ }
+
+ _onChangeCallback() {}
+
+}
+
+Quaternion.prototype.isQuaternion = true;
+
+class Vector3 {
+ constructor(x = 0, y = 0, z = 0) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ }
+
+ set(x, y, z) {
+ if (z === undefined) z = this.z; // sprite.scale.set(x,y)
+
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ return this;
+ }
+
+ setScalar(scalar) {
+ this.x = scalar;
+ this.y = scalar;
+ this.z = scalar;
+ return this;
+ }
+
+ setX(x) {
+ this.x = x;
+ return this;
+ }
+
+ setY(y) {
+ this.y = y;
+ return this;
+ }
+
+ setZ(z) {
+ this.z = z;
+ return this;
+ }
+
+ setComponent(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);
+ }
+
+ return this;
+ }
+
+ getComponent(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);
+ }
+ }
+
+ clone() {
+ return new this.constructor(this.x, this.y, this.z);
+ }
+
+ copy(v) {
+ this.x = v.x;
+ this.y = v.y;
+ this.z = v.z;
+ return this;
+ }
+
+ add(v, w) {
+ if (w !== undefined) {
+ console.warn('THREE.Vector3: .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(s) {
+ this.x += s;
+ this.y += s;
+ this.z += s;
+ return this;
+ }
+
+ addVectors(a, b) {
+ this.x = a.x + b.x;
+ this.y = a.y + b.y;
+ this.z = a.z + b.z;
+ return this;
+ }
+
+ addScaledVector(v, s) {
+ this.x += v.x * s;
+ this.y += v.y * s;
+ this.z += v.z * s;
+ return this;
+ }
+
+ sub(v, w) {
+ if (w !== undefined) {
+ console.warn('THREE.Vector3: .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;
+ }
+
+ subScalar(s) {
+ this.x -= s;
+ this.y -= s;
+ this.z -= s;
+ return this;
+ }
+
+ subVectors(a, b) {
+ this.x = a.x - b.x;
+ this.y = a.y - b.y;
+ this.z = a.z - b.z;
+ return this;
+ }
+
+ multiply(v, w) {
+ if (w !== undefined) {
+ console.warn('THREE.Vector3: .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(scalar) {
+ this.x *= scalar;
+ this.y *= scalar;
+ this.z *= scalar;
+ return this;
+ }
+
+ multiplyVectors(a, b) {
+ this.x = a.x * b.x;
+ this.y = a.y * b.y;
+ this.z = a.z * b.z;
+ return this;
+ }
+
+ applyEuler(euler) {
+ if (!(euler && euler.isEuler)) {
+ console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
+ }
+
+ return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
+ }
+
+ applyAxisAngle(axis, angle) {
+ return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
+ }
+
+ applyMatrix3(m) {
+ const x = this.x,
+ y = this.y,
+ z = this.z;
+ const 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;
+ }
+
+ applyNormalMatrix(m) {
+ return this.applyMatrix3(m).normalize();
+ }
+
+ applyMatrix4(m) {
+ const x = this.x,
+ y = this.y,
+ z = this.z;
+ const e = m.elements;
+ const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
+ 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;
+ return this;
+ }
+
+ applyQuaternion(q) {
+ const x = this.x,
+ y = this.y,
+ z = this.z;
+ const qx = q.x,
+ qy = q.y,
+ qz = q.z,
+ qw = q.w; // calculate quat * vector
+
+ const ix = qw * x + qy * z - qz * y;
+ const iy = qw * y + qz * x - qx * z;
+ const iz = qw * z + qx * y - qy * x;
+ const 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;
+ }
+
+ project(camera) {
+ return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
+ }
+
+ unproject(camera) {
+ return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
+ }
+
+ transformDirection(m) {
+ // input: THREE.Matrix4 affine matrix
+ // vector interpreted as a direction
+ const x = this.x,
+ y = this.y,
+ z = this.z;
+ const 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;
+ return this.normalize();
+ }
+
+ divide(v) {
+ this.x /= v.x;
+ this.y /= v.y;
+ this.z /= v.z;
+ return this;
+ }
+
+ divideScalar(scalar) {
+ return this.multiplyScalar(1 / scalar);
+ }
+
+ 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);
+ return this;
+ }
+
+ 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);
+ return this;
+ }
+
+ clamp(min, max) {
+ // assumes min < max, componentwise
+ this.x = Math.max(min.x, Math.min(max.x, this.x));
+ this.y = Math.max(min.y, Math.min(max.y, this.y));
+ this.z = Math.max(min.z, Math.min(max.z, this.z));
+ return this;
+ }
+
+ clampScalar(minVal, maxVal) {
+ this.x = Math.max(minVal, Math.min(maxVal, this.x));
+ this.y = Math.max(minVal, Math.min(maxVal, this.y));
+ this.z = Math.max(minVal, Math.min(maxVal, this.z));
+ return this;
+ }
+
+ clampLength(min, max) {
+ const length = this.length();
+ return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
+ }
+
+ floor() {
+ this.x = Math.floor(this.x);
+ this.y = Math.floor(this.y);
+ this.z = Math.floor(this.z);
+ return this;
+ }
+
+ ceil() {
+ this.x = Math.ceil(this.x);
+ this.y = Math.ceil(this.y);
+ this.z = Math.ceil(this.z);
+ return this;
+ }
+
+ round() {
+ this.x = Math.round(this.x);
+ this.y = Math.round(this.y);
+ this.z = Math.round(this.z);
+ return this;
+ }
+
+ roundToZero() {
+ 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() {
+ this.x = -this.x;
+ this.y = -this.y;
+ this.z = -this.z;
+ return this;
+ }
+
+ dot(v) {
+ return this.x * v.x + this.y * v.y + this.z * v.z;
+ } // TODO lengthSquared?
+
+
+ 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(length) {
+ return this.normalize().multiplyScalar(length);
+ }
+
+ lerp(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;
+ }
+
+ 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;
+ return this;
+ }
+
+ cross(v, w) {
+ if (w !== undefined) {
+ console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
+ return this.crossVectors(v, w);
+ }
+
+ return this.crossVectors(this, v);
+ }
+
+ crossVectors(a, b) {
+ const ax = a.x,
+ ay = a.y,
+ az = a.z;
+ const 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(v) {
+ const denominator = v.lengthSq();
+ if (denominator === 0) return this.set(0, 0, 0);
+ const scalar = v.dot(this) / denominator;
+ return this.copy(v).multiplyScalar(scalar);
+ }
+
+ projectOnPlane(planeNormal) {
+ _vector$c.copy(this).projectOnVector(planeNormal);
+
+ return this.sub(_vector$c);
+ }
+
+ reflect(normal) {
+ // reflect incident vector off plane orthogonal to normal
+ // normal is assumed to have unit length
+ return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
+ }
+
+ angleTo(v) {
+ const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
+ if (denominator === 0) return Math.PI / 2;
+ const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
+
+ return Math.acos(clamp(theta, -1, 1));
+ }
+
+ distanceTo(v) {
+ return Math.sqrt(this.distanceToSquared(v));
+ }
+
+ distanceToSquared(v) {
+ const dx = this.x - v.x,
+ dy = this.y - v.y,
+ dz = this.z - v.z;
+ return dx * dx + dy * dy + dz * dz;
+ }
+
+ manhattanDistanceTo(v) {
+ return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
+ }
+
+ setFromSpherical(s) {
+ return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
+ }
+
+ setFromSphericalCoords(radius, phi, theta) {
+ const sinPhiRadius = Math.sin(phi) * radius;
+ this.x = sinPhiRadius * Math.sin(theta);
+ this.y = Math.cos(phi) * radius;
+ this.z = sinPhiRadius * Math.cos(theta);
+ return this;
+ }
+
+ setFromCylindrical(c) {
+ return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
+ }
+
+ setFromCylindricalCoords(radius, theta, y) {
+ this.x = radius * Math.sin(theta);
+ this.y = y;
+ this.z = radius * Math.cos(theta);
+ return this;
+ }
+
+ setFromMatrixPosition(m) {
+ const e = m.elements;
+ this.x = e[12];
+ this.y = e[13];
+ this.z = e[14];
+ return this;
+ }
+
+ setFromMatrixScale(m) {
+ const sx = this.setFromMatrixColumn(m, 0).length();
+ const sy = this.setFromMatrixColumn(m, 1).length();
+ const sz = this.setFromMatrixColumn(m, 2).length();
+ this.x = sx;
+ this.y = sy;
+ this.z = sz;
+ return this;
+ }
+
+ setFromMatrixColumn(m, index) {
+ return this.fromArray(m.elements, index * 4);
+ }
+
+ setFromMatrix3Column(m, index) {
+ return this.fromArray(m.elements, index * 3);
+ }
+
+ equals(v) {
+ return v.x === this.x && v.y === this.y && v.z === this.z;
+ }
+
+ fromArray(array, offset = 0) {
+ this.x = array[offset];
+ this.y = array[offset + 1];
+ this.z = array[offset + 2];
+ return this;
+ }
+
+ toArray(array = [], offset = 0) {
+ array[offset] = this.x;
+ array[offset + 1] = this.y;
+ array[offset + 2] = this.z;
+ return array;
+ }
+
+ fromBufferAttribute(attribute, index, offset) {
+ if (offset !== undefined) {
+ console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
+ }
+
+ this.x = attribute.getX(index);
+ this.y = attribute.getY(index);
+ this.z = attribute.getZ(index);
+ return this;
+ }
+
+ random() {
+ this.x = Math.random();
+ this.y = Math.random();
+ this.z = Math.random();
+ return this;
+ }
+
+ randomDirection() {
+ // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
+ const u = (Math.random() - 0.5) * 2;
+ const t = Math.random() * Math.PI * 2;
+ const f = Math.sqrt(1 - u ** 2);
+ this.x = f * Math.cos(t);
+ this.y = f * Math.sin(t);
+ this.z = u;
+ return this;
+ }
+
+ *[Symbol.iterator]() {
+ yield this.x;
+ yield this.y;
+ yield this.z;
+ }
+
+}
+
+Vector3.prototype.isVector3 = true;
+
+const _vector$c = /*@__PURE__*/new Vector3();
+
+const _quaternion$4 = /*@__PURE__*/new Quaternion();
+
+class Box3 {
+ constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
+ this.min = min;
+ this.max = max;
+ }
+
+ set(min, max) {
+ this.min.copy(min);
+ this.max.copy(max);
+ return this;
+ }
+
+ setFromArray(array) {
+ let minX = +Infinity;
+ let minY = +Infinity;
+ let minZ = +Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ let maxZ = -Infinity;
+
+ for (let i = 0, l = array.length; i < l; i += 3) {
+ const x = array[i];
+ const y = array[i + 1];
+ const z = array[i + 2];
+ if (x < minX) minX = x;
+ if (y < minY) minY = y;
+ if (z < minZ) minZ = z;
+ if (x > maxX) maxX = x;
+ if (y > maxY) maxY = y;
+ if (z > maxZ) maxZ = z;
+ }
+
+ this.min.set(minX, minY, minZ);
+ this.max.set(maxX, maxY, maxZ);
+ return this;
+ }
+
+ setFromBufferAttribute(attribute) {
+ let minX = +Infinity;
+ let minY = +Infinity;
+ let minZ = +Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ let maxZ = -Infinity;
+
+ for (let i = 0, l = attribute.count; i < l; i++) {
+ const x = attribute.getX(i);
+ const y = attribute.getY(i);
+ const z = attribute.getZ(i);
+ if (x < minX) minX = x;
+ if (y < minY) minY = y;
+ if (z < minZ) minZ = z;
+ if (x > maxX) maxX = x;
+ if (y > maxY) maxY = y;
+ if (z > maxZ) maxZ = z;
+ }
+
+ this.min.set(minX, minY, minZ);
+ this.max.set(maxX, maxY, maxZ);
+ return this;
+ }
+
+ setFromPoints(points) {
+ this.makeEmpty();
+
+ for (let i = 0, il = points.length; i < il; i++) {
+ this.expandByPoint(points[i]);
+ }
+
+ return this;
+ }
+
+ 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;
+ }
+
+ setFromObject(object, precise = false) {
+ this.makeEmpty();
+ return this.expandByObject(object, precise);
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+ copy(box) {
+ this.min.copy(box.min);
+ this.max.copy(box.max);
+ return this;
+ }
+
+ makeEmpty() {
+ this.min.x = this.min.y = this.min.z = +Infinity;
+ this.max.x = this.max.y = this.max.z = -Infinity;
+ return this;
+ }
+
+ isEmpty() {
+ // 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;
+ }
+
+ getCenter(target) {
+ return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
+ }
+
+ getSize(target) {
+ return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
+ }
+
+ expandByPoint(point) {
+ this.min.min(point);
+ this.max.max(point);
+ return this;
+ }
+
+ expandByVector(vector) {
+ this.min.sub(vector);
+ this.max.add(vector);
+ return this;
+ }
+
+ expandByScalar(scalar) {
+ this.min.addScalar(-scalar);
+ this.max.addScalar(scalar);
+ return this;
+ }
+
+ expandByObject(object, precise = false) {
+ // Computes the world-axis-aligned bounding box of an object (including its children),
+ // accounting for both the object's, and children's, world transforms
+ object.updateWorldMatrix(false, false);
+ const geometry = object.geometry;
+
+ if (geometry !== undefined) {
+ if (precise && geometry.attributes != undefined && geometry.attributes.position !== undefined) {
+ const position = geometry.attributes.position;
+
+ for (let i = 0, l = position.count; i < l; i++) {
+ _vector$b.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
+
+ this.expandByPoint(_vector$b);
+ }
+ } else {
+ if (geometry.boundingBox === null) {
+ geometry.computeBoundingBox();
+ }
+
+ _box$3.copy(geometry.boundingBox);
+
+ _box$3.applyMatrix4(object.matrixWorld);
+
+ this.union(_box$3);
+ }
+ }
+
+ const children = object.children;
+
+ for (let i = 0, l = children.length; i < l; i++) {
+ this.expandByObject(children[i], precise);
+ }
+
+ return this;
+ }
+
+ containsPoint(point) {
+ return 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 ? false : true;
+ }
+
+ 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;
+ }
+
+ getParameter(point, target) {
+ // This can potentially have a divide by zero if the box
+ // has a size dimension of 0.
+ return target.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));
+ }
+
+ intersectsBox(box) {
+ // using 6 splitting planes to rule out intersections.
+ 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 ? false : true;
+ }
+
+ intersectsSphere(sphere) {
+ // Find the point on the AABB closest to the sphere center.
+ this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
+
+ return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
+ }
+
+ intersectsPlane(plane) {
+ // We compute the minimum and maximum dot product values. If those values
+ // are on the same side (back or front) of the plane, then there is no intersection.
+ 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;
+ }
+
+ intersectsTriangle(triangle) {
+ if (this.isEmpty()) {
+ return false;
+ } // compute box center and extents
+
+
+ this.getCenter(_center);
+
+ _extents.subVectors(this.max, _center); // translate triangle to aabb origin
+
+
+ _v0$2.subVectors(triangle.a, _center);
+
+ _v1$7.subVectors(triangle.b, _center);
+
+ _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
+
+
+ _f0.subVectors(_v1$7, _v0$2);
+
+ _f1.subVectors(_v2$3, _v1$7);
+
+ _f2.subVectors(_v0$2, _v2$3); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
+ // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
+ // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
+
+
+ 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$7, _v2$3, _extents)) {
+ return false;
+ } // test 3 face normals from the aabb
+
+
+ axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
+
+ if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
+ return false;
+ } // finally testing the face normal of the triangle
+ // use already existing triangle edge vectors here
+
+
+ _triangleNormal.crossVectors(_f0, _f1);
+
+ axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
+ return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
+ }
+
+ clampPoint(point, target) {
+ return target.copy(point).clamp(this.min, this.max);
+ }
+
+ distanceToPoint(point) {
+ const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
+
+ return clampedPoint.sub(point).length();
+ }
+
+ getBoundingSphere(target) {
+ this.getCenter(target.center);
+ target.radius = this.getSize(_vector$b).length() * 0.5;
+ return target;
+ }
+
+ intersect(box) {
+ this.min.max(box.min);
+ this.max.min(box.max); // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
+
+ if (this.isEmpty()) this.makeEmpty();
+ return this;
+ }
+
+ union(box) {
+ this.min.min(box.min);
+ this.max.max(box.max);
+ return this;
+ }
+
+ applyMatrix4(matrix) {
+ // transform of empty box is an empty box.
+ if (this.isEmpty()) return this; // 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.setFromPoints(_points);
+ return this;
+ }
+
+ translate(offset) {
+ this.min.add(offset);
+ this.max.add(offset);
+ return this;
+ }
+
+ equals(box) {
+ return box.min.equals(this.min) && box.max.equals(this.max);
+ }
+
+}
+
+Box3.prototype.isBox3 = true;
+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$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
+
+
+const _v0$2 = /*@__PURE__*/new Vector3();
+
+const _v1$7 = /*@__PURE__*/new Vector3();
+
+const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
+
+
+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); // project the aabb onto the seperating axis
+
+
+ const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the seperating axis
+
+ const p0 = v0.dot(_testAxis);
+ const p1 = v1.dot(_testAxis);
+ const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
+
+ if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
+ // points of the projected triangle are outside the projected half-length of the aabb
+ // the axis is seperating and we can exit
+ return false;
+ }
+ }
+
+ return true;
+}
+
+const _box$2 = /*@__PURE__*/new Box3();
+
+const _v1$6 = /*@__PURE__*/new Vector3();
+
+const _toFarthestPoint = /*@__PURE__*/new Vector3();
+
+const _toPoint = /*@__PURE__*/new Vector3();
+
+class Sphere {
+ constructor(center = new Vector3(), radius = -1) {
+ this.center = center;
+ this.radius = radius;
+ }
+
+ set(center, radius) {
+ this.center.copy(center);
+ this.radius = radius;
+ return this;
+ }
+
+ setFromPoints(points, optionalCenter) {
+ const center = this.center;
+
+ if (optionalCenter !== undefined) {
+ center.copy(optionalCenter);
+ } else {
+ _box$2.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;
+ }
+
+ copy(sphere) {
+ this.center.copy(sphere.center);
+ this.radius = sphere.radius;
+ return this;
+ }
+
+ isEmpty() {
+ return this.radius < 0;
+ }
+
+ makeEmpty() {
+ this.center.set(0, 0, 0);
+ this.radius = -1;
+ return this;
+ }
+
+ containsPoint(point) {
+ return point.distanceToSquared(this.center) <= this.radius * this.radius;
+ }
+
+ distanceToPoint(point) {
+ return point.distanceTo(this.center) - this.radius;
+ }
+
+ intersectsSphere(sphere) {
+ const radiusSum = this.radius + sphere.radius;
+ return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
+ }
+
+ intersectsBox(box) {
+ return box.intersectsSphere(this);
+ }
+
+ intersectsPlane(plane) {
+ return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
+ }
+
+ clampPoint(point, target) {
+ const deltaLengthSq = this.center.distanceToSquared(point);
+ target.copy(point);
+
+ if (deltaLengthSq > this.radius * this.radius) {
+ target.sub(this.center).normalize();
+ target.multiplyScalar(this.radius).add(this.center);
+ }
+
+ return target;
+ }
+
+ getBoundingBox(target) {
+ if (this.isEmpty()) {
+ // Empty sphere produces empty bounding box
+ target.makeEmpty();
+ return target;
+ }
+
+ target.set(this.center, this.center);
+ target.expandByScalar(this.radius);
+ return target;
+ }
+
+ applyMatrix4(matrix) {
+ this.center.applyMatrix4(matrix);
+ this.radius = this.radius * matrix.getMaxScaleOnAxis();
+ return this;
+ }
+
+ translate(offset) {
+ this.center.add(offset);
+ return this;
+ }
+
+ expandByPoint(point) {
+ // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
+ _toPoint.subVectors(point, this.center);
+
+ const lengthSq = _toPoint.lengthSq();
+
+ if (lengthSq > this.radius * this.radius) {
+ const length = Math.sqrt(lengthSq);
+ const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
+ // and the other half to position. This gives a tighter enclosure, instead of if
+ // the whole missing distance were just added to radius.
+
+ this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
+ this.radius += missingRadiusHalf;
+ }
+
+ return this;
+ }
+
+ union(sphere) {
+ // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
+ // To enclose another sphere into this sphere, we only need to enclose two points:
+ // 1) Enclose the farthest point on the other sphere into this sphere.
+ // 2) Enclose the opposite point of the farthest point into this sphere.
+ if (this.center.equals(sphere.center) === true) {
+ _toFarthestPoint.set(0, 0, 1).multiplyScalar(sphere.radius);
+ } else {
+ _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
+ }
+
+ this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
+ this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
+ return this;
+ }
+
+ equals(sphere) {
+ return sphere.center.equals(this.center) && sphere.radius === this.radius;
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+}
+
+const _vector$a = /*@__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 {
+ constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
+ this.origin = origin;
+ this.direction = direction;
+ }
+
+ set(origin, direction) {
+ this.origin.copy(origin);
+ this.direction.copy(direction);
+ return this;
+ }
+
+ copy(ray) {
+ this.origin.copy(ray.origin);
+ this.direction.copy(ray.direction);
+ return this;
+ }
+
+ at(t, target) {
+ return target.copy(this.direction).multiplyScalar(t).add(this.origin);
+ }
+
+ lookAt(v) {
+ this.direction.copy(v).sub(this.origin).normalize();
+ return this;
+ }
+
+ recast(t) {
+ this.origin.copy(this.at(t, _vector$a));
+ return this;
+ }
+
+ closestPointToPoint(point, target) {
+ target.subVectors(point, this.origin);
+ const directionDistance = target.dot(this.direction);
+
+ if (directionDistance < 0) {
+ return target.copy(this.origin);
+ }
+
+ return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
+ }
+
+ distanceToPoint(point) {
+ return Math.sqrt(this.distanceSqToPoint(point));
+ }
+
+ distanceSqToPoint(point) {
+ const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
+
+
+ if (directionDistance < 0) {
+ return this.origin.distanceToSquared(point);
+ }
+
+ _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
+
+ return _vector$a.distanceToSquared(point);
+ }
+
+ distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
+ // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
+ // 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
+ _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) {
+ // 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.
+ const 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).multiplyScalar(s0).add(this.origin);
+ }
+
+ if (optionalPointOnSegment) {
+ optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
+ }
+
+ return sqrDist;
+ }
+
+ intersectSphere(sphere, target) {
+ _vector$a.subVectors(sphere.center, this.origin);
+
+ const tca = _vector$a.dot(this.direction);
+
+ const d2 = _vector$a.dot(_vector$a) - tca * tca;
+ const radius2 = sphere.radius * sphere.radius;
+ if (d2 > radius2) return null;
+ const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
+
+ const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
+
+ const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
+
+ if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
+ // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
+ // in order to always return an intersect point that is in front of the ray.
+
+ if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0
+
+ return this.at(t0, target);
+ }
+
+ intersectsSphere(sphere) {
+ return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
+ }
+
+ distanceToPlane(plane) {
+ const 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;
+ }
+
+ const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
+
+ return t >= 0 ? t : null;
+ }
+
+ intersectPlane(plane, target) {
+ const t = this.distanceToPlane(plane);
+
+ if (t === null) {
+ return null;
+ }
+
+ return this.at(t, target);
+ }
+
+ intersectsPlane(plane) {
+ // check if the ray lies on the plane first
+ const distToPoint = plane.distanceToPoint(this.origin);
+
+ if (distToPoint === 0) {
+ return true;
+ }
+
+ const 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;
+ }
+
+ 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; // 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, target);
+ }
+
+ intersectsBox(box) {
+ return this.intersectBox(box, _vector$a) !== null;
+ }
+
+ intersectTriangle(a, b, c, backfaceCulling, target) {
+ // Compute the offset origin, edges, and normal.
+ // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
+ _edge1.subVectors(b, a);
+
+ _edge2.subVectors(c, a);
+
+ _normal$1.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)
+
+
+ let DdN = this.direction.dot(_normal$1);
+ let 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);
+
+ const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
+
+ if (DdQxE2 < 0) {
+ return null;
+ }
+
+ const 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.
+
+
+ const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
+
+
+ if (QdN < 0) {
+ return null;
+ } // Ray intersects triangle.
+
+
+ return this.at(QdN / DdN, target);
+ }
+
+ applyMatrix4(matrix4) {
+ this.origin.applyMatrix4(matrix4);
+ this.direction.transformDirection(matrix4);
+ return this;
+ }
+
+ equals(ray) {
+ return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+}
+
+class Matrix4 {
+ constructor() {
+ this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+
+ if (arguments.length > 0) {
+ console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
+ }
+ }
+
+ 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;
+ }
+
+ identity() {
+ this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
+ return this;
+ }
+
+ clone() {
+ return new Matrix4().fromArray(this.elements);
+ }
+
+ 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;
+ }
+
+ copyPosition(m) {
+ const te = this.elements,
+ me = m.elements;
+ te[12] = me[12];
+ te[13] = me[13];
+ te[14] = me[14];
+ return this;
+ }
+
+ 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;
+ }
+
+ extractBasis(xAxis, yAxis, zAxis) {
+ xAxis.setFromMatrixColumn(this, 0);
+ yAxis.setFromMatrixColumn(this, 1);
+ zAxis.setFromMatrixColumn(this, 2);
+ return this;
+ }
+
+ 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;
+ }
+
+ extractRotation(m) {
+ // this method does not support reflection matrices
+ const te = this.elements;
+ const me = m.elements;
+
+ const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
+
+ const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
+
+ const scaleZ = 1 / _v1$5.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;
+ }
+
+ makeRotationFromEuler(euler) {
+ if (!(euler && euler.isEuler)) {
+ console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
+ }
+
+ 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;
+ } // bottom row
+
+
+ te[3] = 0;
+ te[7] = 0;
+ te[11] = 0; // last column
+
+ te[12] = 0;
+ te[13] = 0;
+ te[14] = 0;
+ te[15] = 1;
+ return this;
+ }
+
+ makeRotationFromQuaternion(q) {
+ return this.compose(_zero, q, _one);
+ }
+
+ lookAt(eye, target, up) {
+ const te = this.elements;
+
+ _z.subVectors(eye, target);
+
+ if (_z.lengthSq() === 0) {
+ // eye and target are in the same position
+ _z.z = 1;
+ }
+
+ _z.normalize();
+
+ _x.crossVectors(up, _z);
+
+ if (_x.lengthSq() === 0) {
+ // up and z are parallel
+ if (Math.abs(up.z) === 1) {
+ _z.x += 0.0001;
+ } else {
+ _z.z += 0.0001;
+ }
+
+ _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;
+ }
+
+ multiply(m, n) {
+ if (n !== undefined) {
+ console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
+ return this.multiplyMatrices(m, n);
+ }
+
+ return this.multiplyMatrices(this, m);
+ }
+
+ premultiply(m) {
+ return this.multiplyMatrices(m, this);
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ 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]; //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() {
+ const te = this.elements;
+ let 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;
+ }
+
+ 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;
+ }
+
+ invert() {
+ // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
+ 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],
+ t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
+ t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
+ t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
+ t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
+ const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
+ 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] = t11 * detInv;
+ te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
+ te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
+ te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
+ te[4] = t12 * detInv;
+ te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
+ te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
+ te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
+ te[8] = t13 * detInv;
+ te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
+ te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
+ te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
+ te[12] = t14 * detInv;
+ te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
+ te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
+ te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
+ return this;
+ }
+
+ 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;
+ }
+
+ 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));
+ }
+
+ makeTranslation(x, y, z) {
+ this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
+ return this;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ makeRotationAxis(axis, angle) {
+ // Based on http://www.gamedev.net/reference/articles/article1199.asp
+ 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;
+ }
+
+ makeScale(x, y, z) {
+ this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
+ return this;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ decompose(position, quaternion, scale) {
+ const te = this.elements;
+
+ let sx = _v1$5.set(te[0], te[1], te[2]).length();
+
+ const sy = _v1$5.set(te[4], te[5], te[6]).length();
+
+ const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
+
+
+ const det = this.determinant();
+ if (det < 0) sx = -sx;
+ position.x = te[12];
+ position.y = te[13];
+ position.z = te[14]; // scale the rotation part
+
+ _m1$2.copy(this);
+
+ const invSX = 1 / sx;
+ const invSY = 1 / sy;
+ const invSZ = 1 / sz;
+ _m1$2.elements[0] *= invSX;
+ _m1$2.elements[1] *= invSX;
+ _m1$2.elements[2] *= invSX;
+ _m1$2.elements[4] *= invSY;
+ _m1$2.elements[5] *= invSY;
+ _m1$2.elements[6] *= invSY;
+ _m1$2.elements[8] *= invSZ;
+ _m1$2.elements[9] *= invSZ;
+ _m1$2.elements[10] *= invSZ;
+ quaternion.setFromRotationMatrix(_m1$2);
+ scale.x = sx;
+ scale.y = sy;
+ scale.z = sz;
+ return this;
+ }
+
+ makePerspective(left, right, top, bottom, near, far) {
+ if (far === undefined) {
+ console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
+ }
+
+ 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);
+ const c = -(far + near) / (far - near);
+ const 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;
+ }
+
+ makeOrthographic(left, right, top, bottom, near, far) {
+ const te = this.elements;
+ const w = 1.0 / (right - left);
+ const h = 1.0 / (top - bottom);
+ const p = 1.0 / (far - near);
+ const x = (right + left) * w;
+ const y = (top + bottom) * h;
+ const 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;
+ }
+
+ 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;
+ }
+
+ fromArray(array, offset = 0) {
+ for (let i = 0; i < 16; i++) {
+ this.elements[i] = array[i + offset];
+ }
+
+ return this;
+ }
+
+ 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;
+
+const _v1$5 = /*@__PURE__*/new Vector3();
+
+const _m1$2 = /*@__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$1 = /*@__PURE__*/new Matrix4();
+
+const _quaternion$3 = /*@__PURE__*/new Quaternion();
+
+class Euler {
+ constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
+ this._x = x;
+ this._y = y;
+ this._z = z;
+ this._order = order;
+ }
+
+ get x() {
+ return this._x;
+ }
+
+ set x(value) {
+ this._x = value;
+
+ this._onChangeCallback();
+ }
+
+ get y() {
+ return this._y;
+ }
+
+ set y(value) {
+ this._y = value;
+
+ this._onChangeCallback();
+ }
+
+ get z() {
+ return this._z;
+ }
+
+ set z(value) {
+ this._z = value;
+
+ this._onChangeCallback();
+ }
+
+ get order() {
+ return this._order;
+ }
+
+ set order(value) {
+ this._order = value;
+
+ this._onChangeCallback();
+ }
+
+ set(x, y, z, order = this._order) {
+ this._x = x;
+ this._y = y;
+ this._z = z;
+ this._order = order;
+
+ this._onChangeCallback();
+
+ return this;
+ }
+
+ clone() {
+ return new this.constructor(this._x, this._y, this._z, this._order);
+ }
+
+ copy(euler) {
+ this._x = euler._x;
+ this._y = euler._y;
+ this._z = euler._z;
+ this._order = euler._order;
+
+ this._onChangeCallback();
+
+ return this;
+ }
+
+ setFromRotationMatrix(m, order = this._order, update = true) {
+ // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
+ 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;
+ }
+
+ break;
+
+ case 'YXZ':
+ this._x = Math.asin(-clamp(m23, -1, 1));
+
+ if (Math.abs(m23) < 0.9999999) {
+ this._y = Math.atan2(m13, m33);
+ this._z = Math.atan2(m21, m22);
+ } else {
+ this._y = Math.atan2(-m31, m11);
+ this._z = 0;
+ }
+
+ 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);
+ }
+
+ 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);
+ }
+
+ break;
+
+ case 'YZX':
+ this._z = Math.asin(clamp(m21, -1, 1));
+
+ if (Math.abs(m21) < 0.9999999) {
+ this._x = Math.atan2(-m23, m22);
+ this._y = Math.atan2(-m31, m11);
+ } else {
+ this._x = 0;
+ this._y = Math.atan2(m13, m33);
+ }
+
+ break;
+
+ case 'XZY':
+ this._z = Math.asin(-clamp(m12, -1, 1));
+
+ if (Math.abs(m12) < 0.9999999) {
+ this._x = Math.atan2(m32, m22);
+ this._y = Math.atan2(m13, m11);
+ } else {
+ this._x = Math.atan2(-m23, m33);
+ this._y = 0;
+ }
+
+ break;
+
+ default:
+ console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
+ }
+
+ this._order = order;
+ if (update === true) this._onChangeCallback();
+ return this;
+ }
+
+ setFromQuaternion(q, order, update) {
+ _matrix$1.makeRotationFromQuaternion(q);
+
+ return this.setFromRotationMatrix(_matrix$1, order, update);
+ }
+
+ setFromVector3(v, order = this._order) {
+ return this.set(v.x, v.y, v.z, order);
+ }
+
+ reorder(newOrder) {
+ // WARNING: this discards revolution information -bhouston
+ _quaternion$3.setFromEuler(this);
+
+ return this.setFromQuaternion(_quaternion$3, newOrder);
+ }
+
+ equals(euler) {
+ return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
+ }
+
+ fromArray(array) {
+ this._x = array[0];
+ this._y = array[1];
+ this._z = array[2];
+ if (array[3] !== undefined) this._order = array[3];
+
+ this._onChangeCallback();
+
+ return this;
+ }
+
+ 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;
+ }
+
+ toVector3(optionalResult) {
+ if (optionalResult) {
+ return optionalResult.set(this._x, this._y, this._z);
+ } else {
+ return new Vector3(this._x, this._y, this._z);
+ }
+ }
+
+ _onChange(callback) {
+ this._onChangeCallback = callback;
+ return this;
+ }
+
+ _onChangeCallback() {}
+
+}
+
+Euler.prototype.isEuler = true;
+Euler.DefaultOrder = 'XYZ';
+Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
+
+class Layers {
+ constructor() {
+ this.mask = 1 | 0;
+ }
+
+ set(channel) {
+ this.mask = (1 << channel | 0) >>> 0;
+ }
+
+ enable(channel) {
+ this.mask |= 1 << channel | 0;
+ }
+
+ enableAll() {
+ this.mask = 0xffffffff | 0;
+ }
+
+ toggle(channel) {
+ this.mask ^= 1 << channel | 0;
+ }
+
+ disable(channel) {
+ this.mask &= ~(1 << channel | 0);
+ }
+
+ disableAll() {
+ this.mask = 0;
+ }
+
+ test(layers) {
+ return (this.mask & layers.mask) !== 0;
+ }
+
+ isEnabled(channel) {
+ return (this.mask & (1 << channel | 0)) !== 0;
+ }
+
+}
+
+let _object3DId = 0;
+
+const _v1$4 = /*@__PURE__*/new Vector3();
+
+const _q1 = /*@__PURE__*/new Quaternion();
+
+const _m1$1 = /*@__PURE__*/new Matrix4();
+
+const _target = /*@__PURE__*/new Vector3();
+
+const _position$3 = /*@__PURE__*/new Vector3();
+
+const _scale$2 = /*@__PURE__*/new Vector3();
+
+const _quaternion$2 = /*@__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'
+};
+
+class Object3D extends EventDispatcher {
+ constructor() {
+ super();
+ Object.defineProperty(this, 'id', {
+ value: _object3DId++
+ });
+ this.uuid = generateUUID();
+ this.name = '';
+ this.type = 'Object3D';
+ this.parent = null;
+ this.children = [];
+ this.up = Object3D.DefaultUp.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, undefined, false);
+ }
+
+ rotation._onChange(onRotationChange);
+
+ quaternion._onChange(onQuaternionChange);
+
+ Object.defineProperties(this, {
+ position: {
+ configurable: true,
+ enumerable: true,
+ value: position
+ },
+ rotation: {
+ configurable: true,
+ enumerable: true,
+ value: rotation
+ },
+ quaternion: {
+ configurable: true,
+ enumerable: true,
+ value: quaternion
+ },
+ scale: {
+ configurable: true,
+ enumerable: true,
+ value: scale
+ },
+ modelViewMatrix: {
+ value: new Matrix4()
+ },
+ normalMatrix: {
+ value: new Matrix3()
+ }
+ });
+ this.matrix = new Matrix4();
+ this.matrixWorld = new Matrix4();
+ this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
+ 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.userData = {};
+ }
+
+ onBeforeRender() {}
+
+ onAfterRender() {}
+
+ applyMatrix4(matrix) {
+ if (this.matrixAutoUpdate) this.updateMatrix();
+ this.matrix.premultiply(matrix);
+ this.matrix.decompose(this.position, this.quaternion, this.scale);
+ }
+
+ applyQuaternion(q) {
+ this.quaternion.premultiply(q);
+ return this;
+ }
+
+ setRotationFromAxisAngle(axis, angle) {
+ // assumes axis is normalized
+ this.quaternion.setFromAxisAngle(axis, angle);
+ }
+
+ setRotationFromEuler(euler) {
+ this.quaternion.setFromEuler(euler, true);
+ }
+
+ setRotationFromMatrix(m) {
+ // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
+ this.quaternion.setFromRotationMatrix(m);
+ }
+
+ setRotationFromQuaternion(q) {
+ // assumes q is normalized
+ this.quaternion.copy(q);
+ }
+
+ rotateOnAxis(axis, angle) {
+ // rotate object on axis in object space
+ // axis is assumed to be normalized
+ _q1.setFromAxisAngle(axis, angle);
+
+ this.quaternion.multiply(_q1);
+ return this;
+ }
+
+ rotateOnWorldAxis(axis, angle) {
+ // rotate object on axis in world space
+ // axis is assumed to be normalized
+ // method assumes no rotated parent
+ _q1.setFromAxisAngle(axis, angle);
+
+ this.quaternion.premultiply(_q1);
+ return this;
+ }
+
+ rotateX(angle) {
+ return this.rotateOnAxis(_xAxis, angle);
+ }
+
+ rotateY(angle) {
+ return this.rotateOnAxis(_yAxis, angle);
+ }
+
+ rotateZ(angle) {
+ return this.rotateOnAxis(_zAxis, angle);
+ }
+
+ translateOnAxis(axis, distance) {
+ // translate object by distance along axis in object space
+ // axis is assumed to be normalized
+ _v1$4.copy(axis).applyQuaternion(this.quaternion);
+
+ this.position.add(_v1$4.multiplyScalar(distance));
+ return this;
+ }
+
+ translateX(distance) {
+ return this.translateOnAxis(_xAxis, distance);
+ }
+
+ translateY(distance) {
+ return this.translateOnAxis(_yAxis, distance);
+ }
+
+ translateZ(distance) {
+ return this.translateOnAxis(_zAxis, distance);
+ }
+
+ localToWorld(vector) {
+ return vector.applyMatrix4(this.matrixWorld);
+ }
+
+ worldToLocal(vector) {
+ return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
+ }
+
+ lookAt(x, y, z) {
+ // This method does not support objects having non-uniformly-scaled parent(s)
+ if (x.isVector3) {
+ _target.copy(x);
+ } else {
+ _target.set(x, y, z);
+ }
+
+ const parent = this.parent;
+ this.updateWorldMatrix(true, false);
+
+ _position$3.setFromMatrixPosition(this.matrixWorld);
+
+ if (this.isCamera || this.isLight) {
+ _m1$1.lookAt(_position$3, _target, this.up);
+ } else {
+ _m1$1.lookAt(_target, _position$3, this.up);
+ }
+
+ this.quaternion.setFromRotationMatrix(_m1$1);
+
+ if (parent) {
+ _m1$1.extractRotation(parent.matrixWorld);
+
+ _q1.setFromRotationMatrix(_m1$1);
+
+ this.quaternion.premultiply(_q1.invert());
+ }
+ }
+
+ add(object) {
+ if (arguments.length > 1) {
+ for (let i = 0; i < arguments.length; i++) {
+ this.add(arguments[i]);
+ }
+
+ return this;
+ }
+
+ if (object === this) {
+ console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
+ return this;
+ }
+
+ if (object && object.isObject3D) {
+ if (object.parent !== null) {
+ object.parent.remove(object);
+ }
+
+ object.parent = this;
+ this.children.push(object);
+ object.dispatchEvent(_addedEvent);
+ } else {
+ console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
+ }
+
+ return this;
+ }
+
+ 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);
+ }
+
+ return this;
+ }
+
+ removeFromParent() {
+ const parent = this.parent;
+
+ if (parent !== null) {
+ parent.remove(this);
+ }
+
+ return this;
+ }
+
+ clear() {
+ for (let i = 0; i < this.children.length; i++) {
+ const object = this.children[i];
+ object.parent = null;
+ object.dispatchEvent(_removedEvent);
+ }
+
+ this.children.length = 0;
+ return this;
+ }
+
+ attach(object) {
+ // adds object as a child of this, while maintaining the object's world transform
+ // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
+ this.updateWorldMatrix(true, false);
+
+ _m1$1.copy(this.matrixWorld).invert();
+
+ if (object.parent !== null) {
+ object.parent.updateWorldMatrix(true, false);
+
+ _m1$1.multiply(object.parent.matrixWorld);
+ }
+
+ object.applyMatrix4(_m1$1);
+ this.add(object);
+ object.updateWorldMatrix(false, true);
+ return this;
+ }
+
+ getObjectById(id) {
+ return this.getObjectByProperty('id', id);
+ }
+
+ getObjectByName(name) {
+ return this.getObjectByProperty('name', name);
+ }
+
+ 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 !== undefined) {
+ return object;
+ }
+ }
+
+ return undefined;
+ }
+
+ getWorldPosition(target) {
+ this.updateWorldMatrix(true, false);
+ return target.setFromMatrixPosition(this.matrixWorld);
+ }
+
+ getWorldQuaternion(target) {
+ this.updateWorldMatrix(true, false);
+ this.matrixWorld.decompose(_position$3, target, _scale$2);
+ return target;
+ }
+
+ getWorldScale(target) {
+ this.updateWorldMatrix(true, false);
+ this.matrixWorld.decompose(_position$3, _quaternion$2, target);
+ return target;
+ }
+
+ getWorldDirection(target) {
+ this.updateWorldMatrix(true, false);
+ const e = this.matrixWorld.elements;
+ return target.set(e[8], e[9], e[10]).normalize();
+ }
+
+ raycast() {}
+
+ traverse(callback) {
+ callback(this);
+ const children = this.children;
+
+ for (let i = 0, l = children.length; i < l; i++) {
+ children[i].traverse(callback);
+ }
+ }
+
+ 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);
+ }
+ }
+
+ traverseAncestors(callback) {
+ const parent = this.parent;
+
+ if (parent !== null) {
+ callback(parent);
+ parent.traverseAncestors(callback);
+ }
+ }
+
+ updateMatrix() {
+ this.matrix.compose(this.position, this.quaternion, this.scale);
+ this.matrixWorldNeedsUpdate = true;
+ }
+
+ updateMatrixWorld(force) {
+ if (this.matrixAutoUpdate) this.updateMatrix();
+
+ if (this.matrixWorldNeedsUpdate || force) {
+ if (this.parent === null) {
+ this.matrixWorld.copy(this.matrix);
+ } else {
+ this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
+ }
+
+ this.matrixWorldNeedsUpdate = false;
+ force = true;
+ } // update children
+
+
+ const children = this.children;
+
+ for (let i = 0, l = children.length; i < l; i++) {
+ children[i].updateMatrixWorld(force);
+ }
+ }
+
+ updateWorldMatrix(updateParents, updateChildren) {
+ const parent = this.parent;
+
+ if (updateParents === true && parent !== null) {
+ parent.updateWorldMatrix(true, false);
+ }
+
+ if (this.matrixAutoUpdate) this.updateMatrix();
+
+ if (this.parent === null) {
+ this.matrixWorld.copy(this.matrix);
+ } else {
+ this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
+ } // update children
+
+
+ if (updateChildren === true) {
+ const children = this.children;
+
+ for (let i = 0, l = children.length; i < l; i++) {
+ children[i].updateWorldMatrix(false, true);
+ }
+ }
+ }
+
+ toJSON(meta) {
+ // meta is a string when called from JSON.stringify
+ const isRootObject = meta === undefined || typeof meta === 'string';
+ const output = {}; // meta is a hash used to collect geometries, materials.
+ // not providing it implies that this is the root object
+ // being serialized.
+
+ if (isRootObject) {
+ // initialize meta obj
+ meta = {
+ geometries: {},
+ materials: {},
+ textures: {},
+ images: {},
+ shapes: {},
+ skeletons: {},
+ animations: {}
+ };
+ output.metadata = {
+ version: 4.5,
+ type: 'Object',
+ generator: 'Object3D.toJSON'
+ };
+ } // standard Object3D serialization
+
+
+ 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 (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
+ object.layers = this.layers.mask;
+ object.matrix = this.matrix.toArray();
+ if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
+
+ if (this.isInstancedMesh) {
+ object.type = 'InstancedMesh';
+ object.count = this.count;
+ object.instanceMatrix = this.instanceMatrix.toJSON();
+ if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
+ } //
+
+
+ function serialize(library, element) {
+ if (library[element.uuid] === undefined) {
+ 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) {
+ 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 !== undefined && parameters.shapes !== undefined) {
+ 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 !== undefined) {
+ serialize(meta.skeletons, this.skeleton);
+ object.skeleton = this.skeleton.uuid;
+ }
+ }
+
+ if (this.material !== undefined) {
+ 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);
+ 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;
+ }
+
+ output.object = object;
+ return output; // extract data from the cache hash
+ // remove metadata on each item
+ // and return as array
+
+ function extractFromCache(cache) {
+ const values = [];
+
+ for (const key in cache) {
+ const data = cache[key];
+ delete data.metadata;
+ values.push(data);
+ }
+
+ return values;
+ }
+ }
+
+ clone(recursive) {
+ return new this.constructor().copy(this, recursive);
+ }
+
+ 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.matrix.copy(source.matrix);
+ this.matrixWorld.copy(source.matrixWorld);
+ this.matrixAutoUpdate = source.matrixAutoUpdate;
+ 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.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.DefaultUp = new Vector3(0, 1, 0);
+Object3D.DefaultMatrixAutoUpdate = true;
+Object3D.prototype.isObject3D = true;
+
+const _v0$1 = /*@__PURE__*/new Vector3();
+
+const _v1$3 = /*@__PURE__*/new Vector3();
+
+const _v2$2 = /*@__PURE__*/new Vector3();
+
+const _v3$1 = /*@__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();
+
+class Triangle {
+ constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
+ this.a = a;
+ this.b = b;
+ this.c = c;
+ }
+
+ static getNormal(a, b, c, target) {
+ target.subVectors(c, b);
+
+ _v0$1.subVectors(a, b);
+
+ target.cross(_v0$1);
+ const targetLengthSq = target.lengthSq();
+
+ if (targetLengthSq > 0) {
+ return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
+ }
+
+ return target.set(0, 0, 0);
+ } // static/instance method to calculate barycentric coordinates
+ // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
+
+
+ static getBarycoord(point, a, b, c, target) {
+ _v0$1.subVectors(c, a);
+
+ _v1$3.subVectors(b, a);
+
+ _v2$2.subVectors(point, a);
+
+ const dot00 = _v0$1.dot(_v0$1);
+
+ const dot01 = _v0$1.dot(_v1$3);
+
+ const dot02 = _v0$1.dot(_v2$2);
+
+ const dot11 = _v1$3.dot(_v1$3);
+
+ const dot12 = _v1$3.dot(_v2$2);
+
+ const denom = dot00 * dot11 - dot01 * dot01; // collinear 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 target.set(-2, -1, -1);
+ }
+
+ const invDenom = 1 / denom;
+ const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
+ const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
+
+ return target.set(1 - u - v, v, u);
+ }
+
+ static containsPoint(point, a, b, c) {
+ this.getBarycoord(point, a, b, c, _v3$1);
+ return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
+ }
+
+ static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
+ this.getBarycoord(point, p1, p2, p3, _v3$1);
+ target.set(0, 0);
+ target.addScaledVector(uv1, _v3$1.x);
+ target.addScaledVector(uv2, _v3$1.y);
+ target.addScaledVector(uv3, _v3$1.z);
+ return target;
+ }
+
+ static isFrontFacing(a, b, c, direction) {
+ _v0$1.subVectors(c, b);
+
+ _v1$3.subVectors(a, b); // strictly front facing
+
+
+ return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
+ }
+
+ set(a, b, c) {
+ this.a.copy(a);
+ this.b.copy(b);
+ this.c.copy(c);
+ return this;
+ }
+
+ setFromPointsAndIndices(points, i0, i1, i2) {
+ this.a.copy(points[i0]);
+ this.b.copy(points[i1]);
+ this.c.copy(points[i2]);
+ return this;
+ }
+
+ setFromAttributeAndIndices(attribute, i0, i1, i2) {
+ this.a.fromBufferAttribute(attribute, i0);
+ this.b.fromBufferAttribute(attribute, i1);
+ this.c.fromBufferAttribute(attribute, i2);
+ return this;
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+ copy(triangle) {
+ this.a.copy(triangle.a);
+ this.b.copy(triangle.b);
+ this.c.copy(triangle.c);
+ return this;
+ }
+
+ getArea() {
+ _v0$1.subVectors(this.c, this.b);
+
+ _v1$3.subVectors(this.a, this.b);
+
+ return _v0$1.cross(_v1$3).length() * 0.5;
+ }
+
+ getMidpoint(target) {
+ return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
+ }
+
+ getNormal(target) {
+ return Triangle.getNormal(this.a, this.b, this.c, target);
+ }
+
+ getPlane(target) {
+ return target.setFromCoplanarPoints(this.a, this.b, this.c);
+ }
+
+ getBarycoord(point, target) {
+ return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
+ }
+
+ getUV(point, uv1, uv2, uv3, target) {
+ return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
+ }
+
+ containsPoint(point) {
+ return Triangle.containsPoint(point, this.a, this.b, this.c);
+ }
+
+ isFrontFacing(direction) {
+ return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
+ }
+
+ intersectsBox(box) {
+ return box.intersectsTriangle(this);
+ }
+
+ closestPointToPoint(p, target) {
+ const a = this.a,
+ b = this.b,
+ c = this.c;
+ let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
+ // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
+ // under the accompanying license; see chapter 5.1.5 for detailed explanation.
+ // basically, we're distinguishing which of the voronoi regions of the triangle
+ // the point lies in with the minimum amount of redundant computation.
+
+ _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) {
+ // vertex region of A; barycentric coords (1, 0, 0)
+ return target.copy(a);
+ }
+
+ _vbp.subVectors(p, b);
+
+ const d3 = _vab.dot(_vbp);
+
+ const d4 = _vac.dot(_vbp);
+
+ if (d3 >= 0 && d4 <= d3) {
+ // vertex region of B; barycentric coords (0, 1, 0)
+ return target.copy(b);
+ }
+
+ const vc = d1 * d4 - d3 * d2;
+
+ if (vc <= 0 && d1 >= 0 && d3 <= 0) {
+ v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
+
+ 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) {
+ // vertex region of C; barycentric coords (0, 0, 1)
+ return target.copy(c);
+ }
+
+ const vb = d5 * d2 - d1 * d6;
+
+ if (vb <= 0 && d2 >= 0 && d6 <= 0) {
+ w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
+
+ 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)); // edge region of BC; barycentric coords (0, 1-w, w)
+
+ return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
+ } // face region
+
+
+ const denom = 1 / (va + vb + vc); // u = va * denom
+
+ v = vb * denom;
+ w = vc * denom;
+ return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
+ }
+
+ equals(triangle) {
+ return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
+ }
+
+}
+
+let materialId = 0;
+
+class Material extends EventDispatcher {
+ constructor() {
+ super();
+ Object.defineProperty(this, 'id', {
+ value: materialId++
+ });
+ this.uuid = generateUUID();
+ this.name = '';
+ this.type = 'Material';
+ this.fog = true;
+ this.blending = NormalBlending;
+ this.side = FrontSide;
+ this.vertexColors = false;
+ this.opacity = 1;
+ this.transparent = false;
+ this.blendSrc = SrcAlphaFactor;
+ this.blendDst = OneMinusSrcAlphaFactor;
+ this.blendEquation = AddEquation;
+ this.blendSrcAlpha = null;
+ this.blendDstAlpha = null;
+ this.blendEquationAlpha = null;
+ this.depthFunc = LessEqualDepth;
+ this.depthTest = true;
+ this.depthWrite = true;
+ this.stencilWriteMask = 0xff;
+ this.stencilFunc = AlwaysStencilFunc;
+ this.stencilRef = 0;
+ this.stencilFuncMask = 0xff;
+ 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.alphaWrite = true;
+ this.precision = null; // override the renderer's default precision for this material
+
+ this.polygonOffset = false;
+ this.polygonOffsetFactor = 0;
+ this.polygonOffsetUnits = 0;
+ this.dithering = false;
+ this.alphaToCoverage = false;
+ this.premultipliedAlpha = false;
+ this.visible = true;
+ this.toneMapped = true;
+ this.userData = {};
+ this.version = 0;
+ this._alphaTest = 0;
+ }
+
+ get alphaTest() {
+ return this._alphaTest;
+ }
+
+ set alphaTest(value) {
+ if (this._alphaTest > 0 !== value > 0) {
+ this.version++;
+ }
+
+ this._alphaTest = value;
+ }
+
+ onBuild() {}
+
+ onBeforeRender() {}
+
+ onBeforeCompile() {}
+
+ customProgramCacheKey() {
+ return this.onBeforeCompile.toString();
+ }
+
+ setValues(values) {
+ if (values === undefined) return;
+
+ for (const key in values) {
+ const newValue = values[key];
+
+ if (newValue === undefined) {
+ console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
+ continue;
+ } // for backward compatability if shading is set in the constructor
+
+
+ if (key === 'shading') {
+ console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
+ this.flatShading = newValue === FlatShading ? true : false;
+ continue;
+ }
+
+ const currentValue = this[key];
+
+ if (currentValue === undefined) {
+ console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
+ continue;
+ }
+
+ if (currentValue && currentValue.isColor) {
+ currentValue.set(newValue);
+ } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
+ currentValue.copy(newValue);
+ } else {
+ this[key] = newValue;
+ }
+ }
+ }
+
+ toJSON(meta) {
+ const isRoot = meta === undefined || typeof meta === 'string';
+
+ if (isRoot) {
+ meta = {
+ textures: {},
+ images: {}
+ };
+ }
+
+ const data = {
+ metadata: {
+ version: 4.5,
+ type: 'Material',
+ generator: 'Material.toJSON'
+ }
+ }; // standard Material serialization
+
+ 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 !== undefined) data.roughness = this.roughness;
+ if (this.metalness !== undefined) data.metalness = this.metalness;
+ if (this.sheen !== undefined) data.sheen = this.sheen;
+ if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex();
+ if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
+ if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
+ if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
+ if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
+ if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
+ if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex();
+ if (this.shininess !== undefined) data.shininess = this.shininess;
+ if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
+ if (this.clearcoatRoughness !== undefined) 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.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 !== undefined) data.combine = this.combine;
+ }
+
+ if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
+ if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
+ if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
+
+ if (this.gradientMap && this.gradientMap.isTexture) {
+ data.gradientMap = this.gradientMap.toJSON(meta).uuid;
+ }
+
+ if (this.transmission !== undefined) data.transmission = this.transmission;
+ if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
+ if (this.thickness !== undefined) data.thickness = this.thickness;
+ if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
+ if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
+ if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
+ if (this.size !== undefined) data.size = this.size;
+ if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
+ if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
+ if (this.blending !== NormalBlending) data.blending = this.blending;
+ if (this.side !== FrontSide) data.side = this.side;
+ if (this.vertexColors) data.vertexColors = true;
+ if (this.opacity < 1) data.opacity = this.opacity;
+ if (this.transparent === true) data.transparent = this.transparent;
+ data.depthFunc = this.depthFunc;
+ data.depthTest = this.depthTest;
+ data.depthWrite = this.depthWrite;
+ data.colorWrite = this.colorWrite;
+ data.alphaWrite = this.alphaWrite;
+ data.stencilWrite = this.stencilWrite;
+ data.stencilWriteMask = this.stencilWriteMask;
+ data.stencilFunc = this.stencilFunc;
+ data.stencilRef = this.stencilRef;
+ data.stencilFuncMask = this.stencilFuncMask;
+ data.stencilFail = this.stencilFail;
+ data.stencilZFail = this.stencilZFail;
+ data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
+
+ if (this.rotation && 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 && this.linewidth !== 1) data.linewidth = this.linewidth;
+ if (this.dashSize !== undefined) data.dashSize = this.dashSize;
+ if (this.gapSize !== undefined) data.gapSize = this.gapSize;
+ if (this.scale !== undefined) data.scale = this.scale;
+ if (this.dithering === true) data.dithering = true;
+ if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
+ if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
+ if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
+ if (this.wireframe === true) data.wireframe = this.wireframe;
+ 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 = this.flatShading;
+ if (this.visible === false) data.visible = false;
+ if (this.toneMapped === false) data.toneMapped = false;
+ if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
+
+ function extractFromCache(cache) {
+ const values = [];
+
+ for (const key in cache) {
+ const data = cache[key];
+ delete data.metadata;
+ values.push(data);
+ }
+
+ return values;
+ }
+
+ if (isRoot) {
+ 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;
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+ copy(source) {
+ this.name = source.name;
+ this.fog = source.fog;
+ 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.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.alphaWrite = source.alphaWrite;
+ 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.alphaToCoverage = source.alphaToCoverage;
+ this.premultipliedAlpha = source.premultipliedAlpha;
+ this.visible = source.visible;
+ this.toneMapped = source.toneMapped;
+ this.userData = JSON.parse(JSON.stringify(source.userData));
+ return this;
+ }
+
+ dispose() {
+ this.dispatchEvent({
+ type: 'dispose'
+ });
+ }
+
+ set needsUpdate(value) {
+ if (value === true) this.version++;
+ }
+
+}
+
+Material.prototype.isMaterial = true;
+
+/**
+ * parameters = {
+ * color: <hex>,
+ * opacity: <float>,
+ * map: new THREE.Texture( <Image> ),
+ *
+ * lightMap: new THREE.Texture( <Image> ),
+ * lightMapIntensity: <float>
+ *
+ * aoMap: new THREE.Texture( <Image> ),
+ * aoMapIntensity: <float>
+ *
+ * specularMap: new THREE.Texture( <Image> ),
+ *
+ * alphaMap: new THREE.Texture( <Image> ),
+ *
+ * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
+ * combine: THREE.Multiply,
+ * reflectivity: <float>,
+ * refractionRatio: <float>,
+ *
+ * depthTest: <bool>,
+ * depthWrite: <bool>,
+ *
+ * wireframe: <boolean>,
+ * wireframeLinewidth: <float>,
+ * }
+ */
+
+class MeshBasicMaterial extends Material {
+ constructor(parameters) {
+ super();
+ this.type = 'MeshBasicMaterial';
+ this.color = new Color(0xffffff); // emissive
+
+ this.map = null;
+ this.lightMap = null;
+ this.lightMapIntensity = 1.0;
+ this.aoMap = null;
+ this.aoMapIntensity = 1.0;
+ this.specularMap = null;
+ this.alphaMap = null;
+ this.envMap = null;
+ this.combine = MultiplyOperation;
+ this.reflectivity = 1;
+ this.refractionRatio = 0.98;
+ this.wireframe = false;
+ this.wireframeLinewidth = 1;
+ this.wireframeLinecap = 'round';
+ this.wireframeLinejoin = 'round';
+ 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.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;
+ return this;
+ }
+
+}
+
+MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
+
+const _vector$9 = /*@__PURE__*/new Vector3();
+
+const _vector2$1 = /*@__PURE__*/new Vector2();
+
+class BufferAttribute {
+ constructor(array, itemSize, normalized) {
+ if (Array.isArray(array)) {
+ throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
+ }
+
+ this.name = '';
+ this.array = array;
+ this.itemSize = itemSize;
+ this.count = array !== undefined ? array.length / itemSize : 0;
+ this.normalized = normalized === true;
+ this.usage = StaticDrawUsage;
+ this.updateRange = {
+ offset: 0,
+ count: -1
+ };
+ this.version = 0;
+ }
+
+ onUploadCallback() {}
+
+ set needsUpdate(value) {
+ if (value === true) this.version++;
+ }
+
+ setUsage(value) {
+ this.usage = value;
+ return this;
+ }
+
+ 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;
+ return this;
+ }
+
+ 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;
+ }
+
+ copyArray(array) {
+ this.array.set(array);
+ return this;
+ }
+
+ copyColorsArray(colors) {
+ const array = this.array;
+ let offset = 0;
+
+ for (let i = 0, l = colors.length; i < l; i++) {
+ let color = colors[i];
+
+ if (color === undefined) {
+ console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
+ color = new Color();
+ }
+
+ array[offset++] = color.r;
+ array[offset++] = color.g;
+ array[offset++] = color.b;
+ }
+
+ return this;
+ }
+
+ copyVector2sArray(vectors) {
+ const array = this.array;
+ let offset = 0;
+
+ for (let i = 0, l = vectors.length; i < l; i++) {
+ let vector = vectors[i];
+
+ if (vector === undefined) {
+ console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
+ vector = new Vector2();
+ }
+
+ array[offset++] = vector.x;
+ array[offset++] = vector.y;
+ }
+
+ return this;
+ }
+
+ copyVector3sArray(vectors) {
+ const array = this.array;
+ let offset = 0;
+
+ for (let i = 0, l = vectors.length; i < l; i++) {
+ let vector = vectors[i];
+
+ if (vector === undefined) {
+ console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
+ vector = new Vector3();
+ }
+
+ array[offset++] = vector.x;
+ array[offset++] = vector.y;
+ array[offset++] = vector.z;
+ }
+
+ return this;
+ }
+
+ copyVector4sArray(vectors) {
+ const array = this.array;
+ let offset = 0;
+
+ for (let i = 0, l = vectors.length; i < l; i++) {
+ let vector = vectors[i];
+
+ if (vector === undefined) {
+ console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
+ vector = new Vector4();
+ }
+
+ array[offset++] = vector.x;
+ array[offset++] = vector.y;
+ array[offset++] = vector.z;
+ array[offset++] = vector.w;
+ }
+
+ return this;
+ }
+
+ 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$9.fromBufferAttribute(this, i);
+
+ _vector$9.applyMatrix3(m);
+
+ this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
+ }
+ }
+
+ return this;
+ }
+
+ applyMatrix4(m) {
+ for (let i = 0, l = this.count; i < l; i++) {
+ _vector$9.x = this.getX(i);
+ _vector$9.y = this.getY(i);
+ _vector$9.z = this.getZ(i);
+
+ _vector$9.applyMatrix4(m);
+
+ this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
+ }
+
+ return this;
+ }
+
+ applyNormalMatrix(m) {
+ for (let i = 0, l = this.count; i < l; i++) {
+ _vector$9.x = this.getX(i);
+ _vector$9.y = this.getY(i);
+ _vector$9.z = this.getZ(i);
+
+ _vector$9.applyNormalMatrix(m);
+
+ this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
+ }
+
+ return this;
+ }
+
+ transformDirection(m) {
+ for (let i = 0, l = this.count; i < l; i++) {
+ _vector$9.x = this.getX(i);
+ _vector$9.y = this.getY(i);
+ _vector$9.z = this.getZ(i);
+
+ _vector$9.transformDirection(m);
+
+ this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
+ }
+
+ return this;
+ }
+
+ set(value, offset = 0) {
+ this.array.set(value, offset);
+ return this;
+ }
+
+ getX(index) {
+ return this.array[index * this.itemSize];
+ }
+
+ setX(index, x) {
+ this.array[index * this.itemSize] = x;
+ return this;
+ }
+
+ getY(index) {
+ return this.array[index * this.itemSize + 1];
+ }
+
+ setY(index, y) {
+ this.array[index * this.itemSize + 1] = y;
+ return this;
+ }
+
+ getZ(index) {
+ return this.array[index * this.itemSize + 2];
+ }
+
+ setZ(index, z) {
+ this.array[index * this.itemSize + 2] = z;
+ return this;
+ }
+
+ getW(index) {
+ return this.array[index * this.itemSize + 3];
+ }
+
+ setW(index, w) {
+ this.array[index * this.itemSize + 3] = w;
+ return this;
+ }
+
+ setXY(index, x, y) {
+ index *= this.itemSize;
+ this.array[index + 0] = x;
+ this.array[index + 1] = y;
+ return this;
+ }
+
+ setXYZ(index, x, y, z) {
+ index *= this.itemSize;
+ this.array[index + 0] = x;
+ this.array[index + 1] = y;
+ this.array[index + 2] = z;
+ return this;
+ }
+
+ setXYZW(index, x, y, z, w) {
+ index *= this.itemSize;
+ this.array[index + 0] = x;
+ this.array[index + 1] = y;
+ this.array[index + 2] = z;
+ this.array[index + 3] = w;
+ return this;
+ }
+
+ onUpload(callback) {
+ this.onUploadCallback = callback;
+ return this;
+ }
+
+ clone() {
+ return new this.constructor(this.array, this.itemSize).copy(this);
+ }
+
+ toJSON() {
+ const data = {
+ itemSize: this.itemSize,
+ type: this.array.constructor.name,
+ array: Array.prototype.slice.call(this.array),
+ normalized: this.normalized
+ };
+ if (this.name !== '') data.name = this.name;
+ if (this.usage !== StaticDrawUsage) data.usage = this.usage;
+ if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
+ return data;
+ }
+
+}
+
+BufferAttribute.prototype.isBufferAttribute = true; //
+
+class Int8BufferAttribute extends BufferAttribute {
+ constructor(array, itemSize, normalized) {
+ super(new Int8Array(array), itemSize, normalized);
+ }
+
+}
+
+class Uint8BufferAttribute extends BufferAttribute {
+ constructor(array, itemSize, normalized) {
+ super(new Uint8Array(array), itemSize, normalized);
+ }
+
+}
+
+class Uint8ClampedBufferAttribute extends BufferAttribute {
+ constructor(array, itemSize, normalized) {
+ super(new Uint8ClampedArray(array), itemSize, normalized);
+ }
+
+}
+
+class Int16BufferAttribute extends BufferAttribute {
+ constructor(array, itemSize, normalized) {
+ super(new Int16Array(array), itemSize, normalized);
+ }
+
+}
+
+class Uint16BufferAttribute extends BufferAttribute {
+ constructor(array, itemSize, normalized) {
+ super(new Uint16Array(array), itemSize, normalized);
+ }
+
+}
+
+class Int32BufferAttribute extends BufferAttribute {
+ constructor(array, itemSize, normalized) {
+ super(new Int32Array(array), itemSize, normalized);
+ }
+
+}
+
+class Uint32BufferAttribute extends BufferAttribute {
+ constructor(array, itemSize, normalized) {
+ super(new Uint32Array(array), itemSize, normalized);
+ }
+
+}
+
+class Float16BufferAttribute extends BufferAttribute {
+ constructor(array, itemSize, normalized) {
+ super(new Uint16Array(array), itemSize, normalized);
+ }
+
+}
+
+Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
+
+class Float32BufferAttribute extends BufferAttribute {
+ constructor(array, itemSize, normalized) {
+ super(new Float32Array(array), itemSize, normalized);
+ }
+
+}
+
+class Float64BufferAttribute extends BufferAttribute {
+ constructor(array, itemSize, normalized) {
+ super(new Float64Array(array), itemSize, normalized);
+ }
+
+} //
+
+let _id$1 = 0;
+
+const _m1 = /*@__PURE__*/new Matrix4();
+
+const _obj = /*@__PURE__*/new Object3D();
+
+const _offset = /*@__PURE__*/new Vector3();
+
+const _box$1 = /*@__PURE__*/new Box3();
+
+const _boxMorphTargets = /*@__PURE__*/new Box3();
+
+const _vector$8 = /*@__PURE__*/new Vector3();
+
+class BufferGeometry extends EventDispatcher {
+ constructor() {
+ super();
+ Object.defineProperty(this, 'id', {
+ value: _id$1++
+ });
+ this.uuid = generateUUID();
+ this.name = '';
+ this.type = 'BufferGeometry';
+ this.index = null;
+ this.attributes = {};
+ this.morphAttributes = {};
+ this.morphTargetsRelative = false;
+ this.groups = [];
+ this.boundingBox = null;
+ this.boundingSphere = null;
+ this.drawRange = {
+ start: 0,
+ count: Infinity
+ };
+ this.userData = {};
+ }
+
+ getIndex() {
+ return this.index;
+ }
+
+ setIndex(index) {
+ if (Array.isArray(index)) {
+ this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
+ } else {
+ this.index = index;
+ }
+
+ return this;
+ }
+
+ getAttribute(name) {
+ return this.attributes[name];
+ }
+
+ setAttribute(name, attribute) {
+ this.attributes[name] = attribute;
+ return this;
+ }
+
+ deleteAttribute(name) {
+ delete this.attributes[name];
+ return this;
+ }
+
+ hasAttribute(name) {
+ return this.attributes[name] !== undefined;
+ }
+
+ addGroup(start, count, materialIndex = 0) {
+ this.groups.push({
+ start: start,
+ count: count,
+ materialIndex: materialIndex
+ });
+ }
+
+ clearGroups() {
+ this.groups = [];
+ }
+
+ setDrawRange(start, count) {
+ this.drawRange.start = start;
+ this.drawRange.count = count;
+ }
+
+ applyMatrix4(matrix) {
+ const position = this.attributes.position;
+
+ if (position !== undefined) {
+ position.applyMatrix4(matrix);
+ position.needsUpdate = true;
+ }
+
+ const normal = this.attributes.normal;
+
+ if (normal !== undefined) {
+ const normalMatrix = new Matrix3().getNormalMatrix(matrix);
+ normal.applyNormalMatrix(normalMatrix);
+ normal.needsUpdate = true;
+ }
+
+ const tangent = this.attributes.tangent;
+
+ if (tangent !== undefined) {
+ tangent.transformDirection(matrix);
+ tangent.needsUpdate = true;
+ }
+
+ if (this.boundingBox !== null) {
+ this.computeBoundingBox();
+ }
+
+ if (this.boundingSphere !== null) {
+ this.computeBoundingSphere();
+ }
+
+ return this;
+ }
+
+ applyQuaternion(q) {
+ _m1.makeRotationFromQuaternion(q);
+
+ this.applyMatrix4(_m1);
+ return this;
+ }
+
+ rotateX(angle) {
+ // rotate geometry around world x-axis
+ _m1.makeRotationX(angle);
+
+ this.applyMatrix4(_m1);
+ return this;
+ }
+
+ rotateY(angle) {
+ // rotate geometry around world y-axis
+ _m1.makeRotationY(angle);
+
+ this.applyMatrix4(_m1);
+ return this;
+ }
+
+ rotateZ(angle) {
+ // rotate geometry around world z-axis
+ _m1.makeRotationZ(angle);
+
+ this.applyMatrix4(_m1);
+ return this;
+ }
+
+ translate(x, y, z) {
+ // translate geometry
+ _m1.makeTranslation(x, y, z);
+
+ this.applyMatrix4(_m1);
+ return this;
+ }
+
+ scale(x, y, z) {
+ // scale geometry
+ _m1.makeScale(x, y, z);
+
+ this.applyMatrix4(_m1);
+ return this;
+ }
+
+ lookAt(vector) {
+ _obj.lookAt(vector);
+
+ _obj.updateMatrix();
+
+ this.applyMatrix4(_obj.matrix);
+ return this;
+ }
+
+ center() {
+ this.computeBoundingBox();
+ this.boundingBox.getCenter(_offset).negate();
+ this.translate(_offset.x, _offset.y, _offset.z);
+ return this;
+ }
+
+ setFromPoints(points) {
+ const position = [];
+
+ for (let i = 0, l = points.length; i < l; i++) {
+ const point = points[i];
+ position.push(point.x, point.y, point.z || 0);
+ }
+
+ this.setAttribute('position', new Float32BufferAttribute(position, 3));
+ return this;
+ }
+
+ computeBoundingBox() {
+ if (this.boundingBox === null) {
+ this.boundingBox = new Box3();
+ }
+
+ const position = this.attributes.position;
+ const morphAttributesPosition = this.morphAttributes.position;
+
+ if (position && position.isGLBufferAttribute) {
+ console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
+ this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
+ return;
+ }
+
+ if (position !== undefined) {
+ this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
+
+ if (morphAttributesPosition) {
+ for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
+ const morphAttribute = morphAttributesPosition[i];
+
+ _box$1.setFromBufferAttribute(morphAttribute);
+
+ if (this.morphTargetsRelative) {
+ _vector$8.addVectors(this.boundingBox.min, _box$1.min);
+
+ this.boundingBox.expandByPoint(_vector$8);
+
+ _vector$8.addVectors(this.boundingBox.max, _box$1.max);
+
+ this.boundingBox.expandByPoint(_vector$8);
+ } else {
+ this.boundingBox.expandByPoint(_box$1.min);
+ this.boundingBox.expandByPoint(_box$1.max);
+ }
+ }
+ }
+ } else {
+ this.boundingBox.makeEmpty();
+ }
+
+ if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
+ console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
+ }
+ }
+
+ computeBoundingSphere() {
+ if (this.boundingSphere === null) {
+ this.boundingSphere = new Sphere();
+ }
+
+ const position = this.attributes.position;
+ const morphAttributesPosition = this.morphAttributes.position;
+
+ if (position && position.isGLBufferAttribute) {
+ console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
+ this.boundingSphere.set(new Vector3(), Infinity);
+ return;
+ }
+
+ if (position) {
+ // first, find the center of the bounding sphere
+ const center = this.boundingSphere.center;
+
+ _box$1.setFromBufferAttribute(position); // process morph attributes if present
+
+
+ if (morphAttributesPosition) {
+ for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
+ const morphAttribute = morphAttributesPosition[i];
+
+ _boxMorphTargets.setFromBufferAttribute(morphAttribute);
+
+ if (this.morphTargetsRelative) {
+ _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
+
+ _box$1.expandByPoint(_vector$8);
+
+ _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
+
+ _box$1.expandByPoint(_vector$8);
+ } else {
+ _box$1.expandByPoint(_boxMorphTargets.min);
+
+ _box$1.expandByPoint(_boxMorphTargets.max);
+ }
+ }
+ }
+
+ _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
+ // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
+
+
+ let maxRadiusSq = 0;
+
+ for (let i = 0, il = position.count; i < il; i++) {
+ _vector$8.fromBufferAttribute(position, i);
+
+ maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
+ } // process morph attributes if present
+
+
+ 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$8.fromBufferAttribute(morphAttribute, j);
+
+ if (morphTargetsRelative) {
+ _offset.fromBufferAttribute(position, j);
+
+ _vector$8.add(_offset);
+ }
+
+ maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
+ }
+ }
+ }
+
+ this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
+
+ if (isNaN(this.boundingSphere.radius)) {
+ console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
+ }
+ }
+ }
+
+ computeTangents() {
+ const index = this.index;
+ const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
+ // (per vertex tangents)
+
+ if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
+ console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
+ return;
+ }
+
+ const indices = index.array;
+ const positions = attributes.position.array;
+ const normals = attributes.normal.array;
+ const uvs = attributes.uv.array;
+ const nVertices = positions.length / 3;
+
+ if (attributes.tangent === undefined) {
+ this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
+ }
+
+ const tangents = attributes.tangent.array;
+ const tan1 = [],
+ tan2 = [];
+
+ for (let i = 0; i < nVertices; 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.fromArray(positions, a * 3);
+ vB.fromArray(positions, b * 3);
+ vC.fromArray(positions, c * 3);
+ uvA.fromArray(uvs, a * 2);
+ uvB.fromArray(uvs, b * 2);
+ uvC.fromArray(uvs, c * 2);
+ vB.sub(vA);
+ vC.sub(vA);
+ uvB.sub(uvA);
+ uvC.sub(uvA);
+ const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
+
+ 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: indices.length
+ }];
+ }
+
+ 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(indices[j + 0], indices[j + 1], indices[j + 2]);
+ }
+ }
+
+ const tmp = new Vector3(),
+ tmp2 = new Vector3();
+ const n = new Vector3(),
+ n2 = new Vector3();
+
+ function handleVertex(v) {
+ n.fromArray(normals, v * 3);
+ n2.copy(n);
+ const t = tan1[v]; // Gram-Schmidt orthogonalize
+
+ tmp.copy(t);
+ tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
+
+ tmp2.crossVectors(n2, t);
+ const test = tmp2.dot(tan2[v]);
+ const 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 (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(indices[j + 0]);
+ handleVertex(indices[j + 1]);
+ handleVertex(indices[j + 2]);
+ }
+ }
+ }
+
+ computeVertexNormals() {
+ const index = this.index;
+ const positionAttribute = this.getAttribute('position');
+
+ if (positionAttribute !== undefined) {
+ let normalAttribute = this.getAttribute('normal');
+
+ if (normalAttribute === undefined) {
+ normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
+ this.setAttribute('normal', normalAttribute);
+ } else {
+ // reset existing normals to zero
+ 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(); // indexed elements
+
+ 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 {
+ // non-indexed elements (unconnected triangle soup)
+ 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;
+ }
+ }
+
+ merge(geometry, offset) {
+ if (!(geometry && geometry.isBufferGeometry)) {
+ console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
+ return;
+ }
+
+ if (offset === undefined) {
+ offset = 0;
+ console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
+ }
+
+ const attributes = this.attributes;
+
+ for (const key in attributes) {
+ if (geometry.attributes[key] === undefined) continue;
+ const attribute1 = attributes[key];
+ const attributeArray1 = attribute1.array;
+ const attribute2 = geometry.attributes[key];
+ const attributeArray2 = attribute2.array;
+ const attributeOffset = attribute2.itemSize * offset;
+ const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
+
+ for (let i = 0, j = attributeOffset; i < length; i++, j++) {
+ attributeArray1[j] = attributeArray2[i];
+ }
+ }
+
+ return this;
+ }
+
+ normalizeNormals() {
+ const normals = this.attributes.normal;
+
+ for (let i = 0, il = normals.count; i < il; i++) {
+ _vector$8.fromBufferAttribute(normals, i);
+
+ _vector$8.normalize();
+
+ normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
+ }
+ }
+
+ toNonIndexed() {
+ function convertBufferAttribute(attribute, indices) {
+ const array = attribute.array;
+ const itemSize = attribute.itemSize;
+ const normalized = attribute.normalized;
+ const array2 = new array.constructor(indices.length * itemSize);
+ let index = 0,
+ index2 = 0;
+
+ for (let i = 0, l = indices.length; i < l; i++) {
+ if (attribute.isInterleavedBufferAttribute) {
+ index = indices[i] * attribute.data.stride + attribute.offset;
+ } else {
+ index = indices[i] * itemSize;
+ }
+
+ for (let j = 0; j < itemSize; j++) {
+ array2[index2++] = array[index++];
+ }
+ }
+
+ return new BufferAttribute(array2, itemSize, normalized);
+ } //
+
+
+ if (this.index === null) {
+ console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
+ return this;
+ }
+
+ const geometry2 = new BufferGeometry();
+ const indices = this.index.array;
+ const attributes = this.attributes; // attributes
+
+ for (const name in attributes) {
+ const attribute = attributes[name];
+ const newAttribute = convertBufferAttribute(attribute, indices);
+ geometry2.setAttribute(name, newAttribute);
+ } // morph attributes
+
+
+ const morphAttributes = this.morphAttributes;
+
+ for (const name in morphAttributes) {
+ const morphArray = [];
+ const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
+
+ 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; // groups
+
+ 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;
+ }
+
+ toJSON() {
+ const data = {
+ metadata: {
+ version: 4.5,
+ type: 'BufferGeometry',
+ generator: 'BufferGeometry.toJSON'
+ }
+ }; // standard BufferGeometry serialization
+
+ 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 !== undefined) {
+ const parameters = this.parameters;
+
+ for (const key in parameters) {
+ if (parameters[key] !== undefined) data[key] = parameters[key];
+ }
+
+ return data;
+ } // for simplicity the code assumes attributes are not shared across geometries, see #15811
+
+
+ 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 = {
+ center: boundingSphere.center.toArray(),
+ radius: boundingSphere.radius
+ };
+ }
+
+ return data;
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+ copy(source) {
+ // reset
+ this.index = null;
+ this.attributes = {};
+ this.morphAttributes = {};
+ this.groups = [];
+ this.boundingBox = null;
+ this.boundingSphere = null; // used for storing cloned, shared data
+
+ const data = {}; // name
+
+ this.name = source.name; // index
+
+ const index = source.index;
+
+ if (index !== null) {
+ this.setIndex(index.clone(data));
+ } // attributes
+
+
+ const attributes = source.attributes;
+
+ for (const name in attributes) {
+ const attribute = attributes[name];
+ this.setAttribute(name, attribute.clone(data));
+ } // morph attributes
+
+
+ const morphAttributes = source.morphAttributes;
+
+ for (const name in morphAttributes) {
+ const array = [];
+ const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
+
+ for (let i = 0, l = morphAttribute.length; i < l; i++) {
+ array.push(morphAttribute[i].clone(data));
+ }
+
+ this.morphAttributes[name] = array;
+ }
+
+ this.morphTargetsRelative = source.morphTargetsRelative; // groups
+
+ 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);
+ } // bounding box
+
+
+ const boundingBox = source.boundingBox;
+
+ if (boundingBox !== null) {
+ this.boundingBox = boundingBox.clone();
+ } // bounding sphere
+
+
+ const boundingSphere = source.boundingSphere;
+
+ if (boundingSphere !== null) {
+ this.boundingSphere = boundingSphere.clone();
+ } // draw range
+
+
+ this.drawRange.start = source.drawRange.start;
+ this.drawRange.count = source.drawRange.count; // user data
+
+ this.userData = source.userData; // geometry generator parameters
+
+ if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
+ return this;
+ }
+
+ dispose() {
+ this.dispatchEvent({
+ type: 'dispose'
+ });
+ }
+
+}
+
+BufferGeometry.prototype.isBufferGeometry = true;
+
+const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
+
+const _ray$2 = /*@__PURE__*/new Ray();
+
+const _sphere$3 = /*@__PURE__*/new Sphere();
+
+const _vA$1 = /*@__PURE__*/new Vector3();
+
+const _vB$1 = /*@__PURE__*/new Vector3();
+
+const _vC$1 = /*@__PURE__*/new Vector3();
+
+const _tempA = /*@__PURE__*/new Vector3();
+
+const _tempB = /*@__PURE__*/new Vector3();
+
+const _tempC = /*@__PURE__*/new Vector3();
+
+const _morphA = /*@__PURE__*/new Vector3();
+
+const _morphB = /*@__PURE__*/new Vector3();
+
+const _morphC = /*@__PURE__*/new Vector3();
+
+const _uvA$1 = /*@__PURE__*/new Vector2();
+
+const _uvB$1 = /*@__PURE__*/new Vector2();
+
+const _uvC$1 = /*@__PURE__*/new Vector2();
+
+const _intersectionPoint = /*@__PURE__*/new Vector3();
+
+const _intersectionPointWorld = /*@__PURE__*/new Vector3();
+
+class Mesh extends Object3D {
+ constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
+ super();
+ this.type = 'Mesh';
+ this.geometry = geometry;
+ this.material = material;
+ this.updateMorphTargets();
+ }
+
+ copy(source) {
+ super.copy(source);
+
+ if (source.morphTargetInfluences !== undefined) {
+ this.morphTargetInfluences = source.morphTargetInfluences.slice();
+ }
+
+ if (source.morphTargetDictionary !== undefined) {
+ this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
+ }
+
+ this.material = source.material;
+ this.geometry = source.geometry;
+ return this;
+ }
+
+ updateMorphTargets() {
+ const geometry = this.geometry;
+
+ if (geometry.isBufferGeometry) {
+ const morphAttributes = geometry.morphAttributes;
+ const keys = Object.keys(morphAttributes);
+
+ if (keys.length > 0) {
+ const morphAttribute = morphAttributes[keys[0]];
+
+ if (morphAttribute !== undefined) {
+ 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;
+ }
+ }
+ }
+ } else {
+ const morphTargets = geometry.morphTargets;
+
+ if (morphTargets !== undefined && morphTargets.length > 0) {
+ console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
+ }
+ }
+ }
+
+ raycast(raycaster, intersects) {
+ const geometry = this.geometry;
+ const material = this.material;
+ const matrixWorld = this.matrixWorld;
+ if (material === undefined) return; // Checking boundingSphere distance to ray
+
+ if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
+
+ _sphere$3.copy(geometry.boundingSphere);
+
+ _sphere$3.applyMatrix4(matrixWorld);
+
+ if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
+
+ _inverseMatrix$2.copy(matrixWorld).invert();
+
+ _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
+
+
+ if (geometry.boundingBox !== null) {
+ if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
+ }
+
+ let intersection;
+
+ if (geometry.isBufferGeometry) {
+ const index = geometry.index;
+ const position = geometry.attributes.position;
+ const morphPosition = geometry.morphAttributes.position;
+ const morphTargetsRelative = geometry.morphTargetsRelative;
+ const uv = geometry.attributes.uv;
+ const uv2 = geometry.attributes.uv2;
+ const groups = geometry.groups;
+ const drawRange = geometry.drawRange;
+
+ if (index !== null) {
+ // indexed buffer geometry
+ 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 = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
+
+ if (intersection) {
+ intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
+
+ intersection.face.materialIndex = group.materialIndex;
+ intersects.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 = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
+
+ if (intersection) {
+ intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
+
+ intersects.push(intersection);
+ }
+ }
+ }
+ } else if (position !== undefined) {
+ // non-indexed buffer geometry
+ 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 = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
+
+ if (intersection) {
+ intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
+
+ intersection.face.materialIndex = group.materialIndex;
+ intersects.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 = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
+
+ if (intersection) {
+ intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
+
+ intersects.push(intersection);
+ }
+ }
+ }
+ }
+ } else if (geometry.isGeometry) {
+ console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
+ }
+ }
+
+}
+
+Mesh.prototype.isMesh = true;
+
+function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
+ let intersect;
+
+ if (material.side === BackSide) {
+ intersect = ray.intersectTriangle(pC, pB, pA, true, point);
+ } else {
+ intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
+ }
+
+ if (intersect === null) return null;
+
+ _intersectionPointWorld.copy(point);
+
+ _intersectionPointWorld.applyMatrix4(object.matrixWorld);
+
+ const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
+ if (distance < raycaster.near || distance > raycaster.far) return null;
+ return {
+ distance: distance,
+ point: _intersectionPointWorld.clone(),
+ object: object
+ };
+}
+
+function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
+ _vA$1.fromBufferAttribute(position, a);
+
+ _vB$1.fromBufferAttribute(position, b);
+
+ _vC$1.fromBufferAttribute(position, c);
+
+ const morphInfluences = object.morphTargetInfluences;
+
+ if (morphPosition && morphInfluences) {
+ _morphA.set(0, 0, 0);
+
+ _morphB.set(0, 0, 0);
+
+ _morphC.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, a);
+
+ _tempB.fromBufferAttribute(morphAttribute, b);
+
+ _tempC.fromBufferAttribute(morphAttribute, c);
+
+ if (morphTargetsRelative) {
+ _morphA.addScaledVector(_tempA, influence);
+
+ _morphB.addScaledVector(_tempB, influence);
+
+ _morphC.addScaledVector(_tempC, influence);
+ } else {
+ _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
+
+ _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
+
+ _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
+ }
+ }
+
+ _vA$1.add(_morphA);
+
+ _vB$1.add(_morphB);
+
+ _vC$1.add(_morphC);
+ }
+
+ if (object.isSkinnedMesh) {
+ object.boneTransform(a, _vA$1);
+ object.boneTransform(b, _vB$1);
+ object.boneTransform(c, _vC$1);
+ }
+
+ const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
+
+ if (intersection) {
+ if (uv) {
+ _uvA$1.fromBufferAttribute(uv, a);
+
+ _uvB$1.fromBufferAttribute(uv, b);
+
+ _uvC$1.fromBufferAttribute(uv, c);
+
+ intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
+ }
+
+ if (uv2) {
+ _uvA$1.fromBufferAttribute(uv2, a);
+
+ _uvB$1.fromBufferAttribute(uv2, b);
+
+ _uvC$1.fromBufferAttribute(uv2, c);
+
+ intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
+ }
+
+ const face = {
+ a: a,
+ b: b,
+ c: c,
+ normal: new Vector3(),
+ materialIndex: 0
+ };
+ Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
+ intersection.face = face;
+ }
+
+ return intersection;
+}
+
+class BoxGeometry extends BufferGeometry {
+ constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
+ super();
+ this.type = 'BoxGeometry';
+ this.parameters = {
+ width: width,
+ height: height,
+ depth: depth,
+ widthSegments: widthSegments,
+ heightSegments: heightSegments,
+ depthSegments: depthSegments
+ };
+ const scope = this; // segments
+
+ widthSegments = Math.floor(widthSegments);
+ heightSegments = Math.floor(heightSegments);
+ depthSegments = Math.floor(depthSegments); // buffers
+
+ const indices = [];
+ const vertices = [];
+ const normals = [];
+ const uvs = []; // helper variables
+
+ let numberOfVertices = 0;
+ let groupStart = 0; // build each side of the box geometry
+
+ buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
+
+ buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
+
+ buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
+
+ buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
+
+ buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
+
+ buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
+ // build geometry
+
+ 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, width, height, depth, gridX, gridY, materialIndex) {
+ const segmentWidth = width / gridX;
+ const segmentHeight = height / gridY;
+ const widthHalf = width / 2;
+ const heightHalf = height / 2;
+ const depthHalf = depth / 2;
+ const gridX1 = gridX + 1;
+ const gridY1 = gridY + 1;
+ let vertexCounter = 0;
+ let groupCount = 0;
+ const vector = new Vector3(); // generate vertices, normals and uvs
+
+ for (let iy = 0; iy < gridY1; iy++) {
+ const y = iy * segmentHeight - heightHalf;
+
+ for (let ix = 0; ix < gridX1; ix++) {
+ const x = ix * segmentWidth - widthHalf; // set values to correct vector component
+
+ vector[u] = x * udir;
+ vector[v] = y * vdir;
+ vector[w] = depthHalf; // now apply vector to vertex buffer
+
+ vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
+
+ vector[u] = 0;
+ vector[v] = 0;
+ vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
+
+ normals.push(vector.x, vector.y, vector.z); // uvs
+
+ uvs.push(ix / gridX);
+ uvs.push(1 - iy / gridY); // counters
+
+ vertexCounter += 1;
+ }
+ } // indices
+ // 1. you need three indices to draw a single face
+ // 2. a single segment consists of two faces
+ // 3. so we need to generate six (2*3) indices per segment
+
+
+ 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; // faces
+
+ indices.push(a, b, d);
+ indices.push(b, c, d); // increase counter
+
+ groupCount += 6;
+ }
+ } // add a group to the geometry. this will ensure multi material support
+
+
+ scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
+
+ groupStart += groupCount; // update total number of vertices
+
+ numberOfVertices += vertexCounter;
+ }
+ }
+
+ static fromJSON(data) {
+ return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
+ }
+
+}
+
+/**
+ * Uniform Utilities
+ */
+function cloneUniforms(src) {
+ const dst = {};
+
+ for (const u in src) {
+ dst[u] = {};
+
+ for (const p in src[u]) {
+ const property = src[u][p];
+
+ if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
+ dst[u][p] = property.clone();
+ } else if (Array.isArray(property)) {
+ 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 tmp = cloneUniforms(uniforms[u]);
+
+ for (const p in tmp) {
+ merged[p] = tmp[p];
+ }
+ }
+
+ return merged;
+} // Legacy
+
+const UniformsUtils = {
+ clone: cloneUniforms,
+ merge: mergeUniforms
+};
+
+var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
+
+var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
+
+/**
+ * parameters = {
+ * defines: { "label" : "value" },
+ * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
+ *
+ * fragmentShader: <string>,
+ * vertexShader: <string>,
+ *
+ * wireframe: <boolean>,
+ * wireframeLinewidth: <float>,
+ *
+ * lights: <bool>
+ * }
+ */
+
+class ShaderMaterial extends Material {
+ constructor(parameters) {
+ super();
+ this.type = 'ShaderMaterial';
+ this.defines = {};
+ this.uniforms = {};
+ this.vertexShader = default_vertex;
+ this.fragmentShader = default_fragment;
+ 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.clipping = false; // set to use user-defined clipping planes
+
+ this.extensions = {
+ derivatives: false,
+ // set to use derivatives
+ fragDepth: false,
+ // set to use fragment depth values
+ drawBuffers: false,
+ // set to use draw buffers
+ shaderTextureLOD: false // set to use shader texture LOD
+
+ }; // 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]
+ };
+ this.index0AttributeName = undefined;
+ this.uniformsNeedUpdate = false;
+ this.glslVersion = null;
+
+ if (parameters !== undefined) {
+ if (parameters.attributes !== undefined) {
+ console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
+ }
+
+ this.setValues(parameters);
+ }
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.fragmentShader = source.fragmentShader;
+ this.vertexShader = source.vertexShader;
+ this.uniforms = cloneUniforms(source.uniforms);
+ this.defines = Object.assign({}, source.defines);
+ this.wireframe = source.wireframe;
+ this.wireframeLinewidth = source.wireframeLinewidth;
+ this.lights = source.lights;
+ this.clipping = source.clipping;
+ this.extensions = Object.assign({}, source.extensions);
+ this.glslVersion = source.glslVersion;
+ 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: value
+ }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
+ }
+ }
+
+ if (Object.keys(this.defines).length > 0) data.defines = this.defines;
+ data.vertexShader = this.vertexShader;
+ data.fragmentShader = this.fragmentShader;
+ 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;
+ }
+
+}
+
+ShaderMaterial.prototype.isShaderMaterial = true;
+
+class Camera extends Object3D {
+ constructor() {
+ super();
+ this.type = 'Camera';
+ this.matrixWorldInverse = new Matrix4();
+ this.projectionMatrix = new Matrix4();
+ this.projectionMatrixInverse = new Matrix4();
+ }
+
+ copy(source, recursive) {
+ super.copy(source, recursive);
+ this.matrixWorldInverse.copy(source.matrixWorldInverse);
+ this.projectionMatrix.copy(source.projectionMatrix);
+ this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
+ return this;
+ }
+
+ getWorldDirection(target) {
+ this.updateWorldMatrix(true, false);
+ const e = this.matrixWorld.elements;
+ return target.set(-e[8], -e[9], -e[10]).normalize();
+ }
+
+ updateMatrixWorld(force) {
+ super.updateMatrixWorld(force);
+ this.matrixWorldInverse.copy(this.matrixWorld).invert();
+ }
+
+ updateWorldMatrix(updateParents, updateChildren) {
+ super.updateWorldMatrix(updateParents, updateChildren);
+ this.matrixWorldInverse.copy(this.matrixWorld).invert();
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+}
+
+Camera.prototype.isCamera = true;
+
+class PerspectiveCamera extends Camera {
+ constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
+ super();
+ this.type = 'PerspectiveCamera';
+ this.fov = fov;
+ this.zoom = 1;
+ this.near = near;
+ this.far = far;
+ this.focus = 10;
+ this.aspect = aspect;
+ this.view = null;
+ this.filmGauge = 35; // width of the film (default in millimeters)
+
+ this.filmOffset = 0; // horizontal film offset (same unit as gauge)
+
+ 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 .filmGauge.
+ *
+ * The default film gauge is 35, so that the focal length can be specified for
+ * a 35mm (full frame) camera.
+ *
+ * Values for focal length and film gauge must have the same unit.
+ */
+
+
+ setFocalLength(focalLength) {
+ /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
+ const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
+ this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
+ this.updateProjectionMatrix();
+ }
+ /**
+ * Calculates the focal length from the current .fov and .filmGauge.
+ */
+
+
+ getFocalLength() {
+ const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
+ return 0.5 * this.getFilmHeight() / vExtentSlope;
+ }
+
+ getEffectiveFOV() {
+ return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
+ }
+
+ getFilmWidth() {
+ // film not completely covered in portrait format (aspect < 1)
+ return this.filmGauge * Math.min(this.aspect, 1);
+ }
+
+ getFilmHeight() {
+ // film not completely covered in landscape format (aspect > 1)
+ return this.filmGauge / Math.max(this.aspect, 1);
+ }
+ /**
+ * 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
+ *
+ * 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.
+ */
+
+
+ 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();
+ }
+
+ clearViewOffset() {
+ if (this.view !== null) {
+ this.view.enabled = false;
+ }
+
+ this.updateProjectionMatrix();
+ }
+
+ 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.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;
+ }
+
+}
+
+PerspectiveCamera.prototype.isPerspectiveCamera = true;
+
+const fov = 90,
+ aspect = 1;
+
+class CubeCamera extends Object3D {
+ constructor(near, far, renderTarget) {
+ super();
+ this.type = 'CubeCamera';
+
+ if (renderTarget.isWebGLCubeRenderTarget !== true) {
+ console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
+ return;
+ }
+
+ this.renderTarget = renderTarget;
+ const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
+ cameraPX.layers = this.layers;
+ cameraPX.up.set(0, -1, 0);
+ cameraPX.lookAt(new Vector3(1, 0, 0));
+ this.add(cameraPX);
+ const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
+ cameraNX.layers = this.layers;
+ cameraNX.up.set(0, -1, 0);
+ cameraNX.lookAt(new Vector3(-1, 0, 0));
+ this.add(cameraNX);
+ const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
+ cameraPY.layers = this.layers;
+ cameraPY.up.set(0, 0, 1);
+ cameraPY.lookAt(new Vector3(0, 1, 0));
+ this.add(cameraPY);
+ const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
+ cameraNY.layers = this.layers;
+ cameraNY.up.set(0, 0, -1);
+ cameraNY.lookAt(new Vector3(0, -1, 0));
+ this.add(cameraNY);
+ const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
+ cameraPZ.layers = this.layers;
+ cameraPZ.up.set(0, -1, 0);
+ cameraPZ.lookAt(new Vector3(0, 0, 1));
+ this.add(cameraPZ);
+ const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
+ cameraNZ.layers = this.layers;
+ cameraNZ.up.set(0, -1, 0);
+ cameraNZ.lookAt(new Vector3(0, 0, -1));
+ this.add(cameraNZ);
+ }
+
+ update(renderer, scene) {
+ if (this.parent === null) this.updateMatrixWorld();
+ const renderTarget = this.renderTarget;
+ const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
+ const currentXrEnabled = renderer.xr.enabled;
+ const currentRenderTarget = renderer.getRenderTarget();
+ renderer.xr.enabled = false;
+ const generateMipmaps = renderTarget.texture.generateMipmaps;
+ renderTarget.texture.generateMipmaps = false;
+ renderer.setRenderTarget(renderTarget, 0);
+ renderer.render(scene, cameraPX);
+ renderer.setRenderTarget(renderTarget, 1);
+ renderer.render(scene, cameraNX);
+ renderer.setRenderTarget(renderTarget, 2);
+ renderer.render(scene, cameraPY);
+ renderer.setRenderTarget(renderTarget, 3);
+ renderer.render(scene, cameraNY);
+ renderer.setRenderTarget(renderTarget, 4);
+ renderer.render(scene, cameraPZ);
+ renderTarget.texture.generateMipmaps = generateMipmaps;
+ renderer.setRenderTarget(renderTarget, 5);
+ renderer.render(scene, cameraNZ);
+ renderer.setRenderTarget(currentRenderTarget);
+ renderer.xr.enabled = currentXrEnabled;
+ renderTarget.texture.needsPMREMUpdate = true;
+ }
+
+}
+
+class CubeTexture extends Texture {
+ constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
+ images = images !== undefined ? images : [];
+ mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
+ super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
+ this.flipY = false;
+ }
+
+ get images() {
+ return this.image;
+ }
+
+ set images(value) {
+ this.image = value;
+ }
+
+}
+
+CubeTexture.prototype.isCubeTexture = true;
+
+class WebGLCubeRenderTarget extends WebGLRenderTarget {
+ constructor(size, options, dummy) {
+ if (Number.isInteger(options)) {
+ console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
+ options = dummy;
+ }
+
+ super(size, size, options);
+ options = options || {}; // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
+ // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
+ // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
+ // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
+ // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
+ // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
+
+ this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
+ this.texture.isRenderTargetTexture = true;
+ this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
+ this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
+ }
+
+ fromEquirectangularTexture(renderer, texture) {
+ this.texture.type = texture.type;
+ this.texture.format = RGBAFormat; // see #18859
+
+ this.texture.encoding = texture.encoding;
+ 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 <begin_vertex>
+ #include <project_vertex>
+
+ }
+ `,
+ fragmentShader:
+ /* glsl */
+ `
+
+ uniform sampler2D tEquirect;
+
+ varying vec3 vWorldDirection;
+
+ #include <common>
+
+ 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; // Avoid blurred poles
+
+ 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;
+ }
+
+ clear(renderer, color, depth, stencil) {
+ const currentRenderTarget = renderer.getRenderTarget();
+
+ for (let i = 0; i < 6; i++) {
+ renderer.setRenderTarget(this, i);
+ renderer.clear(color, depth, stencil);
+ }
+
+ renderer.setRenderTarget(currentRenderTarget);
+ }
+
+}
+
+WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
+
+const _vector1 = /*@__PURE__*/new Vector3();
+
+const _vector2 = /*@__PURE__*/new Vector3();
+
+const _normalMatrix = /*@__PURE__*/new Matrix3();
+
+class Plane {
+ constructor(normal = new Vector3(1, 0, 0), constant = 0) {
+ // normal is assumed to be normalized
+ this.normal = normal;
+ this.constant = constant;
+ }
+
+ set(normal, constant) {
+ this.normal.copy(normal);
+ this.constant = constant;
+ return this;
+ }
+
+ setComponents(x, y, z, w) {
+ this.normal.set(x, y, z);
+ this.constant = w;
+ return this;
+ }
+
+ setFromNormalAndCoplanarPoint(normal, point) {
+ this.normal.copy(normal);
+ this.constant = -point.dot(this.normal);
+ return this;
+ }
+
+ setFromCoplanarPoints(a, b, c) {
+ const normal = _vector1.subVectors(c, b).cross(_vector2.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(plane) {
+ this.normal.copy(plane.normal);
+ this.constant = plane.constant;
+ return this;
+ }
+
+ normalize() {
+ // Note: will lead to a divide by zero if the plane is invalid.
+ const inverseNormalLength = 1.0 / this.normal.length();
+ this.normal.multiplyScalar(inverseNormalLength);
+ this.constant *= inverseNormalLength;
+ return this;
+ }
+
+ negate() {
+ this.constant *= -1;
+ this.normal.negate();
+ return this;
+ }
+
+ distanceToPoint(point) {
+ return this.normal.dot(point) + this.constant;
+ }
+
+ distanceToSphere(sphere) {
+ return this.distanceToPoint(sphere.center) - sphere.radius;
+ }
+
+ projectPoint(point, target) {
+ return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
+ }
+
+ intersectLine(line, target) {
+ const direction = line.delta(_vector1);
+ const denominator = this.normal.dot(direction);
+
+ if (denominator === 0) {
+ // line is coplanar, return origin
+ if (this.distanceToPoint(line.start) === 0) {
+ return target.copy(line.start);
+ } // Unsure if this is the correct method to handle this case.
+
+
+ return null;
+ }
+
+ const t = -(line.start.dot(this.normal) + this.constant) / denominator;
+
+ if (t < 0 || t > 1) {
+ return null;
+ }
+
+ return target.copy(direction).multiplyScalar(t).add(line.start);
+ }
+
+ intersectsLine(line) {
+ // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
+ const startSign = this.distanceToPoint(line.start);
+ const endSign = this.distanceToPoint(line.end);
+ return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
+ }
+
+ intersectsBox(box) {
+ return box.intersectsPlane(this);
+ }
+
+ intersectsSphere(sphere) {
+ return sphere.intersectsPlane(this);
+ }
+
+ coplanarPoint(target) {
+ return target.copy(this.normal).multiplyScalar(-this.constant);
+ }
+
+ 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;
+ }
+
+ translate(offset) {
+ this.constant -= offset.dot(this.normal);
+ return this;
+ }
+
+ equals(plane) {
+ return plane.normal.equals(this.normal) && plane.constant === this.constant;
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+}
+
+Plane.prototype.isPlane = true;
+
+const _sphere$2 = /*@__PURE__*/new Sphere();
+
+const _vector$7 = /*@__PURE__*/new Vector3();
+
+class 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];
+ }
+
+ 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;
+ }
+
+ copy(frustum) {
+ const planes = this.planes;
+
+ for (let i = 0; i < 6; i++) {
+ planes[i].copy(frustum.planes[i]);
+ }
+
+ return this;
+ }
+
+ setFromProjectionMatrix(m) {
+ 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();
+ 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(object) {
+ const geometry = object.geometry;
+ if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
+
+ _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
+
+ return this.intersectsSphere(_sphere$2);
+ }
+
+ intersectsSprite(sprite) {
+ _sphere$2.center.set(0, 0, 0);
+
+ _sphere$2.radius = 0.7071067811865476;
+
+ _sphere$2.applyMatrix4(sprite.matrixWorld);
+
+ return this.intersectsSphere(_sphere$2);
+ }
+
+ 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;
+ }
+
+ intersectsBox(box) {
+ const planes = this.planes;
+
+ for (let i = 0; i < 6; i++) {
+ const plane = planes[i]; // corner at max distance
+
+ _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
+ _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
+ _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
+
+ if (plane.distanceToPoint(_vector$7) < 0) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ containsPoint(point) {
+ const planes = this.planes;
+
+ for (let i = 0; i < 6; i++) {
+ if (planes[i].distanceToPoint(point) < 0) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+}
+
+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;
+ requestId = context.requestAnimationFrame(onAnimationFrame);
+ isAnimating = true;
+ },
+ stop: function () {
+ context.cancelAnimationFrame(requestId);
+ isAnimating = false;
+ },
+ setAnimationLoop: function (callback) {
+ animationLoop = callback;
+ },
+ setContext: function (value) {
+ context = value;
+ }
+ };
+}
+
+function WebGLAttributes(gl, capabilities) {
+ const isWebGL2 = capabilities.isWebGL2;
+ const buffers = new WeakMap();
+
+ function createBuffer(attribute, bufferType) {
+ const array = attribute.array;
+ const usage = attribute.usage;
+ const buffer = gl.createBuffer();
+ gl.bindBuffer(bufferType, buffer);
+ gl.bufferData(bufferType, array, usage);
+ attribute.onUploadCallback();
+ let type = gl.FLOAT;
+
+ if (array instanceof Float32Array) {
+ type = gl.FLOAT;
+ } else if (array instanceof Float64Array) {
+ console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
+ } else if (array instanceof Uint16Array) {
+ if (attribute.isFloat16BufferAttribute) {
+ if (isWebGL2) {
+ type = gl.HALF_FLOAT;
+ } else {
+ console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
+ }
+ } 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;
+ }
+
+ return {
+ buffer: buffer,
+ type: type,
+ bytesPerElement: array.BYTES_PER_ELEMENT,
+ version: attribute.version
+ };
+ }
+
+ function updateBuffer(buffer, attribute, bufferType) {
+ const array = attribute.array;
+ const updateRange = attribute.updateRange;
+ gl.bindBuffer(bufferType, buffer);
+
+ if (updateRange.count === -1) {
+ // Not using update ranges
+ gl.bufferSubData(bufferType, 0, array);
+ } else {
+ if (isWebGL2) {
+ gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
+ } else {
+ gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
+ }
+
+ updateRange.count = -1; // reset range
+ }
+ } //
+
+
+ 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.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;
+ }
+
+ if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
+ const data = buffers.get(attribute);
+
+ if (data === undefined) {
+ buffers.set(attribute, createBuffer(attribute, bufferType));
+ } else if (data.version < attribute.version) {
+ updateBuffer(data.buffer, attribute, bufferType);
+ data.version = attribute.version;
+ }
+ }
+
+ return {
+ get: get,
+ remove: remove,
+ update: update
+ };
+}
+
+class PlaneGeometry extends BufferGeometry {
+ constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
+ super();
+ this.type = 'PlaneGeometry';
+ this.parameters = {
+ width: width,
+ height: height,
+ widthSegments: widthSegments,
+ heightSegments: 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));
+ }
+
+ static fromJSON(data) {
+ return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
+ }
+
+}
+
+var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
+
+var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
+
+var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
+
+var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
+
+var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
+
+var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
+
+var begin_vertex = "vec3 transformed = vec3( position );";
+
+var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
+
+var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn 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\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif";
+
+var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
+
+var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
+
+var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
+
+var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
+
+var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
+
+var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
+
+var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
+
+var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
+
+var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\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; }\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 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
+
+var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 ) + 0.5;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\treturn texture2D( envMap, uv ).rgb;\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
+
+var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
+
+var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
+
+var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
+
+var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
+
+var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
+
+var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
+
+var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
+
+var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
+
+var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
+
+var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
+
+var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
+
+var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
+
+var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
+
+var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
+
+var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
+
+var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
+
+var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
+
+var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
+
+var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
+
+var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
+
+var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
+
+var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
+
+var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
+
+var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
+
+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\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
+
+var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\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\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
+
+var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\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\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
+
+var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
+
+var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
+
+var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
+
+var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
+
+var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
+
+var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
+
+var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
+
+var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
+
+var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
+
+var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
+
+var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
+
+var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
+
+var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
+
+var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
+
+var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
+
+var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
+
+var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
+
+var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
+
+var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
+
+var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
+
+var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
+
+var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
+
+var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
+
+var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif";
+
+var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
+
+var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
+
+var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn 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\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
+
+var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
+
+var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
+
+var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
+
+var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
+
+var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
+
+var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
+
+var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
+
+var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
+
+var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
+
+var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
+
+var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
+
+var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
+
+var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
+
+var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
+
+var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
+
+var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
+
+var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_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\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
+
+var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif";
+
+var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
+
+var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
+
+var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
+
+var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
+
+var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
+
+var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
+
+var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
+
+var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
+
+const vertex$g = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
+const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
+
+const vertex$f = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
+const fragment$f = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
+
+const vertex$e = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
+const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
+
+const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
+const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
+
+const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
+const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
+
+const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
+const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
+
+const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
+const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
+
+const vertex$9 = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
+const fragment$9 = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
+
+const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
+const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
+
+const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
+const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
+
+const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
+const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
+
+const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
+const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
+
+const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
+const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
+
+const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
+const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
+
+const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
+const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
+
+const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
+const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
+
+const ShaderChunk = {
+ alphamap_fragment: alphamap_fragment,
+ alphamap_pars_fragment: alphamap_pars_fragment,
+ alphatest_fragment: alphatest_fragment,
+ alphatest_pars_fragment: alphatest_pars_fragment,
+ aomap_fragment: aomap_fragment,
+ aomap_pars_fragment: aomap_pars_fragment,
+ begin_vertex: begin_vertex,
+ beginnormal_vertex: beginnormal_vertex,
+ bsdfs: bsdfs,
+ bumpmap_pars_fragment: bumpmap_pars_fragment,
+ clipping_planes_fragment: clipping_planes_fragment,
+ clipping_planes_pars_fragment: clipping_planes_pars_fragment,
+ clipping_planes_pars_vertex: clipping_planes_pars_vertex,
+ clipping_planes_vertex: clipping_planes_vertex,
+ color_fragment: color_fragment,
+ color_pars_fragment: color_pars_fragment,
+ color_pars_vertex: color_pars_vertex,
+ color_vertex: color_vertex,
+ common: common,
+ cube_uv_reflection_fragment: cube_uv_reflection_fragment,
+ defaultnormal_vertex: defaultnormal_vertex,
+ displacementmap_pars_vertex: displacementmap_pars_vertex,
+ displacementmap_vertex: displacementmap_vertex,
+ emissivemap_fragment: emissivemap_fragment,
+ emissivemap_pars_fragment: emissivemap_pars_fragment,
+ encodings_fragment: encodings_fragment,
+ encodings_pars_fragment: encodings_pars_fragment,
+ envmap_fragment: envmap_fragment,
+ envmap_common_pars_fragment: envmap_common_pars_fragment,
+ envmap_pars_fragment: envmap_pars_fragment,
+ envmap_pars_vertex: envmap_pars_vertex,
+ envmap_physical_pars_fragment: envmap_physical_pars_fragment,
+ envmap_vertex: envmap_vertex,
+ fog_vertex: fog_vertex,
+ fog_pars_vertex: fog_pars_vertex,
+ fog_fragment: fog_fragment,
+ fog_pars_fragment: fog_pars_fragment,
+ gradientmap_pars_fragment: gradientmap_pars_fragment,
+ lightmap_fragment: lightmap_fragment,
+ lightmap_pars_fragment: lightmap_pars_fragment,
+ lights_lambert_vertex: lights_lambert_vertex,
+ lights_pars_begin: lights_pars_begin,
+ lights_toon_fragment: lights_toon_fragment,
+ lights_toon_pars_fragment: lights_toon_pars_fragment,
+ lights_phong_fragment: lights_phong_fragment,
+ lights_phong_pars_fragment: lights_phong_pars_fragment,
+ lights_physical_fragment: lights_physical_fragment,
+ lights_physical_pars_fragment: lights_physical_pars_fragment,
+ lights_fragment_begin: lights_fragment_begin,
+ lights_fragment_maps: lights_fragment_maps,
+ lights_fragment_end: lights_fragment_end,
+ logdepthbuf_fragment: logdepthbuf_fragment,
+ logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
+ logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
+ logdepthbuf_vertex: logdepthbuf_vertex,
+ map_fragment: map_fragment,
+ map_pars_fragment: map_pars_fragment,
+ map_particle_fragment: map_particle_fragment,
+ map_particle_pars_fragment: map_particle_pars_fragment,
+ metalnessmap_fragment: metalnessmap_fragment,
+ metalnessmap_pars_fragment: metalnessmap_pars_fragment,
+ morphnormal_vertex: morphnormal_vertex,
+ morphtarget_pars_vertex: morphtarget_pars_vertex,
+ morphtarget_vertex: morphtarget_vertex,
+ normal_fragment_begin: normal_fragment_begin,
+ normal_fragment_maps: normal_fragment_maps,
+ normal_pars_fragment: normal_pars_fragment,
+ normal_pars_vertex: normal_pars_vertex,
+ normal_vertex: normal_vertex,
+ normalmap_pars_fragment: normalmap_pars_fragment,
+ clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
+ clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
+ clearcoat_pars_fragment: clearcoat_pars_fragment,
+ output_fragment: output_fragment,
+ packing: packing,
+ premultiplied_alpha_fragment: premultiplied_alpha_fragment,
+ project_vertex: project_vertex,
+ dithering_fragment: dithering_fragment,
+ dithering_pars_fragment: dithering_pars_fragment,
+ roughnessmap_fragment: roughnessmap_fragment,
+ roughnessmap_pars_fragment: roughnessmap_pars_fragment,
+ shadowmap_pars_fragment: shadowmap_pars_fragment,
+ shadowmap_pars_vertex: shadowmap_pars_vertex,
+ shadowmap_vertex: shadowmap_vertex,
+ shadowmask_pars_fragment: shadowmask_pars_fragment,
+ skinbase_vertex: skinbase_vertex,
+ skinning_pars_vertex: skinning_pars_vertex,
+ skinning_vertex: skinning_vertex,
+ skinnormal_vertex: skinnormal_vertex,
+ specularmap_fragment: specularmap_fragment,
+ specularmap_pars_fragment: specularmap_pars_fragment,
+ tonemapping_fragment: tonemapping_fragment,
+ tonemapping_pars_fragment: tonemapping_pars_fragment,
+ transmission_fragment: transmission_fragment,
+ transmission_pars_fragment: transmission_pars_fragment,
+ uv_pars_fragment: uv_pars_fragment,
+ uv_pars_vertex: uv_pars_vertex,
+ uv_vertex: uv_vertex,
+ uv2_pars_fragment: uv2_pars_fragment,
+ uv2_pars_vertex: uv2_pars_vertex,
+ uv2_vertex: uv2_vertex,
+ worldpos_vertex: worldpos_vertex,
+ background_vert: vertex$g,
+ background_frag: fragment$g,
+ cube_vert: vertex$f,
+ cube_frag: fragment$f,
+ depth_vert: vertex$e,
+ depth_frag: fragment$e,
+ distanceRGBA_vert: vertex$d,
+ distanceRGBA_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
+};
+
+/**
+ * Uniforms library for shared webgl shaders
+ */
+
+const UniformsLib = {
+ common: {
+ diffuse: {
+ value: new Color(0xffffff)
+ },
+ opacity: {
+ value: 1.0
+ },
+ map: {
+ value: null
+ },
+ uvTransform: {
+ value: new Matrix3()
+ },
+ uv2Transform: {
+ value: new Matrix3()
+ },
+ alphaMap: {
+ value: null
+ },
+ alphaTest: {
+ value: 0
+ }
+ },
+ specularmap: {
+ specularMap: {
+ value: null
+ }
+ },
+ envmap: {
+ envMap: {
+ value: null
+ },
+ flipEnvMap: {
+ value: -1
+ },
+ reflectivity: {
+ value: 1.0
+ },
+ // basic, lambert, phong
+ ior: {
+ value: 1.5
+ },
+ // standard, physical
+ refractionRatio: {
+ value: 0.98
+ }
+ },
+ aomap: {
+ aoMap: {
+ value: null
+ },
+ aoMapIntensity: {
+ value: 1
+ }
+ },
+ lightmap: {
+ lightMap: {
+ value: null
+ },
+ lightMapIntensity: {
+ value: 1
+ }
+ },
+ emissivemap: {
+ emissiveMap: {
+ value: null
+ }
+ },
+ bumpmap: {
+ bumpMap: {
+ value: null
+ },
+ bumpScale: {
+ value: 1
+ }
+ },
+ normalmap: {
+ normalMap: {
+ value: null
+ },
+ normalScale: {
+ value: new Vector2(1, 1)
+ }
+ },
+ displacementmap: {
+ displacementMap: {
+ value: null
+ },
+ displacementScale: {
+ value: 1
+ },
+ displacementBias: {
+ value: 0
+ }
+ },
+ roughnessmap: {
+ roughnessMap: {
+ value: null
+ }
+ },
+ metalnessmap: {
+ metalnessMap: {
+ value: null
+ }
+ },
+ gradientmap: {
+ gradientMap: {
+ value: null
+ }
+ },
+ fog: {
+ fogDensity: {
+ value: 0.00025
+ },
+ fogNear: {
+ value: 1
+ },
+ fogFar: {
+ value: 2000
+ },
+ fogColor: {
+ value: new Color(0xffffff)
+ }
+ },
+ lights: {
+ ambientLightColor: {
+ value: []
+ },
+ lightProbe: {
+ value: []
+ },
+ directionalLights: {
+ value: [],
+ properties: {
+ direction: {},
+ color: {}
+ }
+ },
+ directionalLightShadows: {
+ value: [],
+ properties: {
+ shadowBias: {},
+ shadowNormalBias: {},
+ shadowRadius: {},
+ shadowMapSize: {}
+ }
+ },
+ directionalShadowMap: {
+ value: []
+ },
+ directionalShadowMatrix: {
+ value: []
+ },
+ spotLights: {
+ value: [],
+ properties: {
+ color: {},
+ position: {},
+ direction: {},
+ distance: {},
+ coneCos: {},
+ penumbraCos: {},
+ decay: {}
+ }
+ },
+ spotLightShadows: {
+ value: [],
+ properties: {
+ shadowBias: {},
+ shadowNormalBias: {},
+ shadowRadius: {},
+ shadowMapSize: {}
+ }
+ },
+ spotShadowMap: {
+ value: []
+ },
+ spotShadowMatrix: {
+ value: []
+ },
+ pointLights: {
+ value: [],
+ properties: {
+ color: {},
+ position: {},
+ decay: {},
+ distance: {}
+ }
+ },
+ pointLightShadows: {
+ value: [],
+ properties: {
+ shadowBias: {},
+ shadowNormalBias: {},
+ shadowRadius: {},
+ shadowMapSize: {},
+ shadowCameraNear: {},
+ shadowCameraFar: {}
+ }
+ },
+ pointShadowMap: {
+ value: []
+ },
+ 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
+ }
+ },
+ points: {
+ diffuse: {
+ value: new Color(0xffffff)
+ },
+ opacity: {
+ value: 1.0
+ },
+ size: {
+ value: 1.0
+ },
+ scale: {
+ value: 1.0
+ },
+ map: {
+ value: null
+ },
+ alphaMap: {
+ value: null
+ },
+ alphaTest: {
+ value: 0
+ },
+ uvTransform: {
+ value: new Matrix3()
+ }
+ },
+ sprite: {
+ diffuse: {
+ value: new Color(0xffffff)
+ },
+ opacity: {
+ value: 1.0
+ },
+ center: {
+ value: new Vector2(0.5, 0.5)
+ },
+ rotation: {
+ value: 0.0
+ },
+ map: {
+ value: null
+ },
+ alphaMap: {
+ value: null
+ },
+ alphaTest: {
+ value: 0
+ },
+ uvTransform: {
+ value: new Matrix3()
+ }
+ }
+};
+
+const ShaderLib = {
+ basic: {
+ uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
+ vertexShader: ShaderChunk.meshbasic_vert,
+ fragmentShader: ShaderChunk.meshbasic_frag
+ },
+ lambert: {
+ uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
+ emissive: {
+ value: new Color(0x000000)
+ }
+ }]),
+ vertexShader: ShaderChunk.meshlambert_vert,
+ fragmentShader: ShaderChunk.meshlambert_frag
+ },
+ phong: {
+ uniforms: 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: new Color(0x000000)
+ },
+ specular: {
+ value: new Color(0x111111)
+ },
+ shininess: {
+ value: 30
+ }
+ }]),
+ vertexShader: ShaderChunk.meshphong_vert,
+ fragmentShader: ShaderChunk.meshphong_frag
+ },
+ standard: {
+ uniforms: 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: new Color(0x000000)
+ },
+ roughness: {
+ value: 1.0
+ },
+ metalness: {
+ value: 0.0
+ },
+ envMapIntensity: {
+ value: 1
+ } // temporary
+
+ }]),
+ vertexShader: ShaderChunk.meshphysical_vert,
+ fragmentShader: ShaderChunk.meshphysical_frag
+ },
+ toon: {
+ uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
+ emissive: {
+ value: new Color(0x000000)
+ }
+ }]),
+ vertexShader: ShaderChunk.meshtoon_vert,
+ fragmentShader: ShaderChunk.meshtoon_frag
+ },
+ matcap: {
+ uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
+ matcap: {
+ value: null
+ }
+ }]),
+ vertexShader: ShaderChunk.meshmatcap_vert,
+ fragmentShader: ShaderChunk.meshmatcap_frag
+ },
+ points: {
+ uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
+ vertexShader: ShaderChunk.points_vert,
+ fragmentShader: ShaderChunk.points_frag
+ },
+ dashed: {
+ uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
+ scale: {
+ value: 1
+ },
+ dashSize: {
+ value: 1
+ },
+ totalSize: {
+ value: 2
+ }
+ }]),
+ vertexShader: ShaderChunk.linedashed_vert,
+ fragmentShader: ShaderChunk.linedashed_frag
+ },
+ depth: {
+ uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
+ vertexShader: ShaderChunk.depth_vert,
+ fragmentShader: ShaderChunk.depth_frag
+ },
+ normal: {
+ uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
+ opacity: {
+ value: 1.0
+ }
+ }]),
+ vertexShader: ShaderChunk.meshnormal_vert,
+ fragmentShader: ShaderChunk.meshnormal_frag
+ },
+ sprite: {
+ uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
+ vertexShader: ShaderChunk.sprite_vert,
+ fragmentShader: ShaderChunk.sprite_frag
+ },
+ background: {
+ uniforms: {
+ uvTransform: {
+ value: new Matrix3()
+ },
+ t2D: {
+ value: null
+ }
+ },
+ vertexShader: ShaderChunk.background_vert,
+ fragmentShader: ShaderChunk.background_frag
+ },
+
+ /* -------------------------------------------------------------------------
+ // Cube map shader
+ ------------------------------------------------------------------------- */
+ cube: {
+ uniforms: mergeUniforms([UniformsLib.envmap, {
+ opacity: {
+ value: 1.0
+ }
+ }]),
+ vertexShader: ShaderChunk.cube_vert,
+ fragmentShader: ShaderChunk.cube_frag
+ },
+ equirect: {
+ uniforms: {
+ tEquirect: {
+ value: null
+ }
+ },
+ vertexShader: ShaderChunk.equirect_vert,
+ fragmentShader: ShaderChunk.equirect_frag
+ },
+ distanceRGBA: {
+ uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
+ referencePosition: {
+ value: new Vector3()
+ },
+ nearDistance: {
+ value: 1
+ },
+ farDistance: {
+ value: 1000
+ }
+ }]),
+ vertexShader: ShaderChunk.distanceRGBA_vert,
+ fragmentShader: ShaderChunk.distanceRGBA_frag
+ },
+ shadow: {
+ uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
+ color: {
+ value: new Color(0x00000)
+ },
+ opacity: {
+ value: 1.0
+ }
+ }]),
+ vertexShader: ShaderChunk.shadow_vert,
+ fragmentShader: ShaderChunk.shadow_frag
+ }
+};
+ShaderLib.physical = {
+ uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
+ clearcoat: {
+ value: 0
+ },
+ clearcoatMap: {
+ value: null
+ },
+ clearcoatRoughness: {
+ value: 0
+ },
+ clearcoatRoughnessMap: {
+ value: null
+ },
+ clearcoatNormalScale: {
+ value: new Vector2(1, 1)
+ },
+ clearcoatNormalMap: {
+ value: null
+ },
+ sheen: {
+ value: 0
+ },
+ sheenColor: {
+ value: new Color(0x000000)
+ },
+ sheenColorMap: {
+ value: null
+ },
+ sheenRoughness: {
+ value: 1
+ },
+ sheenRoughnessMap: {
+ value: null
+ },
+ transmission: {
+ value: 0
+ },
+ transmissionMap: {
+ value: null
+ },
+ transmissionSamplerSize: {
+ value: new Vector2()
+ },
+ transmissionSamplerMap: {
+ value: null
+ },
+ thickness: {
+ value: 0
+ },
+ thicknessMap: {
+ value: null
+ },
+ attenuationDistance: {
+ value: 0
+ },
+ attenuationColor: {
+ value: new Color(0x000000)
+ },
+ specularIntensity: {
+ value: 1
+ },
+ specularIntensityMap: {
+ value: null
+ },
+ specularColor: {
+ value: new Color(1, 1, 1)
+ },
+ specularColorMap: {
+ value: null
+ }
+ }]),
+ vertexShader: ShaderChunk.meshphysical_vert,
+ fragmentShader: ShaderChunk.meshphysical_frag
+};
+
+function WebGLBackground(renderer, cubemaps, state, objects, alpha, premultipliedAlpha) {
+ const clearColor = new Color(0x000000);
+ let clearAlpha = alpha === true ? 0 : 1;
+ let planeMesh;
+ let boxMesh;
+ let currentBackground = null;
+ let currentBackgroundVersion = 0;
+ let currentTonemapping = null;
+
+ function render(renderList, scene) {
+ let forceClear = false;
+ let background = scene.isScene === true ? scene.background : null;
+
+ if (background && background.isTexture) {
+ background = cubemaps.get(background);
+ } // Ignore background in AR
+ // TODO: Reconsider this.
+
+
+ const xr = renderer.xr;
+ const session = xr.getSession && xr.getSession();
+
+ if (session && session.environmentBlendMode === 'additive') {
+ background = null;
+ }
+
+ if (background === null) {
+ setClear(clearColor, clearAlpha);
+ } else if (background && background.isColor) {
+ setClear(background, 1);
+ forceClear = true;
+ }
+
+ if (renderer.autoClear || forceClear) {
+ renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
+ }
+
+ if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
+ if (boxMesh === undefined) {
+ boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
+ name: 'BackgroundCubeMaterial',
+ uniforms: cloneUniforms(ShaderLib.cube.uniforms),
+ vertexShader: ShaderLib.cube.vertexShader,
+ fragmentShader: ShaderLib.cube.fragmentShader,
+ side: BackSide,
+ depthTest: false,
+ depthWrite: false,
+ fog: false
+ }));
+ boxMesh.geometry.deleteAttribute('normal');
+ boxMesh.geometry.deleteAttribute('uv');
+
+ boxMesh.onBeforeRender = function (renderer, scene, camera) {
+ this.matrixWorld.copyPosition(camera.matrixWorld);
+ }; // enable code injection for non-built-in material
+
+
+ Object.defineProperty(boxMesh.material, 'envMap', {
+ get: function () {
+ return this.uniforms.envMap.value;
+ }
+ });
+ objects.update(boxMesh);
+ }
+
+ boxMesh.material.uniforms.envMap.value = background;
+ boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
+
+ if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
+ boxMesh.material.needsUpdate = true;
+ currentBackground = background;
+ currentBackgroundVersion = background.version;
+ currentTonemapping = renderer.toneMapping;
+ } // push to the pre-sorted opaque render list
+
+
+ renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
+ } else if (background && background.isTexture) {
+ if (planeMesh === undefined) {
+ 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
+ }));
+ planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
+
+ Object.defineProperty(planeMesh.material, 'map', {
+ get: function () {
+ return this.uniforms.t2D.value;
+ }
+ });
+ objects.update(planeMesh);
+ }
+
+ planeMesh.material.uniforms.t2D.value = background;
+
+ 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;
+ } // push to the pre-sorted opaque render list
+
+
+ renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
+ }
+ }
+
+ function setClear(color, alpha) {
+ state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
+ }
+
+ return {
+ getClearColor: function () {
+ return clearColor;
+ },
+ setClearColor: function (color, alpha = 1) {
+ clearColor.set(color);
+ clearAlpha = alpha;
+ setClear(clearColor, clearAlpha);
+ },
+ getClearAlpha: function () {
+ return clearAlpha;
+ },
+ setClearAlpha: function (alpha) {
+ clearAlpha = alpha;
+ setClear(clearColor, clearAlpha);
+ },
+ render: render
+ };
+}
+
+function WebGLBindingStates(gl, extensions, attributes, capabilities) {
+ const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
+ const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
+ const vaoAvailable = capabilities.isWebGL2 || extension !== null;
+ const bindingStates = {};
+ const defaultState = createBindingState(null);
+ let currentState = defaultState;
+
+ function setup(object, material, program, geometry, index) {
+ let updateBuffers = false;
+
+ if (vaoAvailable) {
+ const state = getBindingState(geometry, program, material);
+
+ if (currentState !== state) {
+ currentState = state;
+ bindVertexArrayObject(currentState.object);
+ }
+
+ updateBuffers = needsUpdate(geometry, index);
+ if (updateBuffers) saveCache(geometry, index);
+ } else {
+ const wireframe = material.wireframe === true;
+
+ if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
+ currentState.geometry = geometry.id;
+ currentState.program = program.id;
+ currentState.wireframe = wireframe;
+ updateBuffers = true;
+ }
+ }
+
+ if (object.isInstancedMesh === true) {
+ updateBuffers = true;
+ }
+
+ if (index !== null) {
+ attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
+ }
+
+ if (updateBuffers) {
+ setupVertexAttributes(object, material, program, geometry);
+
+ if (index !== null) {
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
+ }
+ }
+ }
+
+ function createVertexArrayObject() {
+ if (capabilities.isWebGL2) return gl.createVertexArray();
+ return extension.createVertexArrayOES();
+ }
+
+ function bindVertexArrayObject(vao) {
+ if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
+ return extension.bindVertexArrayOES(vao);
+ }
+
+ function deleteVertexArrayObject(vao) {
+ if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
+ return extension.deleteVertexArrayOES(vao);
+ }
+
+ function getBindingState(geometry, program, material) {
+ const wireframe = material.wireframe === true;
+ let programMap = bindingStates[geometry.id];
+
+ if (programMap === undefined) {
+ programMap = {};
+ bindingStates[geometry.id] = programMap;
+ }
+
+ let stateMap = programMap[program.id];
+
+ if (stateMap === undefined) {
+ stateMap = {};
+ programMap[program.id] = stateMap;
+ }
+
+ let state = stateMap[wireframe];
+
+ if (state === undefined) {
+ 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: newAttributes,
+ enabledAttributes: enabledAttributes,
+ attributeDivisors: attributeDivisors,
+ object: vao,
+ attributes: {},
+ index: null
+ };
+ }
+
+ function needsUpdate(geometry, index) {
+ const cachedAttributes = currentState.attributes;
+ const geometryAttributes = geometry.attributes;
+ let attributesNum = 0;
+
+ for (const key in geometryAttributes) {
+ const cachedAttribute = cachedAttributes[key];
+ const geometryAttribute = geometryAttributes[key];
+ if (cachedAttribute === undefined) return true;
+ if (cachedAttribute.attribute !== geometryAttribute) return true;
+ if (cachedAttribute.data !== geometryAttribute.data) return true;
+ attributesNum++;
+ }
+
+ if (currentState.attributesNum !== attributesNum) return true;
+ if (currentState.index !== index) return true;
+ return false;
+ }
+
+ function saveCache(geometry, index) {
+ const cache = {};
+ const attributes = geometry.attributes;
+ let attributesNum = 0;
+
+ for (const key in attributes) {
+ const attribute = attributes[key];
+ const data = {};
+ data.attribute = attribute;
+
+ if (attribute.data) {
+ data.data = attribute.data;
+ }
+
+ cache[key] = 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) {
+ const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
+ extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](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) {
+ if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
+ gl.vertexAttribIPointer(index, size, type, stride, offset);
+ } else {
+ gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
+ }
+ }
+
+ function setupVertexAttributes(object, material, program, geometry) {
+ if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
+ if (extensions.get('ANGLE_instanced_arrays') === null) return;
+ }
+
+ 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 === undefined) {
+ if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
+ if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
+ }
+
+ if (geometryAttribute !== undefined) {
+ const normalized = geometryAttribute.normalized;
+ const size = geometryAttribute.itemSize;
+ const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
+
+ if (attribute === undefined) continue;
+ const buffer = attribute.buffer;
+ const type = attribute.type;
+ const bytesPerElement = attribute.bytesPerElement;
+
+ if (geometryAttribute.isInterleavedBufferAttribute) {
+ const data = geometryAttribute.data;
+ const stride = data.stride;
+ const offset = geometryAttribute.offset;
+
+ if (data && data.isInstancedInterleavedBuffer) {
+ for (let i = 0; i < programAttribute.locationSize; i++) {
+ enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
+ }
+
+ if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
+ 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);
+ }
+ } else {
+ if (geometryAttribute.isInstancedBufferAttribute) {
+ for (let i = 0; i < programAttribute.locationSize; i++) {
+ enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
+ }
+
+ if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
+ 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);
+ }
+ }
+ } else if (materialDefaultAttributeValues !== undefined) {
+ const value = materialDefaultAttributeValues[name];
+
+ if (value !== undefined) {
+ 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 programMap = bindingStates[geometryId];
+
+ 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] === undefined) return;
+ const programMap = bindingStates[geometry.id];
+
+ 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 programMap = bindingStates[geometryId];
+ if (programMap[program.id] === undefined) continue;
+ const stateMap = programMap[program.id];
+
+ for (const wireframe in stateMap) {
+ deleteVertexArrayObject(stateMap[wireframe].object);
+ delete stateMap[wireframe];
+ }
+
+ delete programMap[program.id];
+ }
+ }
+
+ function reset() {
+ resetDefaultState();
+ if (currentState === defaultState) return;
+ currentState = defaultState;
+ bindVertexArrayObject(currentState.object);
+ } // for backward-compatilibity
+
+
+ function resetDefaultState() {
+ defaultState.geometry = null;
+ defaultState.program = null;
+ defaultState.wireframe = false;
+ }
+
+ return {
+ setup: setup,
+ reset: reset,
+ resetDefaultState: resetDefaultState,
+ dispose: dispose,
+ releaseStatesOfGeometry: releaseStatesOfGeometry,
+ releaseStatesOfProgram: releaseStatesOfProgram,
+ initAttributes: initAttributes,
+ enableAttribute: enableAttribute,
+ disableUnusedAttributes: disableUnusedAttributes
+ };
+}
+
+function WebGLBufferRenderer(gl, extensions, info, capabilities) {
+ const isWebGL2 = capabilities.isWebGL2;
+ 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;
+ let extension, methodName;
+
+ if (isWebGL2) {
+ extension = gl;
+ methodName = 'drawArraysInstanced';
+ } else {
+ extension = extensions.get('ANGLE_instanced_arrays');
+ methodName = 'drawArraysInstancedANGLE';
+
+ if (extension === null) {
+ console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
+ return;
+ }
+ }
+
+ extension[methodName](mode, start, count, primcount);
+ info.update(count, mode, primcount);
+ } //
+
+
+ this.setMode = setMode;
+ this.render = render;
+ this.renderInstances = renderInstances;
+}
+
+function WebGLCapabilities(gl, extensions, parameters) {
+ let maxAnisotropy;
+
+ function getMaxAnisotropy() {
+ if (maxAnisotropy !== undefined) 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 getMaxPrecision(precision) {
+ if (precision === 'highp') {
+ if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
+ return 'highp';
+ }
+
+ precision = 'mediump';
+ }
+
+ if (precision === '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';
+ }
+
+ const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
+ let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
+ const maxPrecision = getMaxPrecision(precision);
+
+ if (maxPrecision !== precision) {
+ console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
+ precision = maxPrecision;
+ }
+
+ const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
+ const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
+ 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 vertexTextures = maxVertexTextures > 0;
+ const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
+ const floatVertexTextures = vertexTextures && floatFragmentTextures;
+ const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
+ return {
+ isWebGL2: isWebGL2,
+ drawBuffers: drawBuffers,
+ getMaxAnisotropy: getMaxAnisotropy,
+ getMaxPrecision: getMaxPrecision,
+ precision: precision,
+ logarithmicDepthBuffer: logarithmicDepthBuffer,
+ maxTextures: maxTextures,
+ maxVertexTextures: maxVertexTextures,
+ maxTextureSize: maxTextureSize,
+ maxCubemapSize: maxCubemapSize,
+ maxAttributes: maxAttributes,
+ maxVertexUniforms: maxVertexUniforms,
+ maxVaryings: maxVaryings,
+ maxFragmentUniforms: maxFragmentUniforms,
+ vertexTextures: vertexTextures,
+ floatFragmentTextures: floatFragmentTextures,
+ floatVertexTextures: floatVertexTextures,
+ maxSamples: maxSamples
+ };
+}
+
+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, camera) {
+ 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;
+ globalState = projectPlanes(planes, camera, 0);
+ numGlobalPlanes = planes.length;
+ return enabled;
+ };
+
+ this.beginShadows = function () {
+ renderingShadows = true;
+ projectPlanes(null);
+ };
+
+ this.endShadows = function () {
+ renderingShadows = false;
+ resetGlobalState();
+ };
+
+ 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) {
+ // there's no local clipping
+ if (renderingShadows) {
+ // there's no global clipping
+ projectPlanes(null);
+ } else {
+ resetGlobalState();
+ }
+ } else {
+ const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
+ lGlobal = nGlobal * 4;
+ let dstArray = materialProperties.clippingState || null;
+ uniform.value = dstArray; // ensure unique state
+
+ 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;
+ }
+}
+
+function WebGLCubeMaps(renderer) {
+ let cubemaps = new WeakMap();
+
+ function mapTextureMapping(texture, mapping) {
+ if (mapping === EquirectangularReflectionMapping) {
+ texture.mapping = CubeReflectionMapping;
+ } else if (mapping === EquirectangularRefractionMapping) {
+ texture.mapping = CubeRefractionMapping;
+ }
+
+ return texture;
+ }
+
+ function get(texture) {
+ if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
+ 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 / 2);
+ renderTarget.fromEquirectangularTexture(renderer, texture);
+ cubemaps.set(texture, renderTarget);
+ texture.addEventListener('dispose', onTextureDispose);
+ return mapTextureMapping(renderTarget.texture, texture.mapping);
+ } else {
+ // image not yet ready. try the conversion next frame
+ return null;
+ }
+ }
+ }
+ }
+
+ return texture;
+ }
+
+ function onTextureDispose(event) {
+ const texture = event.target;
+ texture.removeEventListener('dispose', onTextureDispose);
+ const cubemap = cubemaps.get(texture);
+
+ if (cubemap !== undefined) {
+ cubemaps.delete(texture);
+ cubemap.dispose();
+ }
+ }
+
+ function dispose() {
+ cubemaps = new WeakMap();
+ }
+
+ return {
+ get: get,
+ dispose: dispose
+ };
+}
+
+class OrthographicCamera extends Camera {
+ constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
+ super();
+ 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;
+ }
+
+ 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();
+ }
+
+ clearViewOffset() {
+ if (this.view !== null) {
+ this.view.enabled = false;
+ }
+
+ this.updateProjectionMatrix();
+ }
+
+ 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.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;
+ }
+
+}
+
+OrthographicCamera.prototype.isOrthographicCamera = true;
+
+class RawShaderMaterial extends ShaderMaterial {
+ constructor(parameters) {
+ super(parameters);
+ this.type = 'RawShaderMaterial';
+ }
+
+}
+
+RawShaderMaterial.prototype.isRawShaderMaterial = true;
+
+const LOD_MIN = 4;
+const LOD_MAX = 8;
+const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
+// chosen to approximate a Trowbridge-Reitz distribution function times the
+// geometric shadowing function. These sigma values squared must match the
+// variance #defines in cube_uv_reflection_fragment.glsl.js.
+
+const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
+const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
+// samples and exit early, but not recompile the shader.
+
+const MAX_SAMPLES = 20;
+
+const _flatCamera = /*@__PURE__*/new OrthographicCamera();
+
+const {
+ _lodPlanes,
+ _sizeLods,
+ _sigmas
+} = /*@__PURE__*/_createPlanes();
+
+const _clearColor = /*@__PURE__*/new Color();
+
+let _oldTarget = null; // Golden Ratio
+
+const PHI = (1 + Math.sqrt(5)) / 2;
+const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
+// same axis), used as axis directions evenly spread on a sphere.
+
+const _axisDirections = [/*@__PURE__*/new Vector3(1, 1, 1), /*@__PURE__*/new Vector3(-1, 1, 1), /*@__PURE__*/new Vector3(1, 1, -1), /*@__PURE__*/new Vector3(-1, 1, -1), /*@__PURE__*/new Vector3(0, PHI, INV_PHI), /*@__PURE__*/new Vector3(0, PHI, -INV_PHI), /*@__PURE__*/new Vector3(INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(-INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(PHI, INV_PHI, 0), /*@__PURE__*/new Vector3(-PHI, INV_PHI, 0)];
+/**
+ * This class generates a Prefiltered, Mipmapped Radiance Environment Map
+ * (PMREM) from a cubeMap environment texture. This allows different levels of
+ * blur to be quickly accessed based on material roughness. It is packed into a
+ * special CubeUV format that allows us to perform custom interpolation so that
+ * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
+ * chain, it only goes down to the LOD_MIN level (above), and then creates extra
+ * even more filtered 'mips' at the same LOD_MIN resolution, associated with
+ * higher roughness levels. In this way we maintain resolution to smoothly
+ * interpolate diffuse lighting while limiting sampling computation.
+ *
+ * Paper: Fast, Accurate Image-Based Lighting
+ * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
+*/
+
+class PMREMGenerator {
+ constructor(renderer) {
+ this._renderer = renderer;
+ this._pingPongRenderTarget = null;
+ this._blurMaterial = _getBlurShader(MAX_SAMPLES);
+ this._equirectShader = null;
+ this._cubemapShader = null;
+
+ this._compileMaterial(this._blurMaterial);
+ }
+ /**
+ * 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 (the cubeCamera
+ * is placed at the origin).
+ */
+
+
+ fromScene(scene, sigma = 0, near = 0.1, far = 100) {
+ _oldTarget = this._renderer.getRenderTarget();
+
+ const cubeUVRenderTarget = this._allocateTargets();
+
+ this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
+
+ 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.
+ */
+
+
+ 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.
+ */
+
+
+ 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._cubemapShader === null) {
+ this._cubemapShader = _getCubemapShader();
+
+ this._compileMaterial(this._cubemapShader);
+ }
+ }
+ /**
+ * 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._equirectShader === null) {
+ this._equirectShader = _getEquirectShader();
+
+ this._compileMaterial(this._equirectShader);
+ }
+ }
+ /**
+ * 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._blurMaterial.dispose();
+
+ if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose();
+ if (this._cubemapShader !== null) this._cubemapShader.dispose();
+ if (this._equirectShader !== null) this._equirectShader.dispose();
+
+ for (let i = 0; i < _lodPlanes.length; i++) {
+ _lodPlanes[i].dispose();
+ }
+ } // private interface
+
+
+ _cleanup(outputTarget) {
+ this._renderer.setRenderTarget(_oldTarget);
+
+ outputTarget.scissorTest = false;
+
+ _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
+ }
+
+ _fromTexture(texture, renderTarget) {
+ _oldTarget = this._renderer.getRenderTarget();
+
+ const cubeUVRenderTarget = renderTarget || this._allocateTargets(texture);
+
+ this._textureToCubeUV(texture, cubeUVRenderTarget);
+
+ this._applyPMREM(cubeUVRenderTarget);
+
+ this._cleanup(cubeUVRenderTarget);
+
+ return cubeUVRenderTarget;
+ }
+
+ _allocateTargets(texture) {
+ // warning: null texture is valid
+ const params = {
+ magFilter: LinearFilter,
+ minFilter: LinearFilter,
+ generateMipmaps: false,
+ type: HalfFloatType,
+ format: RGBAFormat,
+ encoding: LinearEncoding,
+ depthBuffer: false
+ };
+
+ const cubeUVRenderTarget = _createRenderTarget(params);
+
+ cubeUVRenderTarget.depthBuffer = texture ? false : true;
+
+ if (this._pingPongRenderTarget === null) {
+ this._pingPongRenderTarget = _createRenderTarget(params);
+ }
+
+ return cubeUVRenderTarget;
+ }
+
+ _compileMaterial(material) {
+ const tmpMesh = new Mesh(_lodPlanes[0], material);
+
+ this._renderer.compile(tmpMesh, _flatCamera);
+ }
+
+ _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
+ const fov = 90;
+ const aspect = 1;
+ const cubeCamera = new PerspectiveCamera(fov, aspect, 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 backgroundMaterial = new MeshBasicMaterial({
+ name: 'PMREM.Background',
+ side: BackSide,
+ depthWrite: false,
+ depthTest: false
+ });
+ const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
+ 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.lookAt(forwardSign[i], 0, 0);
+ } else if (col === 1) {
+ cubeCamera.up.set(0, 0, upSign[i]);
+ cubeCamera.lookAt(0, forwardSign[i], 0);
+ } else {
+ cubeCamera.up.set(0, upSign[i], 0);
+ cubeCamera.lookAt(0, 0, forwardSign[i]);
+ }
+
+ _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
+
+ renderer.setRenderTarget(cubeUVRenderTarget);
+
+ if (useSolidColor) {
+ renderer.render(backgroundBox, cubeCamera);
+ }
+
+ renderer.render(scene, cubeCamera);
+ }
+
+ backgroundBox.geometry.dispose();
+ backgroundBox.material.dispose();
+ 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._cubemapShader === null) {
+ this._cubemapShader = _getCubemapShader();
+ }
+
+ this._cubemapShader.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1;
+ } else {
+ if (this._equirectShader === null) {
+ this._equirectShader = _getEquirectShader();
+ }
+ }
+
+ const material = isCubeTexture ? this._cubemapShader : this._equirectShader;
+ const mesh = new Mesh(_lodPlanes[0], material);
+ const uniforms = material.uniforms;
+ uniforms['envMap'].value = texture;
+
+ if (!isCubeTexture) {
+ uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
+ }
+
+ _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
+
+ renderer.setRenderTarget(cubeUVRenderTarget);
+ renderer.render(mesh, _flatCamera);
+ }
+
+ _applyPMREM(cubeUVRenderTarget) {
+ const renderer = this._renderer;
+ const autoClear = renderer.autoClear;
+ renderer.autoClear = false;
+
+ for (let i = 1; i < TOTAL_LODS; i++) {
+ const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
+ const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
+
+ this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
+ }
+
+ renderer.autoClear = autoClear;
+ }
+ /**
+ * 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.
+ */
+
+
+ _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') {
+ console.error('blur direction must be either latitudinal or longitudinal!');
+ } // Number of standard deviations at which to cut off the discrete approximation.
+
+
+ const STANDARD_DEVIATIONS = 3;
+ const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
+ const blurUniforms = blurMaterial.uniforms;
+ const pixels = _sizeLods[lodIn] - 1;
+ const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 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) {
+ console.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 x = i / sigmaPixels;
+ const weight = Math.exp(-x * x / 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;
+ }
+
+ blurUniforms['dTheta'].value = radiansPerPixel;
+ blurUniforms['mipInt'].value = LOD_MAX - lodIn;
+ const outputSize = _sizeLods[lodOut];
+ const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
+ const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
+
+ _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
+
+ renderer.setRenderTarget(targetOut);
+ renderer.render(blurMesh, _flatCamera);
+ }
+
+}
+
+function _createPlanes() {
+ const _lodPlanes = [];
+ const _sizeLods = [];
+ const _sigmas = [];
+ let lod = LOD_MAX;
+
+ for (let i = 0; i < TOTAL_LODS; i++) {
+ const sizeLod = Math.pow(2, lod);
+
+ _sizeLods.push(sizeLod);
+
+ let sigma = 1.0 / sizeLod;
+
+ if (i > LOD_MAX - LOD_MIN) {
+ sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
+ } else if (i === 0) {
+ sigma = 0;
+ }
+
+ _sigmas.push(sigma);
+
+ const texelSize = 1.0 / (sizeLod - 1);
+ const min = -texelSize / 2;
+ const max = 1 + texelSize / 2;
+ 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 face = 0; face < cubeFaces; face++) {
+ const x = face % 3 * 2 / 3 - 1;
+ const y = face > 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 * face);
+ uv.set(uv1, uvSize * vertices * face);
+ const fill = [face, face, face, face, face, face];
+ faceIndex.set(fill, faceIndexSize * vertices * face);
+ }
+
+ 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));
+
+ _lodPlanes.push(planes);
+
+ if (lod > LOD_MIN) {
+ lod--;
+ }
+ }
+
+ return {
+ _lodPlanes,
+ _sizeLods,
+ _sigmas
+ };
+}
+
+function _createRenderTarget(params) {
+ const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, 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 _getBlurShader(maxSamples) {
+ const weights = new Float32Array(maxSamples);
+ const poleAxis = new Vector3(0, 1, 0);
+ const shaderMaterial = new RawShaderMaterial({
+ name: 'SphericalGaussianBlur',
+ defines: {
+ 'n': maxSamples
+ },
+ 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 <cube_uv_reflection_fragment>
+
+ 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 _getEquirectShader() {
+ const texelSize = new Vector2(1, 1);
+ const shaderMaterial = new RawShaderMaterial({
+ name: 'EquirectangularToCubeUV',
+ uniforms: {
+ 'envMap': {
+ value: null
+ },
+ 'texelSize': {
+ value: texelSize
+ }
+ },
+ vertexShader: _getCommonVertexShader(),
+ fragmentShader:
+ /* glsl */
+ `
+
+ precision mediump float;
+ precision mediump int;
+
+ varying vec3 vOutputDirection;
+
+ uniform sampler2D envMap;
+ uniform vec2 texelSize;
+
+ #include <common>
+
+ void main() {
+
+ gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
+
+ vec3 outputDirection = normalize( vOutputDirection );
+ vec2 uv = equirectUv( outputDirection );
+
+ vec2 f = fract( uv / texelSize - 0.5 );
+ uv -= f * texelSize;
+ vec3 tl = texture2D ( envMap, uv ).rgb;
+ uv.x += texelSize.x;
+ vec3 tr = texture2D ( envMap, uv ).rgb;
+ uv.y += texelSize.y;
+ vec3 br = texture2D ( envMap, uv ).rgb;
+ uv.x -= texelSize.x;
+ vec3 bl = texture2D ( envMap, uv ).rgb;
+
+ vec3 tm = mix( tl, tr, f.x );
+ vec3 bm = mix( bl, br, f.x );
+ gl_FragColor.rgb = mix( tm, bm, f.y );
+
+ }
+ `,
+ blending: NoBlending,
+ depthTest: false,
+ depthWrite: false
+ });
+ return shaderMaterial;
+}
+
+function _getCubemapShader() {
+ const shaderMaterial = new RawShaderMaterial({
+ 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
+ });
+ return shaderMaterial;
+}
+
+function _getCommonVertexShader() {
+ return (
+ /* glsl */
+ `
+
+ precision mediump float;
+ precision mediump int;
+
+ attribute vec3 position;
+ attribute vec2 uv;
+ 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 );
+
+ }
+ `
+ );
+}
+
+function WebGLCubeUVMaps(renderer) {
+ let cubeUVmaps = new WeakMap();
+ let pmremGenerator = null;
+
+ function get(texture) {
+ if (texture && texture.isTexture) {
+ const mapping = texture.mapping;
+ const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
+ const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; // equirect/cube map to cubeUV conversion
+
+ if (isEquirectMap || isCubeMap) {
+ if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) {
+ texture.needsPMREMUpdate = false;
+ let renderTarget = cubeUVmaps.get(texture);
+ if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
+ renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget);
+ cubeUVmaps.set(texture, renderTarget);
+ return renderTarget.texture;
+ } else {
+ if (cubeUVmaps.has(texture)) {
+ return cubeUVmaps.get(texture).texture;
+ } else {
+ const image = texture.image;
+
+ if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
+ if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
+ const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
+ cubeUVmaps.set(texture, renderTarget);
+ texture.addEventListener('dispose', onTextureDispose);
+ return renderTarget.texture;
+ } else {
+ // image not yet ready. try the conversion next frame
+ return null;
+ }
+ }
+ }
+ }
+ }
+
+ return texture;
+ }
+
+ function isCubeTextureComplete(image) {
+ let count = 0;
+ const length = 6;
+
+ for (let i = 0; i < length; i++) {
+ if (image[i] !== undefined) count++;
+ }
+
+ return count === length;
+ }
+
+ function onTextureDispose(event) {
+ const texture = event.target;
+ texture.removeEventListener('dispose', onTextureDispose);
+ const cubemapUV = cubeUVmaps.get(texture);
+
+ if (cubemapUV !== undefined) {
+ cubeUVmaps.delete(texture);
+ cubemapUV.dispose();
+ }
+ }
+
+ function dispose() {
+ cubeUVmaps = new WeakMap();
+
+ if (pmremGenerator !== null) {
+ pmremGenerator.dispose();
+ pmremGenerator = null;
+ }
+ }
+
+ return {
+ get: get,
+ dispose: dispose
+ };
+}
+
+function WebGLExtensions(gl) {
+ const extensions = {};
+
+ function getExtension(name) {
+ if (extensions[name] !== undefined) {
+ return extensions[name];
+ }
+
+ let extension;
+
+ switch (name) {
+ case 'WEBGL_depth_texture':
+ extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
+ break;
+
+ case 'EXT_texture_filter_anisotropic':
+ extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
+ break;
+
+ case 'WEBGL_compressed_texture_s3tc':
+ extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
+ break;
+
+ case 'WEBGL_compressed_texture_pvrtc':
+ extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
+ break;
+
+ default:
+ extension = gl.getExtension(name);
+ }
+
+ extensions[name] = extension;
+ return extension;
+ }
+
+ return {
+ has: function (name) {
+ return getExtension(name) !== null;
+ },
+ init: function (capabilities) {
+ if (capabilities.isWebGL2) {
+ getExtension('EXT_color_buffer_float');
+ } else {
+ getExtension('WEBGL_depth_texture');
+ getExtension('OES_texture_float');
+ getExtension('OES_texture_half_float');
+ getExtension('OES_texture_half_float_linear');
+ getExtension('OES_standard_derivatives');
+ getExtension('OES_element_index_uint');
+ getExtension('OES_vertex_array_object');
+ getExtension('ANGLE_instanced_arrays');
+ }
+
+ getExtension('OES_texture_float_linear');
+ getExtension('EXT_color_buffer_half_float');
+ getExtension('WEBGL_multisampled_render_to_texture');
+ },
+ get: function (name) {
+ const extension = getExtension(name);
+
+ if (extension === null) {
+ console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
+ }
+
+ return extension;
+ }
+ };
+}
+
+function WebGLGeometries(gl, attributes, info, bindingStates) {
+ const geometries = {};
+ const wireframeAttributes = 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; // Updating index buffer in VAO now. See WebGLBindingStates.
+
+ for (const name in geometryAttributes) {
+ attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
+ } // morph targets
+
+
+ const morphAttributes = geometry.morphAttributes;
+
+ for (const name in morphAttributes) {
+ const array = morphAttributes[name];
+
+ for (let i = 0, l = array.length; i < l; i++) {
+ attributes.update(array[i], gl.ARRAY_BUFFER);
+ }
+ }
+ }
+
+ function updateWireframeAttribute(geometry) {
+ const indices = [];
+ const geometryIndex = geometry.index;
+ const geometryPosition = geometry.attributes.position;
+ let version = 0;
+
+ 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 (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
+ attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
+ //
+
+ 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 the attribute is obsolete, create a new one
+ if (currentAttribute.version < geometryIndex.version) {
+ updateWireframeAttribute(geometry);
+ }
+ }
+ } else {
+ updateWireframeAttribute(geometry);
+ }
+
+ return wireframeAttributes.get(geometry);
+ }
+
+ return {
+ get: get,
+ update: update,
+ getWireframeAttribute: getWireframeAttribute
+ };
+}
+
+function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
+ const isWebGL2 = capabilities.isWebGL2;
+ 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;
+ let extension, methodName;
+
+ if (isWebGL2) {
+ extension = gl;
+ methodName = 'drawElementsInstanced';
+ } else {
+ extension = extensions.get('ANGLE_instanced_arrays');
+ methodName = 'drawElementsInstancedANGLE';
+
+ if (extension === null) {
+ console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
+ return;
+ }
+ }
+
+ extension[methodName](mode, count, type, start * bytesPerElement, primcount);
+ info.update(count, mode, primcount);
+ } //
+
+
+ this.setMode = setMode;
+ this.setIndex = setIndex;
+ this.render = render;
+ this.renderInstances = renderInstances;
+}
+
+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:
+ console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
+ break;
+ }
+ }
+
+ function reset() {
+ render.frame++;
+ render.calls = 0;
+ render.triangles = 0;
+ render.points = 0;
+ render.lines = 0;
+ }
+
+ return {
+ memory: memory,
+ render: render,
+ programs: null,
+ autoReset: true,
+ reset: reset,
+ update: update
+ };
+}
+
+class DataTexture2DArray extends Texture {
+ constructor(data = null, width = 1, height = 1, depth = 1) {
+ super(null);
+ this.image = {
+ data,
+ width,
+ height,
+ depth
+ };
+ this.magFilter = NearestFilter;
+ this.minFilter = NearestFilter;
+ this.wrapR = ClampToEdgeWrapping;
+ this.generateMipmaps = false;
+ this.flipY = false;
+ this.unpackAlignment = 1;
+ }
+
+}
+
+DataTexture2DArray.prototype.isDataTexture2DArray = true;
+
+function numericalSort(a, b) {
+ return a[0] - b[0];
+}
+
+function absNumericalSort(a, b) {
+ return Math.abs(b[1]) - Math.abs(a[1]);
+}
+
+function denormalize(morph, attribute) {
+ let denominator = 1;
+ const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
+ if (array instanceof Int8Array) denominator = 127;else if (array instanceof Int16Array) denominator = 32767;else if (array instanceof Int32Array) denominator = 2147483647;else console.error('THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array);
+ morph.divideScalar(denominator);
+}
+
+function WebGLMorphtargets(gl, capabilities, textures) {
+ const influencesList = {};
+ const morphInfluences = new Float32Array(8);
+ const morphTextures = new WeakMap();
+ const morph = new Vector3();
+ const workInfluences = [];
+
+ for (let i = 0; i < 8; i++) {
+ workInfluences[i] = [i, 0];
+ }
+
+ function update(object, geometry, material, program) {
+ const objectInfluences = object.morphTargetInfluences;
+
+ if (capabilities.isWebGL2 === true) {
+ // instead of using attributes, the WebGL 2 code path encodes morph targets
+ // into an array of data textures. Each layer represents a single morph target.
+ const numberOfMorphTargets = geometry.morphAttributes.position.length;
+ let entry = morphTextures.get(geometry);
+
+ if (entry === undefined || entry.count !== numberOfMorphTargets) {
+ if (entry !== undefined) entry.texture.dispose();
+ const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
+ const morphTargets = geometry.morphAttributes.position;
+ const morphNormals = geometry.morphAttributes.normal || [];
+ const numberOfVertices = geometry.attributes.position.count;
+ const numberOfVertexData = hasMorphNormals === true ? 2 : 1; // (v,n) vs. (v)
+
+ let width = numberOfVertices * numberOfVertexData;
+ let height = 1;
+
+ if (width > capabilities.maxTextureSize) {
+ height = Math.ceil(width / capabilities.maxTextureSize);
+ width = capabilities.maxTextureSize;
+ }
+
+ const buffer = new Float32Array(width * height * 4 * numberOfMorphTargets);
+ const texture = new DataTexture2DArray(buffer, width, height, numberOfMorphTargets);
+ texture.format = RGBAFormat; // using RGBA since RGB might be emulated (and is thus slower)
+
+ texture.type = FloatType;
+ texture.needsUpdate = true; // fill buffer
+
+ const vertexDataStride = numberOfVertexData * 4;
+
+ for (let i = 0; i < numberOfMorphTargets; i++) {
+ const morphTarget = morphTargets[i];
+ const morphNormal = morphNormals[i];
+ const offset = width * height * 4 * i;
+
+ for (let j = 0; j < morphTarget.count; j++) {
+ morph.fromBufferAttribute(morphTarget, j);
+ if (morphTarget.normalized === true) denormalize(morph, morphTarget);
+ const stride = j * vertexDataStride;
+ 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);
+ if (morphNormal.normalized === true) denormalize(morph, morphNormal);
+ buffer[offset + stride + 4] = morph.x;
+ buffer[offset + stride + 5] = morph.y;
+ buffer[offset + stride + 6] = morph.z;
+ buffer[offset + stride + 7] = 0;
+ }
+ }
+ }
+
+ entry = {
+ count: numberOfMorphTargets,
+ texture: texture,
+ size: new Vector2(width, height)
+ };
+ morphTextures.set(geometry, entry);
+
+ function disposeTexture() {
+ texture.dispose();
+ morphTextures.delete(geometry);
+ geometry.removeEventListener('dispose', disposeTexture);
+ }
+
+ geometry.addEventListener('dispose', disposeTexture);
+ } //
+
+
+ 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);
+ } else {
+ // When object doesn't have morph target influences defined, we treat it as a 0-length array
+ // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
+ const length = objectInfluences === undefined ? 0 : objectInfluences.length;
+ let influences = influencesList[geometry.id];
+
+ if (influences === undefined || influences.length !== length) {
+ // initialise list
+ influences = [];
+
+ for (let i = 0; i < length; i++) {
+ influences[i] = [i, 0];
+ }
+
+ influencesList[geometry.id] = influences;
+ } // Collect influences
+
+
+ for (let i = 0; i < length; i++) {
+ const influence = influences[i];
+ influence[0] = i;
+ influence[1] = objectInfluences[i];
+ }
+
+ influences.sort(absNumericalSort);
+
+ for (let i = 0; i < 8; i++) {
+ if (i < length && influences[i][1]) {
+ workInfluences[i][0] = influences[i][0];
+ workInfluences[i][1] = influences[i][1];
+ } else {
+ workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
+ workInfluences[i][1] = 0;
+ }
+ }
+
+ workInfluences.sort(numericalSort);
+ const morphTargets = geometry.morphAttributes.position;
+ const morphNormals = geometry.morphAttributes.normal;
+ let morphInfluencesSum = 0;
+
+ for (let i = 0; i < 8; i++) {
+ const influence = workInfluences[i];
+ const index = influence[0];
+ const value = influence[1];
+
+ if (index !== Number.MAX_SAFE_INTEGER && value) {
+ if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
+ geometry.setAttribute('morphTarget' + i, morphTargets[index]);
+ }
+
+ if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
+ geometry.setAttribute('morphNormal' + i, morphNormals[index]);
+ }
+
+ morphInfluences[i] = value;
+ morphInfluencesSum += value;
+ } else {
+ if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
+ geometry.deleteAttribute('morphTarget' + i);
+ }
+
+ if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
+ geometry.deleteAttribute('morphNormal' + i);
+ }
+
+ morphInfluences[i] = 0;
+ }
+ } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
+ // This allows us to switch between absolute morphs and relative morphs without changing shader code
+ // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
+
+
+ const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
+ program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
+ program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
+ }
+ }
+
+ return {
+ update: update
+ };
+}
+
+function WebGLObjects(gl, geometries, attributes, info) {
+ let updateMap = new WeakMap();
+
+ function update(object) {
+ const frame = info.render.frame;
+ const geometry = object.geometry;
+ const buffergeometry = geometries.get(object, geometry); // Update once per frame
+
+ 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);
+ }
+
+ attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
+
+ if (object.instanceColor !== null) {
+ attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
+ }
+ }
+
+ return buffergeometry;
+ }
+
+ function dispose() {
+ updateMap = new WeakMap();
+ }
+
+ function onInstancedMeshDispose(event) {
+ const instancedMesh = event.target;
+ instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
+ attributes.remove(instancedMesh.instanceMatrix);
+ if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
+ }
+
+ return {
+ update: update,
+ dispose: dispose
+ };
+}
+
+class DataTexture3D extends Texture {
+ constructor(data = null, width = 1, height = 1, depth = 1) {
+ // We're going to add .setXXX() methods for setting properties later.
+ // Users can still set in DataTexture3D directly.
+ //
+ // const texture = new THREE.DataTexture3D( data, width, height, depth );
+ // texture.anisotropy = 16;
+ //
+ // See #14839
+ super(null);
+ this.image = {
+ data,
+ width,
+ height,
+ depth
+ };
+ this.magFilter = NearestFilter;
+ this.minFilter = NearestFilter;
+ this.wrapR = ClampToEdgeWrapping;
+ this.generateMipmaps = false;
+ this.flipY = false;
+ this.unpackAlignment = 1;
+ }
+
+}
+
+DataTexture3D.prototype.isDataTexture3D = true;
+
+/**
+ * Uniforms of a program.
+ * Those form a tree structure with a special top-level container for the root,
+ * which you get by calling 'new WebGLUniforms( gl, program )'.
+ *
+ *
+ * Properties of inner nodes including the top-level container:
+ *
+ * .seq - array of nested uniforms
+ * .map - nested uniforms by name
+ *
+ *
+ * Methods of all nodes except the top-level container:
+ *
+ * .setValue( gl, value, [textures] )
+ *
+ * uploads a uniform value(s)
+ * the 'textures' parameter is needed for sampler uniforms
+ *
+ *
+ * Static methods of the top-level container (textures factorizations):
+ *
+ * .upload( gl, seq, values, textures )
+ *
+ * sets uniforms in 'seq' to 'values[id].value'
+ *
+ * .seqWithValue( seq, values ) : filteredSeq
+ *
+ * filters 'seq' entries with corresponding entry in values
+ *
+ *
+ * Methods of the top-level container (textures factorizations):
+ *
+ * .setValue( gl, name, value, textures )
+ *
+ * sets uniform with name 'name' to 'value'
+ *
+ * .setOptional( gl, obj, prop )
+ *
+ * like .set for an optional property of the object
+ *
+ */
+const emptyTexture = new Texture();
+const emptyTexture2dArray = new DataTexture2DArray();
+const emptyTexture3d = new DataTexture3D();
+const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
+// Array Caches (provide typed arrays for temporary by size)
+
+const arrayCacheF32 = [];
+const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
+
+const mat4array = new Float32Array(16);
+const mat3array = new Float32Array(9);
+const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
+
+function flatten(array, nBlocks, blockSize) {
+ const firstElem = array[0];
+ if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
+ // see http://jacksondunstan.com/articles/983
+
+ const n = nBlocks * blockSize;
+ let r = arrayCacheF32[n];
+
+ if (r === undefined) {
+ 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];
+ }
+} // Texture unit allocation
+
+
+function allocTexUnits(textures, n) {
+ let r = arrayCacheI32[n];
+
+ if (r === undefined) {
+ r = new Int32Array(n);
+ arrayCacheI32[n] = r;
+ }
+
+ for (let i = 0; i !== n; ++i) {
+ r[i] = textures.allocateTextureUnit();
+ }
+
+ return r;
+} // --- Setters ---
+// Note: Defining these methods externally, because they come in a bunch
+// and this way their names minify.
+// Single scalar
+
+
+function setValueV1f(gl, v) {
+ const cache = this.cache;
+ if (cache[0] === v) return;
+ gl.uniform1f(this.addr, v);
+ cache[0] = v;
+} // Single float vector (from flat array or THREE.VectorN)
+
+
+function setValueV2f(gl, v) {
+ const cache = this.cache;
+
+ if (v.x !== undefined) {
+ 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 !== undefined) {
+ 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 !== undefined) {
+ 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 !== undefined) {
+ 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);
+ }
+} // Single matrix (from flat array or THREE.MatrixN)
+
+
+function setValueM2(gl, v) {
+ const cache = this.cache;
+ const elements = v.elements;
+
+ if (elements === undefined) {
+ 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 === undefined) {
+ 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 === undefined) {
+ 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);
+ }
+} // Single integer / boolean
+
+
+function setValueV1i(gl, v) {
+ const cache = this.cache;
+ if (cache[0] === v) return;
+ gl.uniform1i(this.addr, v);
+ cache[0] = v;
+} // Single integer / boolean vector (from flat array)
+
+
+function setValueV2i(gl, v) {
+ const cache = this.cache;
+ if (arraysEqual(cache, v)) return;
+ gl.uniform2iv(this.addr, v);
+ copyArray(cache, v);
+}
+
+function setValueV3i(gl, v) {
+ const cache = this.cache;
+ if (arraysEqual(cache, v)) return;
+ gl.uniform3iv(this.addr, v);
+ copyArray(cache, v);
+}
+
+function setValueV4i(gl, v) {
+ const cache = this.cache;
+ if (arraysEqual(cache, v)) return;
+ gl.uniform4iv(this.addr, v);
+ copyArray(cache, v);
+} // Single unsigned integer
+
+
+function setValueV1ui(gl, v) {
+ const cache = this.cache;
+ if (cache[0] === v) return;
+ gl.uniform1ui(this.addr, v);
+ cache[0] = v;
+} // Single unsigned integer vector (from flat array)
+
+
+function setValueV2ui(gl, v) {
+ const cache = this.cache;
+ if (arraysEqual(cache, v)) return;
+ gl.uniform2uiv(this.addr, v);
+ copyArray(cache, v);
+}
+
+function setValueV3ui(gl, v) {
+ const cache = this.cache;
+ if (arraysEqual(cache, v)) return;
+ gl.uniform3uiv(this.addr, v);
+ copyArray(cache, v);
+}
+
+function setValueV4ui(gl, v) {
+ const cache = this.cache;
+ if (arraysEqual(cache, v)) return;
+ gl.uniform4uiv(this.addr, v);
+ copyArray(cache, v);
+} // Single texture (2D / Cube)
+
+
+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;
+ }
+
+ textures.safeSetTexture2D(v || emptyTexture, 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 || emptyTexture3d, 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.safeSetTextureCube(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 || emptyTexture2dArray, unit);
+} // Helper to pick the right setter for the singular case
+
+
+function getSingularSetter(type) {
+ switch (type) {
+ case 0x1406:
+ return setValueV1f;
+ // FLOAT
+
+ case 0x8b50:
+ return setValueV2f;
+ // _VEC2
+
+ case 0x8b51:
+ return setValueV3f;
+ // _VEC3
+
+ case 0x8b52:
+ return setValueV4f;
+ // _VEC4
+
+ case 0x8b5a:
+ return setValueM2;
+ // _MAT2
+
+ case 0x8b5b:
+ return setValueM3;
+ // _MAT3
+
+ case 0x8b5c:
+ return setValueM4;
+ // _MAT4
+
+ case 0x1404:
+ case 0x8b56:
+ return setValueV1i;
+ // INT, BOOL
+
+ case 0x8b53:
+ case 0x8b57:
+ return setValueV2i;
+ // _VEC2
+
+ case 0x8b54:
+ case 0x8b58:
+ return setValueV3i;
+ // _VEC3
+
+ case 0x8b55:
+ case 0x8b59:
+ return setValueV4i;
+ // _VEC4
+
+ case 0x1405:
+ return setValueV1ui;
+ // UINT
+
+ case 0x8dc6:
+ return setValueV2ui;
+ // _VEC2
+
+ case 0x8dc7:
+ return setValueV3ui;
+ // _VEC3
+
+ case 0x8dc8:
+ return setValueV4ui;
+ // _VEC4
+
+ case 0x8b5e: // SAMPLER_2D
+
+ case 0x8d66: // SAMPLER_EXTERNAL_OES
+
+ case 0x8dca: // INT_SAMPLER_2D
+
+ case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
+
+ case 0x8b62:
+ // SAMPLER_2D_SHADOW
+ return setValueT1;
+
+ case 0x8b5f: // SAMPLER_3D
+
+ case 0x8dcb: // INT_SAMPLER_3D
+
+ case 0x8dd3:
+ // UNSIGNED_INT_SAMPLER_3D
+ return setValueT3D1;
+
+ case 0x8b60: // SAMPLER_CUBE
+
+ case 0x8dcc: // INT_SAMPLER_CUBE
+
+ case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
+
+ case 0x8dc5:
+ // SAMPLER_CUBE_SHADOW
+ return setValueT6;
+
+ case 0x8dc1: // SAMPLER_2D_ARRAY
+
+ case 0x8dcf: // INT_SAMPLER_2D_ARRAY
+
+ case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
+
+ case 0x8dc4:
+ // SAMPLER_2D_ARRAY_SHADOW
+ return setValueT2DArray1;
+ }
+} // Array of scalars
+
+
+function setValueV1fArray(gl, v) {
+ gl.uniform1fv(this.addr, v);
+} // Array of vectors (from flat array or array of THREE.VectorN)
+
+
+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);
+} // Array of matrices (from flat array or array of THREE.MatrixN)
+
+
+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);
+} // Array of integer / boolean
+
+
+function setValueV1iArray(gl, v) {
+ gl.uniform1iv(this.addr, v);
+} // Array of integer / boolean vectors (from flat array)
+
+
+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);
+} // Array of unsigned integer
+
+
+function setValueV1uiArray(gl, v) {
+ gl.uniform1uiv(this.addr, v);
+} // Array of unsigned integer vectors (from flat array)
+
+
+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);
+} // Array of textures (2D / 3D / Cube / 2DArray)
+
+
+function setValueT1Array(gl, v, textures) {
+ const n = v.length;
+ const units = allocTexUnits(textures, n);
+ gl.uniform1iv(this.addr, units);
+
+ for (let i = 0; i !== n; ++i) {
+ textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
+ }
+}
+
+function setValueT3DArray(gl, v, textures) {
+ const n = v.length;
+ const units = allocTexUnits(textures, n);
+ gl.uniform1iv(this.addr, units);
+
+ for (let i = 0; i !== n; ++i) {
+ textures.setTexture3D(v[i] || emptyTexture3d, units[i]);
+ }
+}
+
+function setValueT6Array(gl, v, textures) {
+ const n = v.length;
+ const units = allocTexUnits(textures, n);
+ gl.uniform1iv(this.addr, units);
+
+ for (let i = 0; i !== n; ++i) {
+ textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
+ }
+}
+
+function setValueT2DArrayArray(gl, v, textures) {
+ const n = v.length;
+ const units = allocTexUnits(textures, n);
+ gl.uniform1iv(this.addr, units);
+
+ for (let i = 0; i !== n; ++i) {
+ textures.setTexture2DArray(v[i] || emptyTexture2dArray, units[i]);
+ }
+} // Helper to pick the right setter for a pure (bottom-level) array
+
+
+function getPureArraySetter(type) {
+ switch (type) {
+ case 0x1406:
+ return setValueV1fArray;
+ // FLOAT
+
+ case 0x8b50:
+ return setValueV2fArray;
+ // _VEC2
+
+ case 0x8b51:
+ return setValueV3fArray;
+ // _VEC3
+
+ case 0x8b52:
+ return setValueV4fArray;
+ // _VEC4
+
+ case 0x8b5a:
+ return setValueM2Array;
+ // _MAT2
+
+ case 0x8b5b:
+ return setValueM3Array;
+ // _MAT3
+
+ case 0x8b5c:
+ return setValueM4Array;
+ // _MAT4
+
+ case 0x1404:
+ case 0x8b56:
+ return setValueV1iArray;
+ // INT, BOOL
+
+ case 0x8b53:
+ case 0x8b57:
+ return setValueV2iArray;
+ // _VEC2
+
+ case 0x8b54:
+ case 0x8b58:
+ return setValueV3iArray;
+ // _VEC3
+
+ case 0x8b55:
+ case 0x8b59:
+ return setValueV4iArray;
+ // _VEC4
+
+ case 0x1405:
+ return setValueV1uiArray;
+ // UINT
+
+ case 0x8dc6:
+ return setValueV2uiArray;
+ // _VEC2
+
+ case 0x8dc7:
+ return setValueV3uiArray;
+ // _VEC3
+
+ case 0x8dc8:
+ return setValueV4uiArray;
+ // _VEC4
+
+ case 0x8b5e: // SAMPLER_2D
+
+ case 0x8d66: // SAMPLER_EXTERNAL_OES
+
+ case 0x8dca: // INT_SAMPLER_2D
+
+ case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
+
+ case 0x8b62:
+ // SAMPLER_2D_SHADOW
+ return setValueT1Array;
+
+ case 0x8b5f: // SAMPLER_3D
+
+ case 0x8dcb: // INT_SAMPLER_3D
+
+ case 0x8dd3:
+ // UNSIGNED_INT_SAMPLER_3D
+ return setValueT3DArray;
+
+ case 0x8b60: // SAMPLER_CUBE
+
+ case 0x8dcc: // INT_SAMPLER_CUBE
+
+ case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
+
+ case 0x8dc5:
+ // SAMPLER_CUBE_SHADOW
+ return setValueT6Array;
+
+ case 0x8dc1: // SAMPLER_2D_ARRAY
+
+ case 0x8dcf: // INT_SAMPLER_2D_ARRAY
+
+ case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
+
+ case 0x8dc4:
+ // SAMPLER_2D_ARRAY_SHADOW
+ return setValueT2DArrayArray;
+ }
+} // --- Uniform Classes ---
+
+
+function SingleUniform(id, activeInfo, addr) {
+ this.id = id;
+ this.addr = addr;
+ this.cache = [];
+ this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
+}
+
+function PureArrayUniform(id, activeInfo, addr) {
+ this.id = id;
+ this.addr = addr;
+ this.cache = [];
+ this.size = activeInfo.size;
+ this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
+}
+
+PureArrayUniform.prototype.updateCache = function (data) {
+ const cache = this.cache;
+
+ if (data instanceof Float32Array && cache.length !== data.length) {
+ this.cache = new Float32Array(data.length);
+ }
+
+ copyArray(cache, data);
+};
+
+function StructuredUniform(id) {
+ this.id = id;
+ this.seq = [];
+ this.map = {};
+}
+
+StructuredUniform.prototype.setValue = function (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);
+ }
+}; // --- Top-level ---
+// Parser - builds up the property tree from the path strings
+
+
+const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
+// - the identifier (member name or array index)
+// - followed by an optional right bracket (found when array index)
+// - followed by an optional left bracket or dot (type of subscript)
+//
+// Note: These portions can be read in a non-overlapping fashion and
+// allow straightforward parsing of the hierarchy that WebGL encodes
+// in the uniform names.
+
+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; // reset RegExp object, because of the early exit of a previous run
+
+ 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; // convert to integer
+
+ if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
+ // bare name or "pure" bottom-level array "[0]" suffix
+ addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
+ break;
+ } else {
+ // step into inner node / create it in case it doesn't exist
+ const map = container.map;
+ let next = map[id];
+
+ if (next === undefined) {
+ next = new StructuredUniform(id);
+ addUniform(container, next);
+ }
+
+ container = next;
+ }
+ }
+} // Root Container
+
+
+function WebGLUniforms(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);
+ }
+}
+
+WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
+ const u = this.map[name];
+ if (u !== undefined) u.setValue(gl, value, textures);
+};
+
+WebGLUniforms.prototype.setOptional = function (gl, object, name) {
+ const v = object[name];
+ if (v !== undefined) this.setValue(gl, name, v);
+}; // Static interface
+
+
+WebGLUniforms.upload = function (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) {
+ // note: always updating when .needsUpdate is undefined
+ u.setValue(gl, v.value, textures);
+ }
+ }
+};
+
+WebGLUniforms.seqWithValue = function (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;
+}
+
+let programIdCount = 0;
+
+function addLineNumbers(string) {
+ const lines = string.split('\n');
+
+ for (let i = 0; i < lines.length; i++) {
+ lines[i] = i + 1 + ': ' + lines[i];
+ }
+
+ return lines.join('\n');
+}
+
+function getEncodingComponents(encoding) {
+ switch (encoding) {
+ case LinearEncoding:
+ return ['Linear', '( value )'];
+
+ case sRGBEncoding:
+ return ['sRGB', '( value )'];
+
+ default:
+ console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
+ return ['Linear', '( value )'];
+ }
+}
+
+function getShaderErrors(gl, shader, type) {
+ const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
+ const errors = gl.getShaderInfoLog(shader).trim();
+ if (status && errors === '') return ''; // --enable-privileged-webgl-extension
+ // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
+
+ return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers(gl.getShaderSource(shader));
+}
+
+function getTexelEncodingFunction(functionName, encoding) {
+ const components = getEncodingComponents(encoding);
+ return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
+}
+
+function getToneMappingFunction(functionName, toneMapping) {
+ let toneMappingName;
+
+ switch (toneMapping) {
+ case LinearToneMapping:
+ toneMappingName = 'Linear';
+ break;
+
+ case ReinhardToneMapping:
+ toneMappingName = 'Reinhard';
+ break;
+
+ case CineonToneMapping:
+ toneMappingName = 'OptimizedCineon';
+ break;
+
+ case ACESFilmicToneMapping:
+ toneMappingName = 'ACESFilmic';
+ break;
+
+ case CustomToneMapping:
+ toneMappingName = 'Custom';
+ break;
+
+ default:
+ console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
+ toneMappingName = 'Linear';
+ }
+
+ return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
+}
+
+function generateExtensions(parameters) {
+ const chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
+ 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; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
+
+ attributes[name] = {
+ type: info.type,
+ location: gl.getAttribLocation(program, name),
+ locationSize: locationSize
+ };
+ }
+
+ return attributes;
+}
+
+function filterEmptyLine(string) {
+ return string !== '';
+}
+
+function replaceLightNums(string, parameters) {
+ return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).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/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);
+} // Resolve Includes
+
+
+const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
+
+function resolveIncludes(string) {
+ return string.replace(includePattern, includeReplacer);
+}
+
+function includeReplacer(match, include) {
+ const string = ShaderChunk[include];
+
+ if (string === undefined) {
+ throw new Error('Can not resolve #include <' + include + '>');
+ }
+
+ return resolveIncludes(string);
+} // Unroll Loops
+
+
+const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
+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).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
+}
+
+function deprecatedLoopReplacer(match, start, end, snippet) {
+ console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
+ return loopReplacer(match, start, end, snippet);
+}
+
+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;\nprecision ' + parameters.precision + ' int;';
+
+ 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;
+}
+
+function generateShadowMapTypeDefine(parameters) {
+ let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
+
+ if (parameters.shadowMapType === PCFShadowMap) {
+ shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
+ } else if (parameters.shadowMapType === PCFSoftShadowMap) {
+ shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
+ } else if (parameters.shadowMapType === VSMShadowMap) {
+ shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
+ }
+
+ return shadowMapTypeDefine;
+}
+
+function generateEnvMapTypeDefine(parameters) {
+ let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
+
+ if (parameters.envMap) {
+ switch (parameters.envMapMode) {
+ case CubeReflectionMapping:
+ case CubeRefractionMapping:
+ envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
+ break;
+
+ case CubeUVReflectionMapping:
+ case CubeUVRefractionMapping:
+ envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
+ break;
+ }
+ }
+
+ return envMapTypeDefine;
+}
+
+function generateEnvMapModeDefine(parameters) {
+ let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
+
+ if (parameters.envMap) {
+ switch (parameters.envMapMode) {
+ case CubeRefractionMapping:
+ case CubeUVRefractionMapping:
+ envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
+ break;
+ }
+ }
+
+ return envMapModeDefine;
+}
+
+function generateEnvMapBlendingDefine(parameters) {
+ let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
+
+ if (parameters.envMap) {
+ switch (parameters.combine) {
+ case MultiplyOperation:
+ envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
+ break;
+
+ case MixOperation:
+ envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
+ break;
+
+ case AddOperation:
+ envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
+ break;
+ }
+ }
+
+ return envMapBlendingDefine;
+}
+
+function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
+ // TODO Send this event to Three.js DevTools
+ // console.log( 'WebGLProgram', cacheKey );
+ 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 customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
+ const customDefines = generateDefines(defines);
+ const program = gl.createProgram();
+ let prefixVertex, prefixFragment;
+ let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
+
+ if (parameters.isRawShaderMaterial) {
+ prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
+
+ if (prefixVertex.length > 0) {
+ prefixVertex += '\n';
+ }
+
+ prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
+
+ if (prefixFragment.length > 0) {
+ prefixFragment += '\n';
+ }
+ } else {
+ prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define MAX_BONES ' + parameters.maxBones, 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.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.morphTargets && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE' : '', parameters.morphTargets && parameters.isWebGL2 ? '#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.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', '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', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', ' 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', '\n'].filter(filterEmptyLine).join('\n');
+ prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', 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 : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', 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.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', '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.alphaWrite ? '' : '#define OPAQUE', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
+ getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#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.isWebGL2 && parameters.isRawShaderMaterial !== true) {
+ // GLSL 3.0 conversion for built-in materials and ShaderMaterial
+ versionString = '#version 300 es\n';
+ prefixVertex = ['precision mediump sampler2DArray;', '#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; // console.log( '*VERTEX*', vertexGlsl );
+ // console.log( '*FRAGMENT*', fragmentGlsl );
+
+ const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
+ const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
+ gl.attachShader(program, glVertexShader);
+ gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
+
+ if (parameters.index0AttributeName !== undefined) {
+ gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
+ } else if (parameters.morphTargets === true) {
+ // programs with morphTargets displace position out of attribute 0
+ gl.bindAttribLocation(program, 0, 'position');
+ }
+
+ gl.linkProgram(program); // check for link errors
+
+ if (renderer.debug.checkShaderErrors) {
+ const programLog = gl.getProgramInfoLog(program).trim();
+ const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
+ const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
+ let runnable = true;
+ let haveDiagnostics = true;
+
+ if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
+ runnable = false;
+ const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
+ const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
+ console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
+ } else if (programLog !== '') {
+ console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
+ } else if (vertexLog === '' || fragmentLog === '') {
+ haveDiagnostics = false;
+ }
+
+ if (haveDiagnostics) {
+ this.diagnostics = {
+ runnable: runnable,
+ programLog: programLog,
+ vertexShader: {
+ log: vertexLog,
+ prefix: prefixVertex
+ },
+ fragmentShader: {
+ log: fragmentLog,
+ prefix: prefixFragment
+ }
+ };
+ }
+ } // Clean up
+ // Crashes in iOS9 and iOS10. #18402
+ // gl.detachShader( program, glVertexShader );
+ // gl.detachShader( program, glFragmentShader );
+
+
+ gl.deleteShader(glVertexShader);
+ gl.deleteShader(glFragmentShader); // set up caching for uniform locations
+
+ let cachedUniforms;
+
+ this.getUniforms = function () {
+ if (cachedUniforms === undefined) {
+ cachedUniforms = new WebGLUniforms(gl, program);
+ }
+
+ return cachedUniforms;
+ }; // set up caching for attribute locations
+
+
+ let cachedAttributes;
+
+ this.getAttributes = function () {
+ if (cachedAttributes === undefined) {
+ cachedAttributes = fetchAttributeLocations(gl, program);
+ }
+
+ return cachedAttributes;
+ }; // free resource
+
+
+ this.destroy = function () {
+ bindingStates.releaseStatesOfProgram(this);
+ gl.deleteProgram(program);
+ this.program = undefined;
+ }; //
+
+
+ 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 = new Map();
+ this.materialCache = 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);
+ }
+
+ 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;
+
+ if (cache.has(material) === false) {
+ cache.set(material, new Set());
+ }
+
+ return cache.get(material);
+ }
+
+ _getShaderStage(code) {
+ const cache = this.shaderCache;
+
+ if (cache.has(code) === false) {
+ const stage = new WebGLShaderStage();
+ cache.set(code, stage);
+ }
+
+ return cache.get(code);
+ }
+
+}
+
+class WebGLShaderStage {
+ constructor() {
+ this.id = _id++;
+ this.usedTimes = 0;
+ }
+
+}
+
+function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
+ const _programLayers = new Layers();
+
+ const _customShaders = new WebGLShaderCache();
+
+ const programs = [];
+ const isWebGL2 = capabilities.isWebGL2;
+ const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
+ const floatVertexTextures = capabilities.floatVertexTextures;
+ const maxVertexUniforms = capabilities.maxVertexUniforms;
+ const vertexTextures = capabilities.vertexTextures;
+ let precision = capabilities.precision;
+ const shaderIDs = {
+ MeshDepthMaterial: 'depth',
+ MeshDistanceMaterial: 'distanceRGBA',
+ 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 getMaxBones(object) {
+ const skeleton = object.skeleton;
+ const bones = skeleton.bones;
+
+ if (floatVertexTextures) {
+ 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)
+ const nVertexUniforms = maxVertexUniforms;
+ const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
+ const maxBones = Math.min(nVertexMatrices, bones.length);
+
+ if (maxBones < bones.length) {
+ console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
+ return 0;
+ }
+
+ return maxBones;
+ }
+ }
+
+ function getParameters(material, lights, shadows, scene, object) {
+ const fog = scene.fog;
+ const environment = material.isMeshStandardMaterial ? scene.environment : null;
+ const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
+ const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
+ // (not to blow over maxLights budget)
+
+ const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
+
+ if (material.precision !== null) {
+ precision = capabilities.getMaxPrecision(material.precision);
+
+ if (precision !== material.precision) {
+ console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
+ }
+ }
+
+ 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 useAlphaTest = material.alphaTest > 0;
+ const useClearcoat = material.clearcoat > 0;
+ const parameters = {
+ isWebGL2: isWebGL2,
+ shaderID: shaderID,
+ shaderName: material.type,
+ vertexShader: vertexShader,
+ fragmentShader: fragmentShader,
+ defines: material.defines,
+ customVertexShaderID: customVertexShaderID,
+ customFragmentShaderID: customFragmentShaderID,
+ isRawShaderMaterial: material.isRawShaderMaterial === true,
+ glslVersion: material.glslVersion,
+ precision: precision,
+ instancing: object.isInstancedMesh === true,
+ instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
+ supportsVertexTextures: vertexTextures,
+ outputEncoding: currentRenderTarget === null ? renderer.outputEncoding : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding,
+ map: !!material.map,
+ matcap: !!material.matcap,
+ envMap: !!envMap,
+ envMapMode: envMap && envMap.mapping,
+ envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
+ lightMap: !!material.lightMap,
+ aoMap: !!material.aoMap,
+ emissiveMap: !!material.emissiveMap,
+ bumpMap: !!material.bumpMap,
+ normalMap: !!material.normalMap,
+ objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
+ tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
+ decodeVideoTexture: !!material.map && material.map.isVideoTexture === true && material.map.encoding === sRGBEncoding,
+ clearcoat: useClearcoat,
+ clearcoatMap: useClearcoat && !!material.clearcoatMap,
+ clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
+ clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
+ displacementMap: !!material.displacementMap,
+ roughnessMap: !!material.roughnessMap,
+ metalnessMap: !!material.metalnessMap,
+ specularMap: !!material.specularMap,
+ specularIntensityMap: !!material.specularIntensityMap,
+ specularColorMap: !!material.specularColorMap,
+ alphaMap: !!material.alphaMap,
+ alphaTest: useAlphaTest,
+ alphaWrite: material.alphaWrite || material.transparent,
+ gradientMap: !!material.gradientMap,
+ sheen: material.sheen > 0,
+ sheenColorMap: !!material.sheenColorMap,
+ sheenRoughnessMap: !!material.sheenRoughnessMap,
+ transmission: material.transmission > 0,
+ transmissionMap: !!material.transmissionMap,
+ thicknessMap: !!material.thicknessMap,
+ combine: material.combine,
+ vertexTangents: !!material.normalMap && !!object.geometry && !!object.geometry.attributes.tangent,
+ vertexColors: material.vertexColors,
+ vertexAlphas: material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
+ vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || !!material.sheenColorMap || !!material.sheenRoughnessMap,
+ uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || material.sheen > 0 || !!material.sheenColorMap || !!material.sheenRoughnessMap) && !!material.displacementMap,
+ fog: !!fog,
+ useFog: material.fog,
+ fogExp2: fog && fog.isFogExp2,
+ flatShading: !!material.flatShading,
+ sizeAttenuation: material.sizeAttenuation,
+ logarithmicDepthBuffer: logarithmicDepthBuffer,
+ skinning: object.isSkinnedMesh === true && maxBones > 0,
+ maxBones: maxBones,
+ useVertexTexture: floatVertexTextures,
+ morphTargets: !!object.geometry && !!object.geometry.morphAttributes.position,
+ morphNormals: !!object.geometry && !!object.geometry.morphAttributes.normal,
+ morphTargetsCount: !!object.geometry && !!object.geometry.morphAttributes.position ? object.geometry.morphAttributes.position.length : 0,
+ numDirLights: lights.directional.length,
+ numPointLights: lights.point.length,
+ numSpotLights: lights.spot.length,
+ numRectAreaLights: lights.rectArea.length,
+ numHemiLights: lights.hemi.length,
+ numDirLightShadows: lights.directionalShadowMap.length,
+ numPointLightShadows: lights.pointShadowMap.length,
+ numSpotLightShadows: lights.spotShadowMap.length,
+ numClippingPlanes: clipping.numPlanes,
+ numClipIntersection: clipping.numIntersection,
+ dithering: material.dithering,
+ shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
+ shadowMapType: renderer.shadowMap.type,
+ toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
+ physicallyCorrectLights: renderer.physicallyCorrectLights,
+ premultipliedAlpha: material.premultipliedAlpha,
+ doubleSided: material.side === DoubleSide,
+ flipSided: material.side === BackSide,
+ depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
+ index0AttributeName: material.index0AttributeName,
+ extensionDerivatives: material.extensions && material.extensions.derivatives,
+ extensionFragDepth: material.extensions && material.extensions.fragDepth,
+ extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
+ extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
+ rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
+ rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
+ rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
+ customProgramCacheKey: material.customProgramCacheKey()
+ };
+ 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 !== undefined) {
+ 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.outputEncoding);
+ }
+
+ array.push(parameters.customProgramCacheKey);
+ return array.join();
+ }
+
+ function getProgramCacheKeyParameters(array, parameters) {
+ array.push(parameters.precision);
+ array.push(parameters.outputEncoding);
+ array.push(parameters.envMapMode);
+ array.push(parameters.combine);
+ array.push(parameters.vertexUvs);
+ array.push(parameters.fogExp2);
+ array.push(parameters.sizeAttenuation);
+ array.push(parameters.maxBones);
+ array.push(parameters.morphTargetsCount);
+ array.push(parameters.numDirLights);
+ array.push(parameters.numPointLights);
+ array.push(parameters.numSpotLights);
+ array.push(parameters.numHemiLights);
+ array.push(parameters.numRectAreaLights);
+ array.push(parameters.numDirLightShadows);
+ array.push(parameters.numPointLightShadows);
+ array.push(parameters.numSpotLightShadows);
+ array.push(parameters.shadowMapType);
+ array.push(parameters.toneMapping);
+ array.push(parameters.numClippingPlanes);
+ array.push(parameters.numClipIntersection);
+ array.push(parameters.alphaWrite);
+ }
+
+ function getProgramCacheKeyBooleans(array, parameters) {
+ _programLayers.disableAll();
+
+ if (parameters.isWebGL2) _programLayers.enable(0);
+ if (parameters.supportsVertexTextures) _programLayers.enable(1);
+ if (parameters.instancing) _programLayers.enable(2);
+ if (parameters.instancingColor) _programLayers.enable(3);
+ if (parameters.map) _programLayers.enable(4);
+ if (parameters.matcap) _programLayers.enable(5);
+ if (parameters.envMap) _programLayers.enable(6);
+ if (parameters.envMapCubeUV) _programLayers.enable(7);
+ if (parameters.lightMap) _programLayers.enable(8);
+ if (parameters.aoMap) _programLayers.enable(9);
+ if (parameters.emissiveMap) _programLayers.enable(10);
+ if (parameters.bumpMap) _programLayers.enable(11);
+ if (parameters.normalMap) _programLayers.enable(12);
+ if (parameters.objectSpaceNormalMap) _programLayers.enable(13);
+ if (parameters.tangentSpaceNormalMap) _programLayers.enable(14);
+ if (parameters.clearcoat) _programLayers.enable(15);
+ if (parameters.clearcoatMap) _programLayers.enable(16);
+ if (parameters.clearcoatRoughnessMap) _programLayers.enable(17);
+ if (parameters.clearcoatNormalMap) _programLayers.enable(18);
+ if (parameters.displacementMap) _programLayers.enable(19);
+ if (parameters.specularMap) _programLayers.enable(20);
+ if (parameters.roughnessMap) _programLayers.enable(21);
+ if (parameters.metalnessMap) _programLayers.enable(22);
+ if (parameters.gradientMap) _programLayers.enable(23);
+ if (parameters.alphaMap) _programLayers.enable(24);
+ if (parameters.alphaTest) _programLayers.enable(25);
+ if (parameters.vertexColors) _programLayers.enable(26);
+ if (parameters.vertexAlphas) _programLayers.enable(27);
+ if (parameters.vertexUvs) _programLayers.enable(28);
+ if (parameters.vertexTangents) _programLayers.enable(29);
+ if (parameters.uvsVertexOnly) _programLayers.enable(30);
+ if (parameters.fog) _programLayers.enable(31);
+ array.push(_programLayers.mask);
+
+ _programLayers.disableAll();
+
+ if (parameters.useFog) _programLayers.enable(0);
+ if (parameters.flatShading) _programLayers.enable(1);
+ if (parameters.logarithmicDepthBuffer) _programLayers.enable(2);
+ if (parameters.skinning) _programLayers.enable(3);
+ if (parameters.useVertexTexture) _programLayers.enable(4);
+ if (parameters.morphTargets) _programLayers.enable(5);
+ if (parameters.morphNormals) _programLayers.enable(6);
+ if (parameters.premultipliedAlpha) _programLayers.enable(7);
+ if (parameters.shadowMapEnabled) _programLayers.enable(8);
+ if (parameters.physicallyCorrectLights) _programLayers.enable(9);
+ if (parameters.doubleSided) _programLayers.enable(10);
+ if (parameters.flipSided) _programLayers.enable(11);
+ if (parameters.depthPacking) _programLayers.enable(12);
+ if (parameters.dithering) _programLayers.enable(13);
+ if (parameters.specularIntensityMap) _programLayers.enable(14);
+ if (parameters.specularColorMap) _programLayers.enable(15);
+ if (parameters.transmission) _programLayers.enable(16);
+ if (parameters.transmissionMap) _programLayers.enable(17);
+ if (parameters.thicknessMap) _programLayers.enable(18);
+ if (parameters.sheen) _programLayers.enable(19);
+ if (parameters.sheenColorMap) _programLayers.enable(20);
+ if (parameters.sheenRoughnessMap) _programLayers.enable(21);
+ if (parameters.decodeVideoTexture) _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; // Check if code has been already compiled
+
+ for (let p = 0, pl = programs.length; p < pl; p++) {
+ const preexistingProgram = programs[p];
+
+ if (preexistingProgram.cacheKey === cacheKey) {
+ program = preexistingProgram;
+ ++program.usedTimes;
+ break;
+ }
+ }
+
+ if (program === undefined) {
+ program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
+ programs.push(program);
+ }
+
+ return program;
+ }
+
+ function releaseProgram(program) {
+ if (--program.usedTimes === 0) {
+ // Remove from unordered set
+ const i = programs.indexOf(program);
+ programs[i] = programs[programs.length - 1];
+ programs.pop(); // Free WebGL resources
+
+ program.destroy();
+ }
+ }
+
+ function releaseShaderCache(material) {
+ _customShaders.remove(material);
+ }
+
+ function dispose() {
+ _customShaders.dispose();
+ }
+
+ return {
+ getParameters: getParameters,
+ getProgramCacheKey: getProgramCacheKey,
+ getUniforms: getUniforms,
+ acquireProgram: acquireProgram,
+ releaseProgram: releaseProgram,
+ releaseShaderCache: releaseShaderCache,
+ // Exposed for resource monitoring & error feedback via renderer.info:
+ programs: programs,
+ dispose: dispose
+ };
+}
+
+function WebGLProperties() {
+ let properties = new WeakMap();
+
+ function get(object) {
+ let map = properties.get(object);
+
+ if (map === undefined) {
+ 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 = new WeakMap();
+ }
+
+ return {
+ get: get,
+ remove: remove,
+ update: update,
+ dispose: 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.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 getNextRenderItem(object, geometry, material, groupOrder, z, group) {
+ let renderItem = renderItems[renderItemsIndex];
+
+ if (renderItem === undefined) {
+ renderItem = {
+ id: object.id,
+ object: object,
+ geometry: geometry,
+ material: material,
+ groupOrder: groupOrder,
+ renderOrder: object.renderOrder,
+ z: z,
+ group: group
+ };
+ renderItems[renderItemsIndex] = renderItem;
+ } else {
+ renderItem.id = object.id;
+ renderItem.object = object;
+ renderItem.geometry = geometry;
+ renderItem.material = material;
+ 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.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.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() {
+ // Clear references from inactive renderItems in the list
+ 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: opaque,
+ transmissive: transmissive,
+ transparent: transparent,
+ init: init,
+ push: push,
+ unshift: unshift,
+ finish: finish,
+ sort: sort
+ };
+}
+
+function WebGLRenderLists() {
+ let lists = new WeakMap();
+
+ function get(scene, renderCallDepth) {
+ let list;
+
+ if (lists.has(scene) === false) {
+ list = new WebGLRenderList();
+ lists.set(scene, [list]);
+ } else {
+ if (renderCallDepth >= lists.get(scene).length) {
+ list = new WebGLRenderList();
+ lists.get(scene).push(list);
+ } else {
+ list = lists.get(scene)[renderCallDepth];
+ }
+ }
+
+ return list;
+ }
+
+ function dispose() {
+ lists = new WeakMap();
+ }
+
+ return {
+ get: get,
+ dispose: dispose
+ };
+}
+
+function UniformsCache() {
+ const lights = {};
+ return {
+ get: function (light) {
+ if (lights[light.id] !== undefined) {
+ 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] !== undefined) {
+ return lights[light.id];
+ }
+
+ let uniforms;
+
+ switch (light.type) {
+ case 'DirectionalLight':
+ uniforms = {
+ shadowBias: 0,
+ shadowNormalBias: 0,
+ shadowRadius: 1,
+ shadowMapSize: new Vector2()
+ };
+ break;
+
+ case 'SpotLight':
+ uniforms = {
+ shadowBias: 0,
+ shadowNormalBias: 0,
+ shadowRadius: 1,
+ shadowMapSize: new Vector2()
+ };
+ break;
+
+ case 'PointLight':
+ uniforms = {
+ shadowBias: 0,
+ shadowNormalBias: 0,
+ shadowRadius: 1,
+ shadowMapSize: new Vector2(),
+ shadowCameraNear: 1,
+ shadowCameraFar: 1000
+ };
+ break;
+ // TODO (abelnation): set RectAreaLight shadow uniforms
+ }
+
+ lights[light.id] = uniforms;
+ return uniforms;
+ }
+ };
+}
+
+let nextVersion = 0;
+
+function shadowCastingLightsFirst(lightA, lightB) {
+ return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
+}
+
+function WebGLLights(extensions, capabilities) {
+ 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
+ },
+ ambient: [0, 0, 0],
+ probe: [],
+ directional: [],
+ directionalShadow: [],
+ directionalShadowMap: [],
+ directionalShadowMatrix: [],
+ spot: [],
+ spotShadow: [],
+ spotShadowMap: [],
+ spotShadowMatrix: [],
+ rectArea: [],
+ rectAreaLTC1: null,
+ rectAreaLTC2: null,
+ point: [],
+ pointShadow: [],
+ pointShadowMap: [],
+ pointShadowMatrix: [],
+ hemi: []
+ };
+
+ 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, physicallyCorrectLights) {
+ 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;
+ lights.sort(shadowCastingLightsFirst); // artist-friendly light intensity scaling factor
+
+ const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
+
+ 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;
+ const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
+
+ if (light.isAmbientLight) {
+ r += color.r * intensity * scaleFactor;
+ g += color.g * intensity * scaleFactor;
+ b += color.b * intensity * scaleFactor;
+ } else if (light.isLightProbe) {
+ for (let j = 0; j < 9; j++) {
+ state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
+ }
+ } else if (light.isDirectionalLight) {
+ const uniforms = cache.get(light);
+ uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
+
+ if (light.castShadow) {
+ const shadow = light.shadow;
+ const shadowUniforms = shadowCache.get(light);
+ 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 * scaleFactor);
+ uniforms.distance = distance;
+ uniforms.coneCos = Math.cos(light.angle);
+ uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
+ uniforms.decay = light.decay;
+
+ if (light.castShadow) {
+ const shadow = light.shadow;
+ const shadowUniforms = shadowCache.get(light);
+ shadowUniforms.shadowBias = shadow.bias;
+ shadowUniforms.shadowNormalBias = shadow.normalBias;
+ shadowUniforms.shadowRadius = shadow.radius;
+ shadowUniforms.shadowMapSize = shadow.mapSize;
+ state.spotShadow[spotLength] = shadowUniforms;
+ state.spotShadowMap[spotLength] = shadowMap;
+ state.spotShadowMatrix[spotLength] = light.shadow.matrix;
+ numSpotShadows++;
+ }
+
+ state.spot[spotLength] = uniforms;
+ spotLength++;
+ } else if (light.isRectAreaLight) {
+ const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
+ //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
+ // (b) intensity is the brightness of the light
+
+ uniforms.color.copy(color).multiplyScalar(intensity);
+ uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
+ uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
+ state.rectArea[rectAreaLength] = uniforms;
+ rectAreaLength++;
+ } else if (light.isPointLight) {
+ const uniforms = cache.get(light);
+ uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
+ uniforms.distance = light.distance;
+ uniforms.decay = light.decay;
+
+ if (light.castShadow) {
+ const shadow = light.shadow;
+ const shadowUniforms = shadowCache.get(light);
+ 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 * scaleFactor);
+ uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
+ state.hemi[hemiLength] = uniforms;
+ hemiLength++;
+ }
+ }
+
+ if (rectAreaLength > 0) {
+ if (capabilities.isWebGL2) {
+ // WebGL 2
+ state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
+ state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
+ } else {
+ // WebGL 1
+ if (extensions.has('OES_texture_float_linear') === true) {
+ state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
+ state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
+ } else if (extensions.has('OES_texture_half_float_linear') === true) {
+ state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
+ state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
+ } else {
+ console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
+ }
+ }
+ }
+
+ 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) {
+ 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.spotShadowMatrix.length = numSpotShadows;
+ hash.directionalLength = directionalLength;
+ hash.pointLength = pointLength;
+ hash.spotLength = spotLength;
+ hash.rectAreaLength = rectAreaLength;
+ hash.hemiLength = hemiLength;
+ hash.numDirectionalShadows = numDirectionalShadows;
+ hash.numPointShadows = numPointShadows;
+ hash.numSpotShadows = numSpotShadows;
+ 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); // extract local rotation of light to derive width/height half vectors
+
+ matrix42.identity();
+ matrix4.copy(light.matrixWorld);
+ matrix4.premultiply(viewMatrix);
+ matrix42.extractRotation(matrix4);
+ uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
+ uniforms.halfHeight.set(0.0, light.height * 0.5, 0.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);
+ uniforms.direction.normalize();
+ hemiLength++;
+ }
+ }
+ }
+
+ return {
+ setup: setup,
+ setupView: setupView,
+ state: state
+ };
+}
+
+function WebGLRenderState(extensions, capabilities) {
+ const lights = new WebGLLights(extensions, capabilities);
+ const lightsArray = [];
+ const shadowsArray = [];
+
+ function init() {
+ lightsArray.length = 0;
+ shadowsArray.length = 0;
+ }
+
+ function pushLight(light) {
+ lightsArray.push(light);
+ }
+
+ function pushShadow(shadowLight) {
+ shadowsArray.push(shadowLight);
+ }
+
+ function setupLights(physicallyCorrectLights) {
+ lights.setup(lightsArray, physicallyCorrectLights);
+ }
+
+ function setupLightsView(camera) {
+ lights.setupView(lightsArray, camera);
+ }
+
+ const state = {
+ lightsArray: lightsArray,
+ shadowsArray: shadowsArray,
+ lights: lights
+ };
+ return {
+ init: init,
+ state: state,
+ setupLights: setupLights,
+ setupLightsView: setupLightsView,
+ pushLight: pushLight,
+ pushShadow: pushShadow
+ };
+}
+
+function WebGLRenderStates(extensions, capabilities) {
+ let renderStates = new WeakMap();
+
+ function get(scene, renderCallDepth = 0) {
+ let renderState;
+
+ if (renderStates.has(scene) === false) {
+ renderState = new WebGLRenderState(extensions, capabilities);
+ renderStates.set(scene, [renderState]);
+ } else {
+ if (renderCallDepth >= renderStates.get(scene).length) {
+ renderState = new WebGLRenderState(extensions, capabilities);
+ renderStates.get(scene).push(renderState);
+ } else {
+ renderState = renderStates.get(scene)[renderCallDepth];
+ }
+ }
+
+ return renderState;
+ }
+
+ function dispose() {
+ renderStates = new WeakMap();
+ }
+
+ return {
+ get: get,
+ dispose: dispose
+ };
+}
+
+/**
+ * parameters = {
+ *
+ * opacity: <float>,
+ *
+ * map: new THREE.Texture( <Image> ),
+ *
+ * alphaMap: new THREE.Texture( <Image> ),
+ *
+ * displacementMap: new THREE.Texture( <Image> ),
+ * displacementScale: <float>,
+ * displacementBias: <float>,
+ *
+ * wireframe: <boolean>,
+ * wireframeLinewidth: <float>
+ * }
+ */
+
+class MeshDepthMaterial extends Material {
+ constructor(parameters) {
+ super();
+ 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.fog = false;
+ 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;
+ }
+
+}
+
+MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
+
+/**
+ * parameters = {
+ *
+ * referencePosition: <float>,
+ * nearDistance: <float>,
+ * farDistance: <float>,
+ *
+ * map: new THREE.Texture( <Image> ),
+ *
+ * alphaMap: new THREE.Texture( <Image> ),
+ *
+ * displacementMap: new THREE.Texture( <Image> ),
+ * displacementScale: <float>,
+ * displacementBias: <float>
+ *
+ * }
+ */
+
+class MeshDistanceMaterial extends Material {
+ constructor(parameters) {
+ super();
+ this.type = 'MeshDistanceMaterial';
+ this.referencePosition = new Vector3();
+ this.nearDistance = 1;
+ this.farDistance = 1000;
+ this.map = null;
+ this.alphaMap = null;
+ this.displacementMap = null;
+ this.displacementScale = 1;
+ this.displacementBias = 0;
+ this.fog = false;
+ this.setValues(parameters);
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.referencePosition.copy(source.referencePosition);
+ this.nearDistance = source.nearDistance;
+ this.farDistance = source.farDistance;
+ this.map = source.map;
+ this.alphaMap = source.alphaMap;
+ this.displacementMap = source.displacementMap;
+ this.displacementScale = source.displacementScale;
+ this.displacementBias = source.displacementBias;
+ return this;
+ }
+
+}
+
+MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
+
+const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
+const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
+
+function WebGLShadowMap(_renderer, _objects, _capabilities) {
+ let _frustum = new Frustum();
+
+ const _shadowMapSize = new Vector2(),
+ _viewportSize = new Vector2(),
+ _viewport = new Vector4(),
+ _depthMaterial = new MeshDepthMaterial({
+ depthPacking: RGBADepthPacking
+ }),
+ _distanceMaterial = new MeshDistanceMaterial(),
+ _materialCache = {},
+ _maxTextureSize = _capabilities.maxTextureSize;
+
+ const shadowSide = {
+ 0: BackSide,
+ 1: FrontSide,
+ 2: DoubleSide
+ };
+ const shadowMaterialVertical = new ShaderMaterial({
+ defines: {
+ VSM_SAMPLES: 8
+ },
+ uniforms: {
+ shadow_pass: {
+ value: null
+ },
+ resolution: {
+ value: new Vector2()
+ },
+ radius: {
+ value: 4.0
+ }
+ },
+ 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;
+
+ this.render = function (lights, scene, camera) {
+ if (scope.enabled === false) return;
+ if (scope.autoUpdate === false && scope.needsUpdate === false) return;
+ if (lights.length === 0) return;
+
+ const currentRenderTarget = _renderer.getRenderTarget();
+
+ const activeCubeFace = _renderer.getActiveCubeFace();
+
+ const activeMipmapLevel = _renderer.getActiveMipmapLevel();
+
+ const _state = _renderer.state; // Set GL state for depth map.
+
+ _state.setBlending(NoBlending);
+
+ _state.buffers.color.setClear(1, 1, 1, 1);
+
+ _state.buffers.depth.setTest(true);
+
+ _state.setScissorTest(false); // render depth map
+
+
+ for (let i = 0, il = lights.length; i < il; i++) {
+ const light = lights[i];
+ const shadow = light.shadow;
+
+ if (shadow === undefined) {
+ console.warn('THREE.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;
+ }
+ }
+
+ if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
+ const pars = {
+ minFilter: LinearFilter,
+ magFilter: LinearFilter,
+ format: RGBAFormat
+ };
+ shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
+ shadow.map.texture.name = light.name + '.shadowMap';
+ shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
+ shadow.camera.updateProjectionMatrix();
+ }
+
+ if (shadow.map === null) {
+ const pars = {
+ minFilter: NearestFilter,
+ magFilter: NearestFilter,
+ format: RGBAFormat
+ };
+ shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
+ shadow.map.texture.name = light.name + '.shadowMap';
+ shadow.camera.updateProjectionMatrix();
+ }
+
+ _renderer.setRenderTarget(shadow.map);
+
+ _renderer.clear();
+
+ const viewportCount = shadow.getViewportCount();
+
+ for (let vp = 0; vp < viewportCount; vp++) {
+ const viewport = shadow.getViewport(vp);
+
+ _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
+
+ _state.viewport(_viewport);
+
+ shadow.updateMatrices(light, vp);
+ _frustum = shadow.getFrustum();
+ renderObject(scene, camera, shadow.camera, light, this.type);
+ } // do blur pass for VSM
+
+
+ if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
+ VSMPass(shadow, camera);
+ }
+
+ shadow.needsUpdate = false;
+ }
+
+ 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;
+ } // vertical pass
+
+
+ shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
+ 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); // horizontal pass
+
+
+ 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, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
+ let result = null;
+ const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
+
+ if (customMaterial !== undefined) {
+ result = customMaterial;
+ } else {
+ result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
+ }
+
+ if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
+ // in this case we need a unique material instance reflecting the
+ // appropriate state
+ const keyA = result.uuid,
+ keyB = material.uuid;
+ let materialsForVariant = _materialCache[keyA];
+
+ if (materialsForVariant === undefined) {
+ materialsForVariant = {};
+ _materialCache[keyA] = materialsForVariant;
+ }
+
+ let cachedMaterial = materialsForVariant[keyB];
+
+ if (cachedMaterial === undefined) {
+ cachedMaterial = result.clone();
+ materialsForVariant[keyB] = cachedMaterial;
+ }
+
+ 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.alphaTest;
+ 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) {
+ result.referencePosition.setFromMatrixPosition(light.matrixWorld);
+ result.nearDistance = shadowCameraNear;
+ result.farDistance = shadowCameraFar;
+ }
+
+ 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 || _frustum.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, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
+
+ _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
+ }
+ }
+ } else if (material.visible) {
+ const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
+
+ _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
+ }
+ }
+ }
+
+ const children = object.children;
+
+ for (let i = 0, l = children.length; i < l; i++) {
+ renderObject(children[i], camera, shadowCamera, light, type);
+ }
+ }
+}
+
+function WebGLState(gl, extensions, capabilities) {
+ const isWebGL2 = capabilities.isWebGL2;
+
+ 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); // set to invalid state
+ }
+ };
+ }
+
+ function DepthBuffer() {
+ let locked = false;
+ let currentDepthMask = null;
+ let currentDepthFunc = null;
+ let currentDepthClear = null;
+ return {
+ 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 (currentDepthFunc !== depthFunc) {
+ if (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);
+ }
+ } else {
+ gl.depthFunc(gl.LEQUAL);
+ }
+
+ currentDepthFunc = depthFunc;
+ }
+ },
+ setLocked: function (lock) {
+ locked = lock;
+ },
+ setClear: function (depth) {
+ if (currentDepthClear !== depth) {
+ gl.clearDepth(depth);
+ currentDepthClear = depth;
+ }
+ },
+ reset: function () {
+ locked = false;
+ currentDepthMask = null;
+ currentDepthFunc = null;
+ currentDepthClear = null;
+ }
+ };
+ }
+
+ 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();
+ let enabledCapabilities = {};
+ let currentBoundFramebuffers = {};
+ let currentDrawbuffers = 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 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.0;
+ } else if (glVersion.indexOf('OpenGL ES') !== -1) {
+ version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
+ lineWidthAvailable = version >= 2.0;
+ }
+
+ 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) {
+ const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 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++) {
+ 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); // init
+
+ 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 (isWebGL2) {
+ // gl.DRAW_FRAMEBUFFER is equivalent to gl.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 drawBuffers = defaultDrawbuffers;
+ let needsUpdate = false;
+
+ if (renderTarget) {
+ drawBuffers = currentDrawbuffers.get(framebuffer);
+
+ if (drawBuffers === undefined) {
+ drawBuffers = [];
+ currentDrawbuffers.set(framebuffer, drawBuffers);
+ }
+
+ if (renderTarget.isWebGLMultipleRenderTargets) {
+ const textures = renderTarget.texture;
+
+ if (drawBuffers.length !== textures.length || drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
+ for (let i = 0, il = textures.length; i < il; i++) {
+ drawBuffers[i] = gl.COLOR_ATTACHMENT0 + i;
+ }
+
+ drawBuffers.length = textures.length;
+ needsUpdate = true;
+ }
+ } else {
+ if (drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
+ drawBuffers[0] = gl.COLOR_ATTACHMENT0;
+ needsUpdate = true;
+ }
+ }
+ } else {
+ if (drawBuffers[0] !== gl.BACK) {
+ drawBuffers[0] = gl.BACK;
+ needsUpdate = true;
+ }
+ }
+
+ if (needsUpdate) {
+ if (capabilities.isWebGL2) {
+ gl.drawBuffers(drawBuffers);
+ } else {
+ extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(drawBuffers);
+ }
+ }
+ }
+
+ 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
+ };
+
+ if (isWebGL2) {
+ equationToGL[MinEquation] = gl.MIN;
+ equationToGL[MaxEquation] = gl.MAX;
+ } else {
+ const extension = extensions.get('EXT_blend_minmax');
+
+ if (extension !== null) {
+ equationToGL[MinEquation] = extension.MIN_EXT;
+ equationToGL[MaxEquation] = extension.MAX_EXT;
+ }
+ }
+
+ 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
+ };
+
+ function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, 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.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
+ break;
+
+ default:
+ console.error('THREE.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.blendFunc(gl.SRC_ALPHA, gl.ONE);
+ break;
+
+ case SubtractiveBlending:
+ gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
+ break;
+
+ case MultiplyBlending:
+ gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
+ break;
+
+ default:
+ console.error('THREE.WebGLState: Invalid blending: ', blending);
+ break;
+ }
+ }
+
+ currentBlendSrc = null;
+ currentBlendDst = null;
+ currentBlendSrcAlpha = null;
+ currentBlendDstAlpha = null;
+ currentBlending = blending;
+ currentPremultipledAlpha = premultipliedAlpha;
+ }
+
+ return;
+ } // custom blending
+
+
+ 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;
+ }
+
+ currentBlending = blending;
+ currentPremultipledAlpha = null;
+ }
+
+ 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.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) {
+ gl.polygonOffset(factor, units);
+ currentPolygonOffsetFactor = factor;
+ currentPolygonOffsetUnits = units;
+ }
+ } else {
+ disable(gl.POLYGON_OFFSET_FILL);
+ }
+ }
+
+ function setScissorTest(scissorTest) {
+ if (scissorTest) {
+ enable(gl.SCISSOR_TEST);
+ } else {
+ disable(gl.SCISSOR_TEST);
+ }
+ } // texture
+
+
+ function activeTexture(webglSlot) {
+ if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
+
+ if (currentTextureSlot !== webglSlot) {
+ gl.activeTexture(webglSlot);
+ currentTextureSlot = webglSlot;
+ }
+ }
+
+ function bindTexture(webglType, webglTexture) {
+ if (currentTextureSlot === null) {
+ activeTexture();
+ }
+
+ let boundTexture = currentBoundTextures[currentTextureSlot];
+
+ if (boundTexture === undefined) {
+ boundTexture = {
+ type: undefined,
+ texture: undefined
+ };
+ currentBoundTextures[currentTextureSlot] = boundTexture;
+ }
+
+ if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
+ gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
+ boundTexture.type = webglType;
+ boundTexture.texture = webglTexture;
+ }
+ }
+
+ function unbindTexture() {
+ const boundTexture = currentBoundTextures[currentTextureSlot];
+
+ if (boundTexture !== undefined && boundTexture.type !== undefined) {
+ gl.bindTexture(boundTexture.type, null);
+ boundTexture.type = undefined;
+ boundTexture.texture = undefined;
+ }
+ }
+
+ function compressedTexImage2D() {
+ try {
+ gl.compressedTexImage2D.apply(gl, arguments);
+ } catch (error) {
+ console.error('THREE.WebGLState:', error);
+ }
+ }
+
+ function texSubImage2D() {
+ try {
+ gl.texSubImage2D.apply(gl, arguments);
+ } catch (error) {
+ console.error('THREE.WebGLState:', error);
+ }
+ }
+
+ function texSubImage3D() {
+ try {
+ gl.texSubImage3D.apply(gl, arguments);
+ } catch (error) {
+ console.error('THREE.WebGLState:', error);
+ }
+ }
+
+ function compressedTexSubImage2D() {
+ try {
+ gl.compressedTexSubImage2D.apply(gl, arguments);
+ } catch (error) {
+ console.error('THREE.WebGLState:', error);
+ }
+ }
+
+ function texStorage2D() {
+ try {
+ gl.texStorage2D.apply(gl, arguments);
+ } catch (error) {
+ console.error('THREE.WebGLState:', error);
+ }
+ }
+
+ function texStorage3D() {
+ try {
+ gl.texStorage3D.apply(gl, arguments);
+ } catch (error) {
+ console.error('THREE.WebGLState:', error);
+ }
+ }
+
+ function texImage2D() {
+ try {
+ gl.texImage2D.apply(gl, arguments);
+ } catch (error) {
+ console.error('THREE.WebGLState:', error);
+ }
+ }
+
+ function texImage3D() {
+ try {
+ gl.texImage3D.apply(gl, arguments);
+ } catch (error) {
+ console.error('THREE.WebGLState:', error);
+ }
+ } //
+
+
+ function scissor(scissor) {
+ if (currentScissor.equals(scissor) === false) {
+ gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
+ currentScissor.copy(scissor);
+ }
+ }
+
+ function viewport(viewport) {
+ if (currentViewport.equals(viewport) === false) {
+ gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
+ currentViewport.copy(viewport);
+ }
+ } //
+
+
+ function reset() {
+ // reset state
+ 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.colorMask(true, true, true, true);
+ gl.clearColor(0, 0, 0, 0);
+ gl.depthMask(true);
+ gl.depthFunc(gl.LESS);
+ gl.clearDepth(1);
+ gl.stencilMask(0xffffffff);
+ gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
+ 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);
+
+ if (isWebGL2 === true) {
+ 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); // reset internals
+
+ enabledCapabilities = {};
+ currentTextureSlot = null;
+ currentBoundTextures = {};
+ currentBoundFramebuffers = {};
+ currentDrawbuffers = new WeakMap();
+ defaultDrawbuffers = [];
+ currentProgram = null;
+ currentBlendingEnabled = false;
+ currentBlending = null;
+ currentBlendEquation = null;
+ currentBlendSrc = null;
+ currentBlendDst = null;
+ currentBlendEquationAlpha = null;
+ currentBlendSrcAlpha = null;
+ currentBlendDstAlpha = null;
+ 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: enable,
+ disable: disable,
+ bindFramebuffer: bindFramebuffer,
+ drawBuffers: drawBuffers,
+ useProgram: useProgram,
+ setBlending: setBlending,
+ setMaterial: setMaterial,
+ setFlipSided: setFlipSided,
+ setCullFace: setCullFace,
+ setLineWidth: setLineWidth,
+ setPolygonOffset: setPolygonOffset,
+ setScissorTest: setScissorTest,
+ activeTexture: activeTexture,
+ bindTexture: bindTexture,
+ unbindTexture: unbindTexture,
+ compressedTexImage2D: compressedTexImage2D,
+ texImage2D: texImage2D,
+ texImage3D: texImage3D,
+ texStorage2D: texStorage2D,
+ texStorage3D: texStorage3D,
+ texSubImage2D: texSubImage2D,
+ texSubImage3D: texSubImage3D,
+ compressedTexSubImage2D: compressedTexSubImage2D,
+ scissor: scissor,
+ viewport: viewport,
+ reset: reset
+ };
+}
+
+function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
+ const isWebGL2 = capabilities.isWebGL2;
+ const maxTextures = capabilities.maxTextures;
+ const maxCubemapSize = capabilities.maxCubemapSize;
+ const maxTextureSize = capabilities.maxTextureSize;
+ const maxSamples = capabilities.maxSamples;
+ const hasMultisampledRenderToTexture = extensions.has('WEBGL_multisampled_render_to_texture');
+ const MultisampledRenderToTextureExtension = hasMultisampledRenderToTexture ? extensions.get('WEBGL_multisampled_render_to_texture') : undefined;
+
+ const _videoTextures = new WeakMap();
+
+ let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
+ // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
+ // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
+
+
+ let useOffscreenCanvas = false;
+
+ try {
+ useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
+ } catch (err) {// Ignore any errors
+ }
+
+ function createCanvas(width, height) {
+ // Use OffscreenCanvas when available. Specially needed in web workers
+ return useOffscreenCanvas ? new OffscreenCanvas(width, height) : createElementNS('canvas');
+ }
+
+ function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
+ let scale = 1; // handle case if texture exceeds max size
+
+ if (image.width > maxSize || image.height > maxSize) {
+ scale = maxSize / Math.max(image.width, image.height);
+ } // only perform resize if necessary
+
+
+ if (scale < 1 || needsPowerOfTwo === true) {
+ // only perform resize for certain image types
+ if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
+ const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
+ const width = floor(scale * image.width);
+ const height = floor(scale * image.height);
+ if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
+
+ const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
+ canvas.width = width;
+ canvas.height = height;
+ const context = canvas.getContext('2d');
+ context.drawImage(image, 0, 0, width, height);
+ console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
+ return canvas;
+ } else {
+ if ('data' in image) {
+ console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
+ }
+
+ return image;
+ }
+ }
+
+ return image;
+ }
+
+ function isPowerOfTwo$1(image) {
+ return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
+ }
+
+ function textureNeedsPowerOfTwo(texture) {
+ if (isWebGL2) return false;
+ return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
+ }
+
+ function textureNeedsGenerateMipmaps(texture, supportsMips) {
+ return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
+ }
+
+ function generateMipmap(target) {
+ _gl.generateMipmap(target);
+ }
+
+ function getInternalFormat(internalFormatName, glFormat, glType, encoding, isVideoTexture = false) {
+ if (isWebGL2 === false) return glFormat;
+
+ if (internalFormatName !== null) {
+ if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
+ console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
+ }
+
+ 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 (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 (glFormat === _gl.RGBA) {
+ if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
+ if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
+ if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding && isVideoTexture === false ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
+ 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 getMipLevels(texture, image, supportsMips) {
+ if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
+ return Math.log2(Math.max(image.width, image.height)) + 1;
+ } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) {
+ // user-defined mipmaps
+ return texture.mipmaps.length;
+ } else if (texture.isCompressedTexture && Array.isArray(texture.image)) {
+ return image.mipmaps.length;
+ } else {
+ // texture without mipmaps (only base level)
+ return 1;
+ }
+ } // Fallback filters for non-power-of-2 textures
+
+
+ function filterFallback(f) {
+ if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
+ return _gl.NEAREST;
+ }
+
+ return _gl.LINEAR;
+ } //
+
+
+ function onTextureDispose(event) {
+ const texture = event.target;
+ texture.removeEventListener('dispose', onTextureDispose);
+ deallocateTexture(texture);
+
+ if (texture.isVideoTexture) {
+ _videoTextures.delete(texture);
+ }
+
+ info.memory.textures--;
+ }
+
+ function onRenderTargetDispose(event) {
+ const renderTarget = event.target;
+ renderTarget.removeEventListener('dispose', onRenderTargetDispose);
+ deallocateRenderTarget(renderTarget);
+ } //
+
+
+ function deallocateTexture(texture) {
+ const textureProperties = properties.get(texture);
+ if (textureProperties.__webglInit === undefined) return;
+
+ _gl.deleteTexture(textureProperties.__webglTexture);
+
+ properties.remove(texture);
+ }
+
+ function deallocateRenderTarget(renderTarget) {
+ const texture = renderTarget.texture;
+ const renderTargetProperties = properties.get(renderTarget);
+ const textureProperties = properties.get(texture);
+ if (!renderTarget) return;
+
+ if (textureProperties.__webglTexture !== undefined) {
+ _gl.deleteTexture(textureProperties.__webglTexture);
+
+ info.memory.textures--;
+ }
+
+ if (renderTarget.depthTexture) {
+ renderTarget.depthTexture.dispose();
+ }
+
+ if (renderTarget.isWebGLCubeRenderTarget) {
+ for (let i = 0; i < 6; i++) {
+ _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
+
+ if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
+ }
+ } else {
+ _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
+
+ if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
+ if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
+ if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
+ if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
+ }
+
+ if (renderTarget.isWebGLMultipleRenderTargets) {
+ for (let i = 0, il = texture.length; i < il; i++) {
+ const attachmentProperties = properties.get(texture[i]);
+
+ if (attachmentProperties.__webglTexture) {
+ _gl.deleteTexture(attachmentProperties.__webglTexture);
+
+ info.memory.textures--;
+ }
+
+ properties.remove(texture[i]);
+ }
+ }
+
+ properties.remove(texture);
+ properties.remove(renderTarget);
+ } //
+
+
+ let textureUnits = 0;
+
+ function resetTextureUnits() {
+ textureUnits = 0;
+ }
+
+ function allocateTextureUnit() {
+ const textureUnit = textureUnits;
+
+ if (textureUnit >= maxTextures) {
+ console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
+ }
+
+ textureUnits += 1;
+ return textureUnit;
+ } //
+
+
+ function setTexture2D(texture, slot) {
+ const textureProperties = properties.get(texture);
+ if (texture.isVideoTexture) updateVideoTexture(texture);
+
+ if (texture.version > 0 && textureProperties.__version !== texture.version) {
+ const image = texture.image;
+
+ if (image === undefined) {
+ console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
+ } else if (image.complete === false) {
+ console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
+ } else {
+ uploadTexture(textureProperties, texture, slot);
+ return;
+ }
+ }
+
+ state.activeTexture(_gl.TEXTURE0 + slot);
+ state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
+ }
+
+ function setTexture2DArray(texture, slot) {
+ const textureProperties = properties.get(texture);
+
+ if (texture.version > 0 && textureProperties.__version !== texture.version) {
+ uploadTexture(textureProperties, texture, slot);
+ return;
+ }
+
+ state.activeTexture(_gl.TEXTURE0 + slot);
+ state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
+ }
+
+ function setTexture3D(texture, slot) {
+ const textureProperties = properties.get(texture);
+
+ if (texture.version > 0 && textureProperties.__version !== texture.version) {
+ uploadTexture(textureProperties, texture, slot);
+ return;
+ }
+
+ state.activeTexture(_gl.TEXTURE0 + slot);
+ state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
+ }
+
+ function setTextureCube(texture, slot) {
+ const textureProperties = properties.get(texture);
+
+ if (texture.version > 0 && textureProperties.__version !== texture.version) {
+ uploadCubeTexture(textureProperties, texture, slot);
+ return;
+ }
+
+ state.activeTexture(_gl.TEXTURE0 + slot);
+ state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
+ }
+
+ 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
+ };
+
+ function setTextureParameters(textureType, texture, supportsMips) {
+ if (supportsMips) {
+ _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]);
+ } else {
+ _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
+
+ _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
+
+ if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
+ _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
+ }
+
+ if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
+ console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
+ }
+
+ _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
+
+ _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
+
+ if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
+ console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
+ }
+ }
+
+ if (extensions.has('EXT_texture_filter_anisotropic') === true) {
+ const extension = extensions.get('EXT_texture_filter_anisotropic');
+ if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
+
+ if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
+
+ if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
+ _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
+
+ properties.get(texture).__currentAnisotropy = texture.anisotropy;
+ }
+ }
+ }
+
+ function initTexture(textureProperties, texture) {
+ if (textureProperties.__webglInit === undefined) {
+ textureProperties.__webglInit = true;
+ texture.addEventListener('dispose', onTextureDispose);
+ textureProperties.__webglTexture = _gl.createTexture();
+ info.memory.textures++;
+ }
+ }
+
+ function uploadTexture(textureProperties, texture, slot) {
+ let textureType = _gl.TEXTURE_2D;
+ if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
+ if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
+ initTexture(textureProperties, texture);
+ state.activeTexture(_gl.TEXTURE0 + slot);
+ state.bindTexture(textureType, textureProperties.__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);
+
+ _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
+
+ const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
+ let image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
+ image = verifyColorSpace(texture, image);
+ const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
+ glFormat = utils.convert(texture.format, texture.encoding);
+ let glType = utils.convert(texture.type),
+ glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture);
+ setTextureParameters(textureType, texture, supportsMips);
+ let mipmap;
+ const mipmaps = texture.mipmaps;
+ const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
+ const allocateMemory = textureProperties.__version === undefined;
+ const levels = getMipLevels(texture, image, supportsMips);
+
+ if (texture.isDepthTexture) {
+ // populate depth texture with dummy data
+ glInternalFormat = _gl.DEPTH_COMPONENT;
+
+ if (isWebGL2) {
+ if (texture.type === FloatType) {
+ glInternalFormat = _gl.DEPTH_COMPONENT32F;
+ } else if (texture.type === UnsignedIntType) {
+ glInternalFormat = _gl.DEPTH_COMPONENT24;
+ } else if (texture.type === UnsignedInt248Type) {
+ glInternalFormat = _gl.DEPTH24_STENCIL8;
+ } else {
+ glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
+ }
+ } else {
+ if (texture.type === FloatType) {
+ console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
+ }
+ } // validation checks for WebGL 1
+
+
+ if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
+ // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
+ // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
+ // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
+ if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
+ console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
+ texture.type = UnsignedShortType;
+ glType = utils.convert(texture.type);
+ }
+ }
+
+ if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
+ // Depth stencil textures need the DEPTH_STENCIL internal format
+ // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
+ glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
+ // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
+ // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
+
+ if (texture.type !== UnsignedInt248Type) {
+ console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
+ texture.type = UnsignedInt248Type;
+ glType = utils.convert(texture.type);
+ }
+ } //
+
+
+ if (useTexStorage && allocateMemory) {
+ 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) {
+ // 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 && supportsMips) {
+ 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) {
+ state.texSubImage2D(_gl.TEXTURE_2D, 0, 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);
+ }
+
+ state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data);
+ } else {
+ state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
+ }
+ }
+ } else if (texture.isCompressedTexture) {
+ 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) {
+ 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 {
+ console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
+ }
+ } else {
+ if (useTexStorage) {
+ 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.isDataTexture2DArray) {
+ if (useTexStorage) {
+ if (allocateMemory) {
+ state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth);
+ }
+
+ 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.isDataTexture3D) {
+ if (useTexStorage) {
+ if (allocateMemory) {
+ state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth);
+ }
+
+ 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 (useTexStorage && allocateMemory) {
+ state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
+ } else {
+ state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
+ }
+ } 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 && supportsMips) {
+ 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) {
+ 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) {
+ state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
+ }
+
+ 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, supportsMips)) {
+ generateMipmap(textureType);
+ }
+
+ textureProperties.__version = texture.version;
+ if (texture.onUpdate) texture.onUpdate(texture);
+ }
+
+ function uploadCubeTexture(textureProperties, texture, slot) {
+ if (texture.image.length !== 6) return;
+ initTexture(textureProperties, texture);
+ state.activeTexture(_gl.TEXTURE0 + slot);
+ state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__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);
+
+ _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
+
+ const isCompressed = texture && (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], false, true, maxCubemapSize);
+ } else {
+ cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
+ }
+
+ cubeImage[i] = verifyColorSpace(texture, cubeImage[i]);
+ }
+
+ const image = cubeImage[0],
+ supportsMips = isPowerOfTwo$1(image) || isWebGL2,
+ glFormat = utils.convert(texture.format, texture.encoding),
+ glType = utils.convert(texture.type),
+ glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
+ const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
+ const allocateMemory = textureProperties.__version === undefined;
+ let levels = getMipLevels(texture, image, supportsMips);
+ setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
+ 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) {
+ 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 {
+ console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
+ }
+ } else {
+ if (useTexStorage) {
+ 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) {
+ // TODO: Uniformly handle mipmap definitions
+ // Normal textures and compressed cube textures define base level + mips with their mipmap array
+ // Uncompressed cube textures use their mipmap array only for mips (no base level)
+ if (mipmaps.length > 0) levels++;
+ state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height);
+ }
+
+ for (let i = 0; i < 6; i++) {
+ if (isDataTexture) {
+ if (useTexStorage) {
+ 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) {
+ 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) {
+ 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) {
+ 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, supportsMips)) {
+ // We assume images for cube map have the same size.
+ generateMipmap(_gl.TEXTURE_CUBE_MAP);
+ }
+
+ textureProperties.__version = texture.version;
+ if (texture.onUpdate) texture.onUpdate(texture);
+ } // Render targets
+ // Setup storage for target texture and bind it to correct framebuffer
+
+
+ function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
+ const glFormat = utils.convert(texture.format, texture.encoding);
+ const glType = utils.convert(texture.type);
+ const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
+ const renderTargetProperties = properties.get(renderTarget);
+
+ if (!renderTargetProperties.__hasExternalTextures) {
+ if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
+ state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
+ } else {
+ state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
+ }
+ }
+
+ state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
+
+ if (renderTarget.useRenderToTexture) {
+ MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget));
+ } else {
+ _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
+ }
+
+ state.bindFramebuffer(_gl.FRAMEBUFFER, null);
+ } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
+
+
+ function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
+ _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
+
+ if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
+ let glInternalFormat = _gl.DEPTH_COMPONENT16;
+
+ if (isMultisample || renderTarget.useRenderToTexture) {
+ const depthTexture = renderTarget.depthTexture;
+
+ if (depthTexture && depthTexture.isDepthTexture) {
+ if (depthTexture.type === FloatType) {
+ glInternalFormat = _gl.DEPTH_COMPONENT32F;
+ } else if (depthTexture.type === UnsignedIntType) {
+ glInternalFormat = _gl.DEPTH_COMPONENT24;
+ }
+ }
+
+ const samples = getRenderTargetSamples(renderTarget);
+
+ if (renderTarget.useRenderToTexture) {
+ MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
+ } else {
+ _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
+ }
+ } else {
+ _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
+ }
+
+ _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
+ } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
+ const samples = getRenderTargetSamples(renderTarget);
+
+ if (isMultisample && renderTarget.useRenderbuffer) {
+ _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
+ } else if (renderTarget.useRenderToTexture) {
+ MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
+ } else {
+ _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
+ }
+
+ _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
+ } else {
+ // Use the first texture for MRT so far
+ const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
+ const glFormat = utils.convert(texture.format, texture.encoding);
+ const glType = utils.convert(texture.type);
+ const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
+ const samples = getRenderTargetSamples(renderTarget);
+
+ if (isMultisample && renderTarget.useRenderbuffer) {
+ _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
+ } else if (renderTarget.useRenderToTexture) {
+ MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
+ } else {
+ _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
+ }
+ }
+
+ _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
+ } // Setup resources for a Depth Texture for a FBO (needs an extension)
+
+
+ function setupDepthTexture(framebuffer, renderTarget) {
+ const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
+ if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
+ state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
+
+ if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
+ throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
+ } // upload an empty depth texture with framebuffer size
+
+
+ if (!properties.get(renderTarget.depthTexture).__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;
+ }
+
+ setTexture2D(renderTarget.depthTexture, 0);
+
+ const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
+
+ const samples = getRenderTargetSamples(renderTarget);
+
+ if (renderTarget.depthTexture.format === DepthFormat) {
+ if (renderTarget.useRenderToTexture) {
+ MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
+ } else {
+ _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
+ }
+ } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
+ if (renderTarget.useRenderToTexture) {
+ MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
+ } else {
+ _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
+ }
+ } else {
+ throw new Error('Unknown depthTexture format');
+ }
+ } // Setup GL resources for a non-texture depth buffer
+
+
+ function setupDepthRenderbuffer(renderTarget) {
+ const renderTargetProperties = properties.get(renderTarget);
+ const isCube = renderTarget.isWebGLCubeRenderTarget === true;
+
+ if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) {
+ if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
+ setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
+ } else {
+ if (isCube) {
+ renderTargetProperties.__webglDepthbuffer = [];
+
+ for (let i = 0; i < 6; i++) {
+ state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
+ renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
+ setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
+ }
+ } else {
+ state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
+ renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
+ setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
+ }
+ }
+
+ state.bindFramebuffer(_gl.FRAMEBUFFER, null);
+ } // rebind framebuffer with external textures
+
+
+ function rebindTextures(renderTarget, colorTexture, depthTexture) {
+ const renderTargetProperties = properties.get(renderTarget);
+
+ if (colorTexture !== undefined) {
+ setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D);
+ }
+
+ if (depthTexture !== undefined) {
+ setupDepthRenderbuffer(renderTarget);
+ }
+ } // Set up GL resources for the render target
+
+
+ function setupRenderTarget(renderTarget) {
+ const texture = renderTarget.texture;
+ const renderTargetProperties = properties.get(renderTarget);
+ const textureProperties = properties.get(texture);
+ renderTarget.addEventListener('dispose', onRenderTargetDispose);
+
+ if (renderTarget.isWebGLMultipleRenderTargets !== true) {
+ if (textureProperties.__webglTexture === undefined) {
+ textureProperties.__webglTexture = _gl.createTexture();
+ }
+
+ textureProperties.__version = texture.version;
+ info.memory.textures++;
+ }
+
+ const isCube = renderTarget.isWebGLCubeRenderTarget === true;
+ const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
+ const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
+ const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Setup framebuffer
+
+ if (isCube) {
+ renderTargetProperties.__webglFramebuffer = [];
+
+ for (let i = 0; i < 6; i++) {
+ renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
+ }
+ } else {
+ renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
+
+ if (isMultipleRenderTargets) {
+ if (capabilities.drawBuffers) {
+ const textures = renderTarget.texture;
+
+ for (let i = 0, il = textures.length; i < il; i++) {
+ const attachmentProperties = properties.get(textures[i]);
+
+ if (attachmentProperties.__webglTexture === undefined) {
+ attachmentProperties.__webglTexture = _gl.createTexture();
+ info.memory.textures++;
+ }
+ }
+ } else {
+ console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
+ }
+ } else if (renderTarget.useRenderbuffer) {
+ if (isWebGL2) {
+ renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
+ renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
+
+ _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
+
+ const glFormat = utils.convert(texture.format, texture.encoding);
+ const glType = utils.convert(texture.type);
+ const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
+ const samples = getRenderTargetSamples(renderTarget);
+
+ _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
+
+ state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
+
+ _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
+
+ _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
+
+ if (renderTarget.depthBuffer) {
+ renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
+ setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
+ }
+
+ state.bindFramebuffer(_gl.FRAMEBUFFER, null);
+ } else {
+ console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
+ }
+ }
+ } // Setup color buffer
+
+
+ if (isCube) {
+ state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
+ setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
+
+ for (let i = 0; i < 6; i++) {
+ setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
+ }
+
+ if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
+ generateMipmap(_gl.TEXTURE_CUBE_MAP);
+ }
+
+ state.unbindTexture();
+ } else if (isMultipleRenderTargets) {
+ const textures = renderTarget.texture;
+
+ for (let i = 0, il = textures.length; i < il; i++) {
+ const attachment = textures[i];
+ const attachmentProperties = properties.get(attachment);
+ state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
+ setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
+ setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
+
+ if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
+ generateMipmap(_gl.TEXTURE_2D);
+ }
+ }
+
+ state.unbindTexture();
+ } else {
+ let glTextureType = _gl.TEXTURE_2D;
+
+ if (isRenderTarget3D) {
+ // Render targets containing layers, i.e: Texture 3D and 2d arrays
+ if (isWebGL2) {
+ const isTexture3D = texture.isDataTexture3D;
+ glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
+ } else {
+ console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
+ }
+ }
+
+ state.bindTexture(glTextureType, textureProperties.__webglTexture);
+ setTextureParameters(glTextureType, texture, supportsMips);
+ setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
+
+ if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
+ generateMipmap(glTextureType);
+ }
+
+ state.unbindTexture();
+ } // Setup depth and stencil buffers
+
+
+ if (renderTarget.depthBuffer) {
+ setupDepthRenderbuffer(renderTarget);
+ }
+ }
+
+ function updateRenderTargetMipmap(renderTarget) {
+ const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
+ const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
+
+ for (let i = 0, il = textures.length; i < il; i++) {
+ const texture = textures[i];
+
+ if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
+ const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
+
+ const webglTexture = properties.get(texture).__webglTexture;
+
+ state.bindTexture(target, webglTexture);
+ generateMipmap(target);
+ state.unbindTexture();
+ }
+ }
+ }
+
+ function updateMultisampleRenderTarget(renderTarget) {
+ if (renderTarget.useRenderbuffer) {
+ if (isWebGL2) {
+ const width = renderTarget.width;
+ const height = renderTarget.height;
+ let mask = _gl.COLOR_BUFFER_BIT;
+ const invalidationArray = [_gl.COLOR_ATTACHMENT0];
+ const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
+
+ if (renderTarget.depthBuffer) {
+ invalidationArray.push(depthStyle);
+ }
+
+ if (!renderTarget.ignoreDepthForMultisampleCopy) {
+ if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
+ if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
+ }
+
+ const renderTargetProperties = properties.get(renderTarget);
+ state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
+ state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
+
+ if (renderTarget.ignoreDepthForMultisampleCopy) {
+ _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]);
+
+ _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]);
+ }
+
+ _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
+
+ _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray);
+
+ state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
+ state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
+ } else {
+ console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
+ }
+ }
+ }
+
+ function getRenderTargetSamples(renderTarget) {
+ return isWebGL2 && (renderTarget.useRenderbuffer || renderTarget.useRenderToTexture) ? Math.min(maxSamples, renderTarget.samples) : 0;
+ }
+
+ function updateVideoTexture(texture) {
+ const frame = info.render.frame; // Check the last frame we updated the VideoTexture
+
+ if (_videoTextures.get(texture) !== frame) {
+ _videoTextures.set(texture, frame);
+
+ texture.update();
+ }
+ }
+
+ function verifyColorSpace(texture, image) {
+ const encoding = texture.encoding;
+ const format = texture.format;
+ const type = texture.type;
+ if (texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat) return image;
+
+ if (encoding !== LinearEncoding) {
+ // sRGB
+ if (encoding === sRGBEncoding) {
+ if (isWebGL2 === false) {
+ // in WebGL 1, try to use EXT_sRGB extension and unsized formats
+ if (extensions.has('EXT_sRGB') === true && format === RGBAFormat) {
+ texture.format = _SRGBAFormat; // it's not possible to generate mips in WebGL 1 with this extension
+
+ texture.minFilter = LinearFilter;
+ texture.generateMipmaps = false;
+ } else {
+ // slow fallback (CPU decode)
+ image = ImageUtils.sRGBToLinear(image);
+ }
+ } else {
+ // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
+ if (format !== RGBAFormat || type !== UnsignedByteType) {
+ console.warn('THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.');
+ }
+ }
+ } else {
+ console.error('THREE.WebGLTextures: Unsupported texture encoding:', encoding);
+ }
+ }
+
+ return image;
+ } // backwards compatibility
+
+
+ let warnedTexture2D = false;
+ let warnedTextureCube = false;
+
+ function safeSetTexture2D(texture, slot) {
+ if (texture && texture.isWebGLRenderTarget) {
+ if (warnedTexture2D === false) {
+ console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
+ warnedTexture2D = true;
+ }
+
+ texture = texture.texture;
+ }
+
+ setTexture2D(texture, slot);
+ }
+
+ function safeSetTextureCube(texture, slot) {
+ if (texture && texture.isWebGLCubeRenderTarget) {
+ if (warnedTextureCube === false) {
+ console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
+ warnedTextureCube = true;
+ }
+
+ texture = texture.texture;
+ }
+
+ setTextureCube(texture, slot);
+ } //
+
+
+ this.allocateTextureUnit = allocateTextureUnit;
+ this.resetTextureUnits = resetTextureUnits;
+ 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.safeSetTexture2D = safeSetTexture2D;
+ this.safeSetTextureCube = safeSetTextureCube;
+}
+
+function WebGLUtils(gl, extensions, capabilities) {
+ const isWebGL2 = capabilities.isWebGL2;
+
+ function convert(p, encoding = null) {
+ let extension;
+ 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 === 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) {
+ if (isWebGL2) return gl.HALF_FLOAT;
+ extension = extensions.get('OES_texture_half_float');
+
+ if (extension !== null) {
+ return extension.HALF_FLOAT_OES;
+ } else {
+ return null;
+ }
+ }
+
+ if (p === AlphaFormat) return gl.ALPHA;
+ if (p === RGBAFormat) return gl.RGBA;
+ if (p === LuminanceFormat) return gl.LUMINANCE;
+ if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
+ if (p === DepthFormat) return gl.DEPTH_COMPONENT;
+ if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
+ if (p === RedFormat) return gl.RED; // WebGL 1 sRGB fallback
+
+ if (p === _SRGBAFormat) {
+ extension = extensions.get('EXT_sRGB');
+
+ if (extension !== null) {
+ return extension.SRGB_ALPHA_EXT;
+ } else {
+ return null;
+ }
+ } // WebGL2 formats.
+
+
+ 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; // S3TC
+
+ if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
+ if (encoding === sRGBEncoding) {
+ 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;
+ }
+ }
+ } // PVRTC
+
+
+ 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;
+ }
+ } // ETC1
+
+
+ if (p === RGB_ETC1_Format) {
+ extension = extensions.get('WEBGL_compressed_texture_etc1');
+
+ if (extension !== null) {
+ return extension.COMPRESSED_RGB_ETC1_WEBGL;
+ } else {
+ return null;
+ }
+ } // ETC2
+
+
+ if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
+ extension = extensions.get('WEBGL_compressed_texture_etc');
+
+ if (extension !== null) {
+ if (p === RGB_ETC2_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
+ if (p === RGBA_ETC2_EAC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
+ } else {
+ return null;
+ }
+ } // ASTC
+
+
+ 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 encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
+ if (p === RGBA_ASTC_5x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
+ if (p === RGBA_ASTC_5x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
+ if (p === RGBA_ASTC_6x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
+ if (p === RGBA_ASTC_6x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
+ if (p === RGBA_ASTC_8x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
+ if (p === RGBA_ASTC_8x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
+ if (p === RGBA_ASTC_8x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
+ if (p === RGBA_ASTC_10x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
+ if (p === RGBA_ASTC_10x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
+ if (p === RGBA_ASTC_10x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
+ if (p === RGBA_ASTC_10x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
+ if (p === RGBA_ASTC_12x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
+ if (p === RGBA_ASTC_12x12_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
+ } else {
+ return null;
+ }
+ } // BPTC
+
+
+ if (p === RGBA_BPTC_Format) {
+ extension = extensions.get('EXT_texture_compression_bptc');
+
+ if (extension !== null) {
+ if (p === RGBA_BPTC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
+ } else {
+ return null;
+ }
+ } //
+
+
+ if (p === UnsignedInt248Type) {
+ if (isWebGL2) return gl.UNSIGNED_INT_24_8;
+ extension = extensions.get('WEBGL_depth_texture');
+
+ if (extension !== null) {
+ return extension.UNSIGNED_INT_24_8_WEBGL;
+ } else {
+ return null;
+ }
+ }
+ }
+
+ return {
+ convert: convert
+ };
+}
+
+class ArrayCamera extends PerspectiveCamera {
+ constructor(array = []) {
+ super();
+ this.cameras = array;
+ }
+
+}
+
+ArrayCamera.prototype.isArrayCamera = true;
+
+class Group extends Object3D {
+ constructor() {
+ super();
+ this.type = 'Group';
+ }
+
+}
+
+Group.prototype.isGroup = true;
+
+const _moveEvent = {
+ type: 'move'
+};
+
+class WebXRController {
+ constructor() {
+ this._targetRay = null;
+ this._grip = null;
+ this._hand = null;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ 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();
+ }
+
+ return this._grip;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ 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 (targetRay !== null) {
+ inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
+
+ if (inputPose !== null) {
+ targetRay.matrix.fromArray(inputPose.transform.matrix);
+ targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
+
+ 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 (hand && inputSource.hand) {
+ handPose = true;
+
+ for (const inputjoint of inputSource.hand.values()) {
+ // Update the joints groups with the XRJoint poses
+ const jointPose = frame.getJointPose(inputjoint, referenceSpace);
+
+ if (hand.joints[inputjoint.jointName] === undefined) {
+ // The transform of this joint will be updated with the joint pose on each frame
+ const joint = new Group();
+ joint.matrixAutoUpdate = false;
+ joint.visible = false;
+ hand.joints[inputjoint.jointName] = joint; // ??
+
+ hand.add(joint);
+ }
+
+ const joint = hand.joints[inputjoint.jointName];
+
+ if (jointPose !== null) {
+ joint.matrix.fromArray(jointPose.transform.matrix);
+ joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
+ joint.jointRadius = jointPose.radius;
+ }
+
+ joint.visible = jointPose !== null;
+ } // Custom events
+ // Check pinchz
+
+
+ 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 = 0.005;
+
+ 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);
+
+ 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 (targetRay !== null) {
+ targetRay.visible = inputPose !== null;
+ }
+
+ if (grip !== null) {
+ grip.visible = gripPose !== null;
+ }
+
+ if (hand !== null) {
+ hand.visible = handPose !== null;
+ }
+
+ return this;
+ }
+
+}
+
+class DepthTexture extends Texture {
+ constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
+ format = format !== undefined ? format : DepthFormat;
+
+ if (format !== DepthFormat && format !== DepthStencilFormat) {
+ throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
+ }
+
+ if (type === undefined && format === DepthFormat) type = UnsignedShortType;
+ if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
+ super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
+ this.image = {
+ width: width,
+ height: height
+ };
+ this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
+ this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
+ this.flipY = false;
+ this.generateMipmaps = false;
+ }
+
+}
+
+DepthTexture.prototype.isDepthTexture = true;
+
+class WebXRManager extends EventDispatcher {
+ constructor(renderer, gl) {
+ super();
+ const scope = this;
+ let session = null;
+ let framebufferScaleFactor = 1.0;
+ let referenceSpace = null;
+ let referenceSpaceType = 'local-floor';
+ const hasMultisampledRenderToTexture = renderer.extensions.has('WEBGL_multisampled_render_to_texture');
+ let pose = null;
+ let glBinding = null;
+ let glProjLayer = null;
+ let glBaseLayer = null;
+ let isMultisample = false;
+ let xrFrame = null;
+ const attributes = gl.getContextAttributes();
+ let initialRenderTarget = null;
+ let newRenderTarget = null;
+ const controllers = [];
+ const inputSourcesMap = new Map(); //
+
+ const cameraL = new PerspectiveCamera();
+ cameraL.layers.enable(1);
+ cameraL.viewport = new Vector4();
+ const cameraR = new PerspectiveCamera();
+ cameraR.layers.enable(2);
+ cameraR.viewport = new Vector4();
+ const cameras = [cameraL, cameraR];
+ const cameraVR = new ArrayCamera();
+ cameraVR.layers.enable(1);
+ cameraVR.layers.enable(2);
+ 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 === undefined) {
+ controller = new WebXRController();
+ controllers[index] = controller;
+ }
+
+ return controller.getTargetRaySpace();
+ };
+
+ this.getControllerGrip = function (index) {
+ let controller = controllers[index];
+
+ if (controller === undefined) {
+ controller = new WebXRController();
+ controllers[index] = controller;
+ }
+
+ return controller.getGripSpace();
+ };
+
+ this.getHand = function (index) {
+ let controller = controllers[index];
+
+ if (controller === undefined) {
+ controller = new WebXRController();
+ controllers[index] = controller;
+ }
+
+ return controller.getHandSpace();
+ }; //
+
+
+ function onSessionEvent(event) {
+ const controller = inputSourcesMap.get(event.inputSource);
+
+ if (controller) {
+ controller.dispatchEvent({
+ type: event.type,
+ data: event.inputSource
+ });
+ }
+ }
+
+ function onSessionEnd() {
+ inputSourcesMap.forEach(function (controller, inputSource) {
+ controller.disconnect(inputSource);
+ });
+ inputSourcesMap.clear();
+ _currentDepthNear = null;
+ _currentDepthFar = null; // restore framebuffer/rendering state
+
+ renderer.setRenderTarget(initialRenderTarget);
+ glBaseLayer = null;
+ glProjLayer = null;
+ glBinding = null;
+ session = null;
+ newRenderTarget = null; //
+
+ animation.stop();
+ scope.isPresenting = false;
+ scope.dispatchEvent({
+ type: 'sessionend'
+ });
+ }
+
+ this.setFramebufferScaleFactor = function (value) {
+ framebufferScaleFactor = value;
+
+ if (scope.isPresenting === true) {
+ console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
+ }
+ };
+
+ this.setReferenceSpaceType = function (value) {
+ referenceSpaceType = value;
+
+ if (scope.isPresenting === true) {
+ console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
+ }
+ };
+
+ this.getReferenceSpace = function () {
+ return referenceSpace;
+ };
+
+ this.getBaseLayer = function () {
+ return glProjLayer !== null ? glProjLayer : glBaseLayer;
+ };
+
+ this.getBinding = function () {
+ 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();
+ }
+
+ if (session.renderState.layers === undefined || renderer.capabilities.isWebGL2 === false) {
+ const layerInit = {
+ antialias: session.renderState.layers === undefined ? attributes.antialias : true,
+ alpha: attributes.alpha,
+ depth: attributes.depth,
+ stencil: attributes.stencil,
+ framebufferScaleFactor: framebufferScaleFactor
+ };
+ glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
+ session.updateRenderState({
+ baseLayer: glBaseLayer
+ });
+ newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, {
+ format: RGBAFormat,
+ type: UnsignedByteType,
+ encoding: renderer.outputEncoding
+ });
+ } else {
+ isMultisample = attributes.antialias;
+ 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 : UnsignedShortType;
+ }
+
+ const projectionlayerInit = {
+ colorFormat: renderer.outputEncoding === sRGBEncoding ? gl.SRGB8_ALPHA8 : gl.RGBA8,
+ depthFormat: glDepthFormat,
+ scaleFactor: framebufferScaleFactor
+ };
+ glBinding = new XRWebGLBinding(session, gl);
+ glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
+ session.updateRenderState({
+ layers: [glProjLayer]
+ });
+
+ if (isMultisample) {
+ newRenderTarget = new WebGLMultisampleRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
+ format: RGBAFormat,
+ type: UnsignedByteType,
+ depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
+ stencilBuffer: attributes.stencil,
+ ignoreDepth: glProjLayer.ignoreDepthValues,
+ useRenderToTexture: hasMultisampledRenderToTexture,
+ encoding: renderer.outputEncoding
+ });
+ } else {
+ newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
+ format: RGBAFormat,
+ type: UnsignedByteType,
+ depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
+ stencilBuffer: attributes.stencil,
+ ignoreDepth: glProjLayer.ignoreDepthValues,
+ encoding: renderer.outputEncoding
+ });
+ }
+ }
+
+ newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
+ // Set foveation to maximum.
+
+ this.setFoveation(1.0);
+ referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
+ animation.setContext(session);
+ animation.start();
+ scope.isPresenting = true;
+ scope.dispatchEvent({
+ type: 'sessionstart'
+ });
+ }
+ };
+
+ function onInputSourcesChange(event) {
+ const inputSources = session.inputSources; // Assign inputSources to available controllers
+
+ for (let i = 0; i < controllers.length; i++) {
+ inputSourcesMap.set(inputSources[i], controllers[i]);
+ } // Notify disconnected
+
+
+ for (let i = 0; i < event.removed.length; i++) {
+ const inputSource = event.removed[i];
+ const controller = inputSourcesMap.get(inputSource);
+
+ if (controller) {
+ controller.dispatchEvent({
+ type: 'disconnected',
+ data: inputSource
+ });
+ inputSourcesMap.delete(inputSource);
+ }
+ } // Notify connected
+
+
+ for (let i = 0; i < event.added.length; i++) {
+ const inputSource = event.added[i];
+ const controller = inputSourcesMap.get(inputSource);
+
+ if (controller) {
+ controller.dispatchEvent({
+ type: 'connected',
+ data: inputSource
+ });
+ }
+ }
+ } //
+
+
+ const cameraLPos = new Vector3();
+ const cameraRPos = new Vector3();
+ /**
+ * Assumes 2 cameras that are parallel and share an X-axis, and that
+ * the cameras' projection and world matrices have already been set.
+ * And that near and far planes are identical for both cameras.
+ * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
+ */
+
+ function setProjectionFromUnion(camera, cameraL, cameraR) {
+ cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
+ cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
+ const ipd = cameraLPos.distanceTo(cameraRPos);
+ const projL = cameraL.projectionMatrix.elements;
+ const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
+ // most likely identical top and bottom frustum extents.
+ // Use the left camera for these values.
+
+ 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; // Calculate the new camera's position offset from the
+ // left camera. xOffset should be roughly half `ipd`.
+
+ const zOffset = ipd / (-leftFov + rightFov);
+ const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
+
+ cameraL.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(); // Find the union of the frustum values of the cameras and scale
+ // the values so that the near plane's position does not change in world space,
+ // although must now be relative to the new union camera.
+
+ 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);
+ }
+
+ 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;
+ cameraVR.near = cameraR.near = cameraL.near = camera.near;
+ cameraVR.far = cameraR.far = cameraL.far = camera.far;
+
+ if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
+ // Note that the new renderState won't apply until the next frame. See #18320
+ session.updateRenderState({
+ depthNear: cameraVR.near,
+ depthFar: cameraVR.far
+ });
+ _currentDepthNear = cameraVR.near;
+ _currentDepthFar = cameraVR.far;
+ }
+
+ const parent = camera.parent;
+ const cameras = cameraVR.cameras;
+ updateCamera(cameraVR, parent);
+
+ for (let i = 0; i < cameras.length; i++) {
+ updateCamera(cameras[i], parent);
+ }
+
+ cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
+
+ camera.position.copy(cameraVR.position);
+ camera.quaternion.copy(cameraVR.quaternion);
+ camera.scale.copy(cameraVR.scale);
+ camera.matrix.copy(cameraVR.matrix);
+ camera.matrixWorld.copy(cameraVR.matrixWorld);
+ const children = camera.children;
+
+ for (let i = 0, l = children.length; i < l; i++) {
+ children[i].updateMatrixWorld(true);
+ } // update projection matrix for proper view frustum culling
+
+
+ if (cameras.length === 2) {
+ setProjectionFromUnion(cameraVR, cameraL, cameraR);
+ } else {
+ // assume single camera setup (AR)
+ cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
+ }
+ };
+
+ this.getCamera = function () {
+ return cameraVR;
+ };
+
+ this.getFoveation = function () {
+ if (glProjLayer !== null) {
+ return glProjLayer.fixedFoveation;
+ }
+
+ if (glBaseLayer !== null) {
+ return glBaseLayer.fixedFoveation;
+ }
+
+ return undefined;
+ };
+
+ this.setFoveation = function (foveation) {
+ // 0 = no foveation = full resolution
+ // 1 = maximum foveation = the edges render at lower resolution
+ if (glProjLayer !== null) {
+ glProjLayer.fixedFoveation = foveation;
+ }
+
+ if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
+ glBaseLayer.fixedFoveation = foveation;
+ }
+ }; // Animation Loop
+
+
+ let onAnimationFrameCallback = null;
+
+ function onAnimationFrame(time, frame) {
+ pose = frame.getViewerPose(referenceSpace);
+ xrFrame = frame;
+
+ if (pose !== null) {
+ const views = pose.views;
+
+ if (glBaseLayer !== null) {
+ renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer);
+ renderer.setRenderTarget(newRenderTarget);
+ }
+
+ let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
+
+ if (views.length !== cameraVR.cameras.length) {
+ cameraVR.cameras.length = 0;
+ cameraVRNeedsUpdate = 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; // For side-by-side projection, we only produce a single texture for both eyes.
+
+ if (i === 0) {
+ renderer.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture);
+ renderer.setRenderTarget(newRenderTarget);
+ }
+ }
+
+ const camera = cameras[i];
+ camera.matrix.fromArray(view.transform.matrix);
+ camera.projectionMatrix.fromArray(view.projectionMatrix);
+ camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
+
+ if (i === 0) {
+ cameraVR.matrix.copy(camera.matrix);
+ }
+
+ if (cameraVRNeedsUpdate === true) {
+ cameraVR.cameras.push(camera);
+ }
+ }
+ } //
+
+
+ const inputSources = session.inputSources;
+
+ for (let i = 0; i < controllers.length; i++) {
+ const controller = controllers[i];
+ const inputSource = inputSources[i];
+ controller.update(inputSource, frame, referenceSpace);
+ }
+
+ if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
+ xrFrame = null;
+ }
+
+ const animation = new WebGLAnimation();
+ animation.setAnimationLoop(onAnimationFrame);
+
+ this.setAnimationLoop = function (callback) {
+ onAnimationFrameCallback = callback;
+ };
+
+ this.dispose = function () {};
+ }
+
+}
+
+function WebGLMaterials(properties) {
+ function refreshFogUniforms(uniforms, fog) {
+ uniforms.fogColor.value.copy(fog.color);
+
+ 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.isMeshBasicMaterial) {
+ refreshUniformsCommon(uniforms, material);
+ } else if (material.isMeshLambertMaterial) {
+ refreshUniformsCommon(uniforms, material);
+ refreshUniformsLambert(uniforms, material);
+ } else if (material.isMeshToonMaterial) {
+ refreshUniformsCommon(uniforms, material);
+ refreshUniformsToon(uniforms, material);
+ } else if (material.isMeshPhongMaterial) {
+ refreshUniformsCommon(uniforms, material);
+ refreshUniformsPhong(uniforms, material);
+ } else if (material.isMeshStandardMaterial) {
+ refreshUniformsCommon(uniforms, material);
+
+ if (material.isMeshPhysicalMaterial) {
+ refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
+ } else {
+ refreshUniformsStandard(uniforms, material);
+ }
+ } else if (material.isMeshMatcapMaterial) {
+ refreshUniformsCommon(uniforms, material);
+ refreshUniformsMatcap(uniforms, material);
+ } else if (material.isMeshDepthMaterial) {
+ refreshUniformsCommon(uniforms, material);
+ refreshUniformsDepth(uniforms, material);
+ } else if (material.isMeshDistanceMaterial) {
+ refreshUniformsCommon(uniforms, material);
+ refreshUniformsDistance(uniforms, material);
+ } else if (material.isMeshNormalMaterial) {
+ refreshUniformsCommon(uniforms, material);
+ refreshUniformsNormal(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; // #15581
+ }
+ }
+
+ 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;
+ }
+
+ if (material.alphaMap) {
+ uniforms.alphaMap.value = material.alphaMap;
+ }
+
+ if (material.specularMap) {
+ uniforms.specularMap.value = material.specularMap;
+ }
+
+ if (material.alphaTest > 0) {
+ uniforms.alphaTest.value = material.alphaTest;
+ }
+
+ const envMap = properties.get(material).envMap;
+
+ if (envMap) {
+ uniforms.envMap.value = envMap;
+ uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
+ 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;
+ }
+
+ if (material.aoMap) {
+ uniforms.aoMap.value = material.aoMap;
+ uniforms.aoMapIntensity.value = material.aoMapIntensity;
+ } // uv repeat and offset setting priorities
+ // 1. color map
+ // 2. specular map
+ // 3. displacementMap map
+ // 4. normal map
+ // 5. bump map
+ // 6. roughnessMap map
+ // 7. metalnessMap map
+ // 8. alphaMap map
+ // 9. emissiveMap map
+ // 10. clearcoat map
+ // 11. clearcoat normal map
+ // 12. clearcoat roughnessMap map
+ // 13. specular intensity map
+ // 14. specular tint map
+ // 15. transmission map
+ // 16. thickness map
+
+
+ let uvScaleMap;
+
+ if (material.map) {
+ uvScaleMap = material.map;
+ } else if (material.specularMap) {
+ uvScaleMap = material.specularMap;
+ } else if (material.displacementMap) {
+ uvScaleMap = material.displacementMap;
+ } else if (material.normalMap) {
+ uvScaleMap = material.normalMap;
+ } else if (material.bumpMap) {
+ uvScaleMap = material.bumpMap;
+ } else if (material.roughnessMap) {
+ uvScaleMap = material.roughnessMap;
+ } else if (material.metalnessMap) {
+ uvScaleMap = material.metalnessMap;
+ } else if (material.alphaMap) {
+ uvScaleMap = material.alphaMap;
+ } else if (material.emissiveMap) {
+ uvScaleMap = material.emissiveMap;
+ } else if (material.clearcoatMap) {
+ uvScaleMap = material.clearcoatMap;
+ } else if (material.clearcoatNormalMap) {
+ uvScaleMap = material.clearcoatNormalMap;
+ } else if (material.clearcoatRoughnessMap) {
+ uvScaleMap = material.clearcoatRoughnessMap;
+ } else if (material.specularIntensityMap) {
+ uvScaleMap = material.specularIntensityMap;
+ } else if (material.specularColorMap) {
+ uvScaleMap = material.specularColorMap;
+ } else if (material.transmissionMap) {
+ uvScaleMap = material.transmissionMap;
+ } else if (material.thicknessMap) {
+ uvScaleMap = material.thicknessMap;
+ } else if (material.sheenColorMap) {
+ uvScaleMap = material.sheenColorMap;
+ } else if (material.sheenRoughnessMap) {
+ uvScaleMap = material.sheenRoughnessMap;
+ }
+
+ if (uvScaleMap !== undefined) {
+ // backwards compatibility
+ if (uvScaleMap.isWebGLRenderTarget) {
+ uvScaleMap = uvScaleMap.texture;
+ }
+
+ if (uvScaleMap.matrixAutoUpdate === true) {
+ uvScaleMap.updateMatrix();
+ }
+
+ uniforms.uvTransform.value.copy(uvScaleMap.matrix);
+ } // uv repeat and offset setting priorities for uv2
+ // 1. ao map
+ // 2. light map
+
+
+ let uv2ScaleMap;
+
+ if (material.aoMap) {
+ uv2ScaleMap = material.aoMap;
+ } else if (material.lightMap) {
+ uv2ScaleMap = material.lightMap;
+ }
+
+ if (uv2ScaleMap !== undefined) {
+ // backwards compatibility
+ if (uv2ScaleMap.isWebGLRenderTarget) {
+ uv2ScaleMap = uv2ScaleMap.texture;
+ }
+
+ if (uv2ScaleMap.matrixAutoUpdate === true) {
+ uv2ScaleMap.updateMatrix();
+ }
+
+ uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
+ }
+ }
+
+ function refreshUniformsLine(uniforms, material) {
+ uniforms.diffuse.value.copy(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 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;
+ }
+
+ if (material.alphaMap) {
+ uniforms.alphaMap.value = material.alphaMap;
+ }
+
+ if (material.alphaTest > 0) {
+ uniforms.alphaTest.value = material.alphaTest;
+ } // uv repeat and offset setting priorities
+ // 1. color map
+ // 2. alpha map
+
+
+ let uvScaleMap;
+
+ if (material.map) {
+ uvScaleMap = material.map;
+ } else if (material.alphaMap) {
+ uvScaleMap = material.alphaMap;
+ }
+
+ if (uvScaleMap !== undefined) {
+ if (uvScaleMap.matrixAutoUpdate === true) {
+ uvScaleMap.updateMatrix();
+ }
+
+ uniforms.uvTransform.value.copy(uvScaleMap.matrix);
+ }
+ }
+
+ 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;
+ }
+
+ if (material.alphaMap) {
+ uniforms.alphaMap.value = material.alphaMap;
+ }
+
+ if (material.alphaTest > 0) {
+ uniforms.alphaTest.value = material.alphaTest;
+ } // uv repeat and offset setting priorities
+ // 1. color map
+ // 2. alpha map
+
+
+ let uvScaleMap;
+
+ if (material.map) {
+ uvScaleMap = material.map;
+ } else if (material.alphaMap) {
+ uvScaleMap = material.alphaMap;
+ }
+
+ if (uvScaleMap !== undefined) {
+ if (uvScaleMap.matrixAutoUpdate === true) {
+ uvScaleMap.updateMatrix();
+ }
+
+ uniforms.uvTransform.value.copy(uvScaleMap.matrix);
+ }
+ }
+
+ function refreshUniformsLambert(uniforms, material) {
+ if (material.emissiveMap) {
+ uniforms.emissiveMap.value = material.emissiveMap;
+ }
+ }
+
+ function refreshUniformsPhong(uniforms, material) {
+ uniforms.specular.value.copy(material.specular);
+ uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
+
+ if (material.emissiveMap) {
+ uniforms.emissiveMap.value = material.emissiveMap;
+ }
+
+ if (material.bumpMap) {
+ uniforms.bumpMap.value = material.bumpMap;
+ uniforms.bumpScale.value = material.bumpScale;
+ if (material.side === BackSide) uniforms.bumpScale.value *= -1;
+ }
+
+ if (material.normalMap) {
+ uniforms.normalMap.value = material.normalMap;
+ uniforms.normalScale.value.copy(material.normalScale);
+ if (material.side === BackSide) uniforms.normalScale.value.negate();
+ }
+
+ if (material.displacementMap) {
+ uniforms.displacementMap.value = material.displacementMap;
+ uniforms.displacementScale.value = material.displacementScale;
+ uniforms.displacementBias.value = material.displacementBias;
+ }
+ }
+
+ function refreshUniformsToon(uniforms, material) {
+ if (material.gradientMap) {
+ uniforms.gradientMap.value = material.gradientMap;
+ }
+
+ if (material.emissiveMap) {
+ uniforms.emissiveMap.value = material.emissiveMap;
+ }
+
+ if (material.bumpMap) {
+ uniforms.bumpMap.value = material.bumpMap;
+ uniforms.bumpScale.value = material.bumpScale;
+ if (material.side === BackSide) uniforms.bumpScale.value *= -1;
+ }
+
+ if (material.normalMap) {
+ uniforms.normalMap.value = material.normalMap;
+ uniforms.normalScale.value.copy(material.normalScale);
+ if (material.side === BackSide) uniforms.normalScale.value.negate();
+ }
+
+ if (material.displacementMap) {
+ uniforms.displacementMap.value = material.displacementMap;
+ uniforms.displacementScale.value = material.displacementScale;
+ uniforms.displacementBias.value = material.displacementBias;
+ }
+ }
+
+ function refreshUniformsStandard(uniforms, material) {
+ uniforms.roughness.value = material.roughness;
+ uniforms.metalness.value = material.metalness;
+
+ if (material.roughnessMap) {
+ uniforms.roughnessMap.value = material.roughnessMap;
+ }
+
+ if (material.metalnessMap) {
+ uniforms.metalnessMap.value = material.metalnessMap;
+ }
+
+ if (material.emissiveMap) {
+ uniforms.emissiveMap.value = material.emissiveMap;
+ }
+
+ if (material.bumpMap) {
+ uniforms.bumpMap.value = material.bumpMap;
+ uniforms.bumpScale.value = material.bumpScale;
+ if (material.side === BackSide) uniforms.bumpScale.value *= -1;
+ }
+
+ if (material.normalMap) {
+ uniforms.normalMap.value = material.normalMap;
+ uniforms.normalScale.value.copy(material.normalScale);
+ if (material.side === BackSide) uniforms.normalScale.value.negate();
+ }
+
+ if (material.displacementMap) {
+ uniforms.displacementMap.value = material.displacementMap;
+ uniforms.displacementScale.value = material.displacementScale;
+ uniforms.displacementBias.value = material.displacementBias;
+ }
+
+ const envMap = properties.get(material).envMap;
+
+ if (envMap) {
+ //uniforms.envMap.value = material.envMap; // part of uniforms common
+ uniforms.envMapIntensity.value = material.envMapIntensity;
+ }
+ }
+
+ function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
+ refreshUniformsStandard(uniforms, material);
+ uniforms.ior.value = material.ior; // also part of uniforms common
+
+ 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;
+ }
+
+ if (material.sheenRoughnessMap) {
+ uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
+ }
+ }
+
+ if (material.clearcoat > 0) {
+ uniforms.clearcoat.value = material.clearcoat;
+ uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
+
+ if (material.clearcoatMap) {
+ uniforms.clearcoatMap.value = material.clearcoatMap;
+ }
+
+ if (material.clearcoatRoughnessMap) {
+ uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
+ }
+
+ if (material.clearcoatNormalMap) {
+ uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
+ uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
+
+ if (material.side === BackSide) {
+ uniforms.clearcoatNormalScale.value.negate();
+ }
+ }
+ }
+
+ 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;
+ }
+
+ uniforms.thickness.value = material.thickness;
+
+ if (material.thicknessMap) {
+ uniforms.thicknessMap.value = material.thicknessMap;
+ }
+
+ uniforms.attenuationDistance.value = material.attenuationDistance;
+ uniforms.attenuationColor.value.copy(material.attenuationColor);
+ }
+
+ uniforms.specularIntensity.value = material.specularIntensity;
+ uniforms.specularColor.value.copy(material.specularColor);
+
+ if (material.specularIntensityMap) {
+ uniforms.specularIntensityMap.value = material.specularIntensityMap;
+ }
+
+ if (material.specularColorMap) {
+ uniforms.specularColorMap.value = material.specularColorMap;
+ }
+ }
+
+ function refreshUniformsMatcap(uniforms, material) {
+ if (material.matcap) {
+ uniforms.matcap.value = material.matcap;
+ }
+
+ if (material.bumpMap) {
+ uniforms.bumpMap.value = material.bumpMap;
+ uniforms.bumpScale.value = material.bumpScale;
+ if (material.side === BackSide) uniforms.bumpScale.value *= -1;
+ }
+
+ if (material.normalMap) {
+ uniforms.normalMap.value = material.normalMap;
+ uniforms.normalScale.value.copy(material.normalScale);
+ if (material.side === BackSide) uniforms.normalScale.value.negate();
+ }
+
+ if (material.displacementMap) {
+ uniforms.displacementMap.value = material.displacementMap;
+ uniforms.displacementScale.value = material.displacementScale;
+ uniforms.displacementBias.value = material.displacementBias;
+ }
+ }
+
+ function refreshUniformsDepth(uniforms, material) {
+ if (material.displacementMap) {
+ uniforms.displacementMap.value = material.displacementMap;
+ uniforms.displacementScale.value = material.displacementScale;
+ uniforms.displacementBias.value = material.displacementBias;
+ }
+ }
+
+ function refreshUniformsDistance(uniforms, material) {
+ if (material.displacementMap) {
+ uniforms.displacementMap.value = material.displacementMap;
+ uniforms.displacementScale.value = material.displacementScale;
+ uniforms.displacementBias.value = material.displacementBias;
+ }
+
+ uniforms.referencePosition.value.copy(material.referencePosition);
+ uniforms.nearDistance.value = material.nearDistance;
+ uniforms.farDistance.value = material.farDistance;
+ }
+
+ function refreshUniformsNormal(uniforms, material) {
+ if (material.bumpMap) {
+ uniforms.bumpMap.value = material.bumpMap;
+ uniforms.bumpScale.value = material.bumpScale;
+ if (material.side === BackSide) uniforms.bumpScale.value *= -1;
+ }
+
+ if (material.normalMap) {
+ uniforms.normalMap.value = material.normalMap;
+ uniforms.normalScale.value.copy(material.normalScale);
+ if (material.side === BackSide) uniforms.normalScale.value.negate();
+ }
+
+ if (material.displacementMap) {
+ uniforms.displacementMap.value = material.displacementMap;
+ uniforms.displacementScale.value = material.displacementScale;
+ uniforms.displacementBias.value = material.displacementBias;
+ }
+ }
+
+ return {
+ refreshFogUniforms: refreshFogUniforms,
+ refreshMaterialUniforms: refreshMaterialUniforms
+ };
+}
+
+function createCanvasElement() {
+ const canvas = createElementNS('canvas');
+ canvas.style.display = 'block';
+ return canvas;
+}
+
+function WebGLRenderer(parameters = {}) {
+ const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
+ _context = parameters.context !== undefined ? parameters.context : null,
+ _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
+ _depth = parameters.depth !== undefined ? parameters.depth : true,
+ _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
+ _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
+ _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
+ _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
+ _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
+ _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
+
+ let currentRenderList = null;
+ let currentRenderState = null; // render() can be called from within a callback triggered by another render.
+ // We track this so that the nested render call gets its list and state isolated from the parent render call.
+
+ const renderListStack = [];
+ const renderStateStack = []; // public properties
+
+ this.domElement = _canvas; // Debug configuration container
+
+ this.debug = {
+ /**
+ * Enables error checking and reporting when shader programs are being compiled
+ * @type {boolean}
+ */
+ checkShaderErrors: true
+ }; // clearing
+
+ this.autoClear = true;
+ this.autoClearColor = true;
+ this.autoClearDepth = true;
+ this.autoClearStencil = true; // scene graph
+
+ this.sortObjects = true; // user-defined clipping
+
+ this.clippingPlanes = [];
+ this.localClippingEnabled = false; // physically based shading
+
+ this.outputEncoding = LinearEncoding; // physical lights
+
+ this.physicallyCorrectLights = false; // tone mapping
+
+ this.toneMapping = NoToneMapping;
+ this.toneMappingExposure = 1.0; // internal properties
+
+ const _this = this;
+
+ let _isContextLost = false; // internal state cache
+
+ 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; //
+
+ 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; // frustum
+
+ const _frustum = new Frustum(); // clipping
+
+
+ let _clippingEnabled = false;
+ let _localClippingEnabled = false; // transmission
+
+ let _transmissionRenderTarget = null; // camera matrices cache
+
+ const _projScreenMatrix = new Matrix4();
+
+ const _vector3 = new Vector3();
+
+ const _emptyScene = {
+ background: null,
+ fog: null,
+ environment: null,
+ overrideMaterial: null,
+ isScene: true
+ };
+
+ function getTargetPixelRatio() {
+ return _currentRenderTarget === null ? _pixelRatio : 1;
+ } // initialize
+
+
+ let _gl = _context;
+
+ function getContext(contextNames, contextAttributes) {
+ for (let i = 0; i < contextNames.length; i++) {
+ const contextName = contextNames[i];
+
+ const context = _canvas.getContext(contextName, contextAttributes);
+
+ if (context !== null) return context;
+ }
+
+ return null;
+ }
+
+ try {
+ const contextAttributes = {
+ alpha: true,
+ depth: _depth,
+ stencil: _stencil,
+ antialias: _antialias,
+ premultipliedAlpha: _premultipliedAlpha,
+ preserveDrawingBuffer: _preserveDrawingBuffer,
+ powerPreference: _powerPreference,
+ failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
+ }; // OffscreenCanvas does not have setAttribute, see #22811
+
+ if ('setAttribute' in _canvas) _canvas.setAttribute('data-engine', `three.js r${REVISION}`); // event listeners must be registered before WebGL context is created, see #12753
+
+ _canvas.addEventListener('webglcontextlost', onContextLost, false);
+
+ _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
+
+ if (_gl === null) {
+ const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
+
+ if (_this.isWebGL1Renderer === true) {
+ contextNames.shift();
+ }
+
+ _gl = getContext(contextNames, contextAttributes);
+
+ if (_gl === null) {
+ if (getContext(contextNames)) {
+ throw new Error('Error creating WebGL context with your selected attributes.');
+ } else {
+ throw new Error('Error creating WebGL context.');
+ }
+ }
+ } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
+
+
+ if (_gl.getShaderPrecisionFormat === undefined) {
+ _gl.getShaderPrecisionFormat = function () {
+ return {
+ 'rangeMin': 1,
+ 'rangeMax': 1,
+ 'precision': 1
+ };
+ };
+ }
+ } catch (error) {
+ console.error('THREE.WebGLRenderer: ' + error.message);
+ throw error;
+ }
+
+ let extensions, capabilities, state, info;
+ let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
+ let programCache, materials, renderLists, renderStates, clipping, shadowMap;
+ let background, morphtargets, bufferRenderer, indexedBufferRenderer;
+ let utils, bindingStates;
+
+ function initGLContext() {
+ extensions = new WebGLExtensions(_gl);
+ capabilities = new WebGLCapabilities(_gl, extensions, parameters);
+ extensions.init(capabilities);
+ utils = new WebGLUtils(_gl, extensions, capabilities);
+ state = new WebGLState(_gl, extensions, capabilities);
+ info = new WebGLInfo(_gl);
+ properties = new WebGLProperties();
+ textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
+ cubemaps = new WebGLCubeMaps(_this);
+ cubeuvmaps = new WebGLCubeUVMaps(_this);
+ attributes = new WebGLAttributes(_gl, capabilities);
+ bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
+ geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
+ objects = new WebGLObjects(_gl, geometries, attributes, info);
+ morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
+ clipping = new WebGLClipping(properties);
+ programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
+ materials = new WebGLMaterials(properties);
+ renderLists = new WebGLRenderLists();
+ renderStates = new WebGLRenderStates(extensions, capabilities);
+ background = new WebGLBackground(_this, cubemaps, state, objects, _alpha, _premultipliedAlpha);
+ shadowMap = new WebGLShadowMap(_this, objects, capabilities);
+ bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
+ indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
+ info.programs = programCache.programs;
+ _this.capabilities = capabilities;
+ _this.extensions = extensions;
+ _this.properties = properties;
+ _this.renderLists = renderLists;
+ _this.shadowMap = shadowMap;
+ _this.state = state;
+ _this.info = info;
+ }
+
+ initGLContext(); // xr
+
+ const xr = new WebXRManager(_this, _gl);
+ this.xr = xr; // API
+
+ 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 === undefined) return;
+ _pixelRatio = value;
+ this.setSize(_width, _height, false);
+ };
+
+ this.getSize = function (target) {
+ return target.set(_width, _height);
+ };
+
+ this.setSize = function (width, height, updateStyle) {
+ if (xr.isPresenting) {
+ console.warn('THREE.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 !== false) {
+ _canvas.style.width = width + 'px';
+ _canvas.style.height = height + 'px';
+ }
+
+ 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.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).floor());
+ };
+
+ 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).floor());
+ };
+
+ 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;
+ }; // Clearing
+
+
+ this.getClearColor = function (target) {
+ return target.copy(background.getClearColor());
+ };
+
+ this.setClearColor = function () {
+ background.setClearColor.apply(background, arguments);
+ };
+
+ this.getClearAlpha = function () {
+ return background.getClearAlpha();
+ };
+
+ this.setClearAlpha = function () {
+ background.setClearAlpha.apply(background, arguments);
+ };
+
+ this.clear = function (color, depth, stencil) {
+ let 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 () {
+ this.clear(true, false, false);
+ };
+
+ this.clearDepth = function () {
+ this.clear(false, true, false);
+ };
+
+ this.clearStencil = function () {
+ this.clear(false, false, true);
+ }; //
+
+
+ this.dispose = function () {
+ _canvas.removeEventListener('webglcontextlost', onContextLost, false);
+
+ _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
+
+ renderLists.dispose();
+ renderStates.dispose();
+ properties.dispose();
+ cubemaps.dispose();
+ cubeuvmaps.dispose();
+ objects.dispose();
+ bindingStates.dispose();
+ programCache.dispose();
+ xr.dispose();
+ xr.removeEventListener('sessionstart', onXRSessionStart);
+ xr.removeEventListener('sessionend', onXRSessionEnd);
+
+ if (_transmissionRenderTarget) {
+ _transmissionRenderTarget.dispose();
+
+ _transmissionRenderTarget = null;
+ }
+
+ animation.stop();
+ }; // Events
+
+
+ function onContextLost(event) {
+ event.preventDefault();
+ console.log('THREE.WebGLRenderer: Context Lost.');
+ _isContextLost = true;
+ }
+
+ function
+ /* event */
+ onContextRestore() {
+ console.log('THREE.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 onMaterialDispose(event) {
+ const material = event.target;
+ material.removeEventListener('dispose', onMaterialDispose);
+ deallocateMaterial(material);
+ } // Buffer deallocation
+
+
+ function deallocateMaterial(material) {
+ releaseMaterialProgramReferences(material);
+ properties.remove(material);
+ }
+
+ function releaseMaterialProgramReferences(material) {
+ const programs = properties.get(material).programs;
+
+ if (programs !== undefined) {
+ programs.forEach(function (program) {
+ programCache.releaseProgram(program);
+ });
+
+ if (material.isShaderMaterial) {
+ programCache.releaseShaderCache(material);
+ }
+ }
+ } // Buffer rendering
+
+
+ this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
+ if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
+
+ const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
+ const program = setProgram(camera, scene, geometry, material, object);
+ state.setMaterial(material, frontFaceCW); //
+
+ let index = geometry.index;
+ const position = geometry.attributes.position; //
+
+ if (index === null) {
+ if (position === undefined || position.count === 0) return;
+ } else if (index.count === 0) {
+ return;
+ } //
+
+
+ let rangeFactor = 1;
+
+ if (material.wireframe === true) {
+ index = geometries.getWireframeAttribute(geometry);
+ rangeFactor = 2;
+ }
+
+ bindingStates.setup(object, material, program, geometry, index);
+ let attribute;
+ let renderer = bufferRenderer;
+
+ if (index !== null) {
+ attribute = attributes.get(index);
+ renderer = indexedBufferRenderer;
+ renderer.setIndex(attribute);
+ } //
+
+
+ const dataCount = index !== null ? index.count : position.count;
+ const rangeStart = geometry.drawRange.start * rangeFactor;
+ const rangeCount = geometry.drawRange.count * rangeFactor;
+ const groupStart = group !== null ? group.start * rangeFactor : 0;
+ const groupCount = group !== null ? group.count * rangeFactor : Infinity;
+ const drawStart = Math.max(rangeStart, groupStart);
+ const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
+ const drawCount = Math.max(0, drawEnd - drawStart + 1);
+ if (drawCount === 0) return; //
+
+ 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 === undefined) lineWidth = 1; // Not using Line*Material
+
+ 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.isInstancedMesh) {
+ renderer.renderInstances(drawStart, drawCount, object.count);
+ } else if (geometry.isInstancedBufferGeometry) {
+ const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
+ renderer.renderInstances(drawStart, drawCount, instanceCount);
+ } else {
+ renderer.render(drawStart, drawCount);
+ }
+ }; // Compile
+
+
+ this.compile = function (scene, camera) {
+ currentRenderState = renderStates.get(scene);
+ currentRenderState.init();
+ renderStateStack.push(currentRenderState);
+ scene.traverseVisible(function (object) {
+ if (object.isLight && object.layers.test(camera.layers)) {
+ currentRenderState.pushLight(object);
+
+ if (object.castShadow) {
+ currentRenderState.pushShadow(object);
+ }
+ }
+ });
+ currentRenderState.setupLights(_this.physicallyCorrectLights);
+ scene.traverse(function (object) {
+ const material = object.material;
+
+ if (material) {
+ if (Array.isArray(material)) {
+ for (let i = 0; i < material.length; i++) {
+ const material2 = material[i];
+ getProgram(material2, scene, object);
+ }
+ } else {
+ getProgram(material, scene, object);
+ }
+ }
+ });
+ renderStateStack.pop();
+ currentRenderState = null;
+ }; // Animation Loop
+
+
+ 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 window !== 'undefined') animation.setContext(window);
+
+ this.setAnimationLoop = function (callback) {
+ onAnimationFrameCallback = callback;
+ xr.setAnimationLoop(callback);
+ callback === null ? animation.stop() : animation.start();
+ };
+
+ xr.addEventListener('sessionstart', onXRSessionStart);
+ xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
+
+ this.render = function (scene, camera) {
+ if (camera !== undefined && camera.isCamera !== true) {
+ console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
+ return;
+ }
+
+ if (_isContextLost === true) return; // update scene graph
+
+ if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
+
+ if (camera.parent === null) camera.updateMatrixWorld();
+
+ if (xr.enabled === true && xr.isPresenting === true) {
+ if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
+ camera = xr.getCamera(); // use XR camera for rendering
+ } //
+
+
+ if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
+ currentRenderState = renderStates.get(scene, renderStateStack.length);
+ currentRenderState.init();
+ renderStateStack.push(currentRenderState);
+
+ _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
+
+ _frustum.setFromProjectionMatrix(_projScreenMatrix);
+
+ _localClippingEnabled = this.localClippingEnabled;
+ _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
+ currentRenderList = renderLists.get(scene, renderListStack.length);
+ currentRenderList.init();
+ renderListStack.push(currentRenderList);
+ projectObject(scene, camera, 0, _this.sortObjects);
+ currentRenderList.finish();
+
+ if (_this.sortObjects === true) {
+ currentRenderList.sort(_opaqueSort, _transparentSort);
+ } //
+
+
+ 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(); //
+
+ background.render(currentRenderList, scene); // render scene
+
+ currentRenderState.setupLights(_this.physicallyCorrectLights);
+
+ if (camera.isArrayCamera) {
+ const cameras = camera.cameras;
+
+ for (let i = 0, l = cameras.length; i < l; i++) {
+ const camera2 = cameras[i];
+ renderScene(currentRenderList, scene, camera2, camera2.viewport);
+ }
+ } else {
+ renderScene(currentRenderList, scene, camera);
+ } //
+
+
+ if (_currentRenderTarget !== null) {
+ // resolve multisample renderbuffers to a single-sample texture if necessary
+ textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
+
+ textures.updateRenderTargetMipmap(_currentRenderTarget);
+ } //
+
+
+ if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
+
+ state.buffers.depth.setTest(true);
+ state.buffers.depth.setMask(true);
+ state.buffers.color.setMask(true);
+ state.setPolygonOffset(false); // _gl.finish();
+
+ bindingStates.resetDefaultState();
+ _currentMaterialId = -1;
+ _currentCamera = null;
+ renderStateStack.pop();
+
+ if (renderStateStack.length > 0) {
+ currentRenderState = renderStateStack[renderStateStack.length - 1];
+ } else {
+ currentRenderState = null;
+ }
+
+ renderListStack.pop();
+
+ if (renderListStack.length > 0) {
+ currentRenderList = renderListStack[renderListStack.length - 1];
+ } else {
+ currentRenderList = null;
+ }
+ };
+
+ 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.isLight) {
+ currentRenderState.pushLight(object);
+
+ if (object.castShadow) {
+ currentRenderState.pushShadow(object);
+ }
+ } else if (object.isSprite) {
+ if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
+ if (sortObjects) {
+ _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
+ }
+
+ const geometry = objects.update(object);
+ const material = object.material;
+
+ if (material.visible) {
+ currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
+ }
+ }
+ } else if (object.isMesh || object.isLine || object.isPoints) {
+ if (object.isSkinnedMesh) {
+ // update skeleton only once in a frame
+ if (object.skeleton.frame !== info.render.frame) {
+ object.skeleton.update();
+ object.skeleton.frame = info.render.frame;
+ }
+ }
+
+ if (!object.frustumCulled || _frustum.intersectsObject(object)) {
+ if (sortObjects) {
+ _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
+ }
+
+ const geometry = objects.update(object);
+ const material = object.material;
+
+ 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, _vector3.z, group);
+ }
+ }
+ } else if (material.visible) {
+ currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
+ }
+ }
+ }
+ }
+
+ const children = object.children;
+
+ for (let i = 0, l = children.length; i < l; i++) {
+ projectObject(children[i], camera, groupOrder, sortObjects);
+ }
+ }
+
+ function renderScene(currentRenderList, scene, camera, viewport) {
+ const opaqueObjects = currentRenderList.opaque;
+ const transmissiveObjects = currentRenderList.transmissive;
+ const transparentObjects = currentRenderList.transparent;
+ currentRenderState.setupLightsView(camera);
+ if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, 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);
+ }
+
+ function renderTransmissionPass(opaqueObjects, scene, camera) {
+ if (_transmissionRenderTarget === null) {
+ const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
+ const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
+ _transmissionRenderTarget = new renderTargetType(1024, 1024, {
+ generateMipmaps: true,
+ type: utils.convert(HalfFloatType) !== null ? HalfFloatType : UnsignedByteType,
+ minFilter: LinearMipmapLinearFilter,
+ magFilter: NearestFilter,
+ wrapS: ClampToEdgeWrapping,
+ wrapT: ClampToEdgeWrapping,
+ useRenderToTexture: extensions.has('WEBGL_multisampled_render_to_texture')
+ });
+ }
+
+ const currentRenderTarget = _this.getRenderTarget();
+
+ _this.setRenderTarget(_transmissionRenderTarget);
+
+ _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
+ // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
+
+
+ const currentToneMapping = _this.toneMapping;
+ _this.toneMapping = NoToneMapping;
+ renderObjects(opaqueObjects, scene, camera);
+ _this.toneMapping = currentToneMapping;
+ textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
+ textures.updateRenderTargetMipmap(_transmissionRenderTarget);
+
+ _this.setRenderTarget(currentRenderTarget);
+ }
+
+ 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 = renderItem.object;
+ const geometry = renderItem.geometry;
+ const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
+ const group = renderItem.group;
+
+ if (object.layers.test(camera.layers)) {
+ renderObject(object, scene, camera, geometry, material, group);
+ }
+ }
+ }
+
+ function renderObject(object, scene, camera, geometry, material, group) {
+ object.onBeforeRender(_this, scene, camera, geometry, material, group);
+ object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
+ object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
+ material.onBeforeRender(_this, scene, camera, geometry, object, group);
+
+ if (material.transparent === true && material.side === DoubleSide) {
+ material.side = BackSide;
+ material.needsUpdate = true;
+
+ _this.renderBufferDirect(camera, scene, geometry, material, object, group);
+
+ material.side = FrontSide;
+ material.needsUpdate = true;
+
+ _this.renderBufferDirect(camera, scene, geometry, material, object, group);
+
+ material.side = DoubleSide;
+ } else {
+ _this.renderBufferDirect(camera, scene, geometry, material, object, group);
+ }
+
+ object.onAfterRender(_this, scene, camera, geometry, material, group);
+ }
+
+ function getProgram(material, scene, object) {
+ if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
+
+ const materialProperties = properties.get(material);
+ const lights = currentRenderState.state.lights;
+ const shadowsArray = currentRenderState.state.shadowsArray;
+ const lightsStateVersion = lights.state.version;
+ const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
+ const programCacheKey = programCache.getProgramCacheKey(parameters);
+ let programs = materialProperties.programs; // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
+
+ materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
+ materialProperties.fog = scene.fog;
+ materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
+
+ if (programs === undefined) {
+ // new material
+ material.addEventListener('dispose', onMaterialDispose);
+ programs = new Map();
+ materialProperties.programs = programs;
+ }
+
+ let program = programs.get(programCacheKey);
+
+ if (program !== undefined) {
+ // early out if program and light state is identical
+ if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
+ updateCommonMaterialProperties(material, parameters);
+ return program;
+ }
+ } else {
+ parameters.uniforms = programCache.getUniforms(material);
+ material.onBuild(object, parameters, _this);
+ material.onBeforeCompile(parameters, _this);
+ program = programCache.acquireProgram(parameters, programCacheKey);
+ programs.set(programCacheKey, program);
+ materialProperties.uniforms = parameters.uniforms;
+ }
+
+ const uniforms = materialProperties.uniforms;
+
+ if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
+ uniforms.clippingPlanes = clipping.uniform;
+ }
+
+ updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
+
+ materialProperties.needsLights = materialNeedsLights(material);
+ materialProperties.lightsStateVersion = lightsStateVersion;
+
+ if (materialProperties.needsLights) {
+ // wire up the material to this renderer's lighting state
+ 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.directionalShadowMap.value = lights.state.directionalShadowMap;
+ uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
+ uniforms.spotShadowMap.value = lights.state.spotShadowMap;
+ uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
+ uniforms.pointShadowMap.value = lights.state.pointShadowMap;
+ uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
+ }
+
+ const progUniforms = program.getUniforms();
+ const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
+ materialProperties.currentProgram = program;
+ materialProperties.uniformsList = uniformsList;
+ return program;
+ }
+
+ function updateCommonMaterialProperties(material, parameters) {
+ const materialProperties = properties.get(material);
+ materialProperties.outputEncoding = parameters.outputEncoding;
+ materialProperties.instancing = parameters.instancing;
+ materialProperties.skinning = parameters.skinning;
+ materialProperties.morphTargets = parameters.morphTargets;
+ materialProperties.morphNormals = parameters.morphNormals;
+ materialProperties.morphTargetsCount = parameters.morphTargetsCount;
+ materialProperties.numClippingPlanes = parameters.numClippingPlanes;
+ materialProperties.numIntersection = parameters.numClipIntersection;
+ materialProperties.vertexAlphas = parameters.vertexAlphas;
+ materialProperties.vertexTangents = parameters.vertexTangents;
+ materialProperties.toneMapping = parameters.toneMapping;
+ }
+
+ function setProgram(camera, scene, geometry, material, object) {
+ if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
+
+ textures.resetTextureUnits();
+ const fog = scene.fog;
+ const environment = material.isMeshStandardMaterial ? scene.environment : null;
+ const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding;
+ const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
+ const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
+ const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent;
+ const morphTargets = !!geometry.morphAttributes.position;
+ const morphNormals = !!geometry.morphAttributes.normal;
+ const morphTargetsCount = !!geometry.morphAttributes.position ? geometry.morphAttributes.position.length : 0;
+ const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
+ 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; // we might want to call this function with some ClippingGroup
+ // object instead of the material, once it becomes feasible
+ // (#8465, #8379)
+
+ 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.outputEncoding !== encoding) {
+ 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 (materialProperties.envMap !== envMap) {
+ needsProgramChange = true;
+ } else if (material.fog && materialProperties.fog !== fog) {
+ needsProgramChange = true;
+ } else if (materialProperties.numClippingPlanes !== undefined && (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.toneMapping !== toneMapping) {
+ needsProgramChange = true;
+ } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) {
+ needsProgramChange = true;
+ }
+ } else {
+ needsProgramChange = true;
+ materialProperties.__version = material.version;
+ } //
+
+
+ let program = materialProperties.currentProgram;
+
+ if (needsProgramChange === true) {
+ program = getProgram(material, scene, object);
+ }
+
+ 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 (refreshProgram || _currentCamera !== camera) {
+ p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
+
+ if (capabilities.logarithmicDepthBuffer) {
+ p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
+ }
+
+ if (_currentCamera !== camera) {
+ _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
+ // now, in case this material supports lights - or later, when
+ // the next material that does gets activated:
+
+ refreshMaterial = true; // set to true on material change
+
+ refreshLights = true; // remains set until update done
+ } // load material specific uniforms
+ // (shader material also gets them for the sake of genericity)
+
+
+ if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
+ const uCamPos = p_uniforms.map.cameraPosition;
+
+ if (uCamPos !== undefined) {
+ uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
+ }
+ }
+
+ if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
+ p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
+ }
+
+ if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
+ p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
+ }
+ } // skinning and morph target uniforms must be set even if material didn't change
+ // auto-setting of texture unit for bone and morph texture must go before other textures
+ // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
+
+
+ if (object.isSkinnedMesh) {
+ p_uniforms.setOptional(_gl, object, 'bindMatrix');
+ p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
+ const skeleton = object.skeleton;
+
+ if (skeleton) {
+ if (capabilities.floatVertexTextures) {
+ if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
+ p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
+ p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
+ } else {
+ p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
+ }
+ }
+ }
+
+ if (!!geometry && (geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined)) {
+ morphtargets.update(object, geometry, material, program);
+ }
+
+ if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
+ materialProperties.receiveShadow = object.receiveShadow;
+ p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
+ }
+
+ if (refreshMaterial) {
+ p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
+
+ if (materialProperties.needsLights) {
+ // the current material requires lighting info
+ // note: all lighting uniforms are always set correctly
+ // they simply reference the renderer's state for their
+ // values
+ //
+ // use the current material's .needsUpdate flags to set
+ // the GL state when required
+ markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
+ } // refresh uniforms common to several materials
+
+
+ if (fog && material.fog) {
+ materials.refreshFogUniforms(m_uniforms, fog);
+ }
+
+ materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
+ WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
+ }
+
+ if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
+ WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
+ material.uniformsNeedUpdate = false;
+ }
+
+ if (material.isSpriteMaterial) {
+ p_uniforms.setValue(_gl, 'center', object.center);
+ } // common matrices
+
+
+ p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
+ p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
+ p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
+ return program;
+ } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
+
+
+ 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) {
+ properties.get(renderTarget.texture).__webglTexture = colorTexture;
+ properties.get(renderTarget.depthTexture).__webglTexture = depthTexture;
+ const renderTargetProperties = properties.get(renderTarget);
+ renderTargetProperties.__hasExternalTextures = true;
+
+ if (renderTargetProperties.__hasExternalTextures) {
+ renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
+
+ if (!renderTargetProperties.__autoAllocateDepthBuffer) {
+ // The multisample_render_to_texture extension doesn't work properly if there
+ // are midframe flushes and an external depth buffer. Disable use of the extension.
+ if (renderTarget.useRenderToTexture) {
+ console.warn('render-to-texture extension was disabled because an external texture was provided');
+ renderTarget.useRenderToTexture = false;
+ renderTarget.useRenderbuffer = true;
+ }
+ }
+ }
+ };
+
+ this.setRenderTargetFramebuffer = function (renderTarget, defaultFramebuffer) {
+ const renderTargetProperties = properties.get(renderTarget);
+ renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
+ renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
+ };
+
+ this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
+ _currentRenderTarget = renderTarget;
+ _currentActiveCubeFace = activeCubeFace;
+ _currentActiveMipmapLevel = activeMipmapLevel;
+ let useDefaultFramebuffer = true;
+
+ if (renderTarget) {
+ const renderTargetProperties = properties.get(renderTarget);
+
+ if (renderTargetProperties.__useDefaultFramebuffer !== undefined) {
+ // We need to make sure to rebind the framebuffer.
+ state.bindFramebuffer(_gl.FRAMEBUFFER, null);
+ useDefaultFramebuffer = false;
+ } else if (renderTargetProperties.__webglFramebuffer === undefined) {
+ textures.setupRenderTarget(renderTarget);
+ } else if (renderTargetProperties.__hasExternalTextures) {
+ // Color and depth texture must be rebound in order for the swapchain to update.
+ textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture);
+ }
+ }
+
+ let framebuffer = null;
+ let isCube = false;
+ let isRenderTarget3D = false;
+
+ if (renderTarget) {
+ const texture = renderTarget.texture;
+
+ if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
+ isRenderTarget3D = true;
+ }
+
+ const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
+
+ if (renderTarget.isWebGLCubeRenderTarget) {
+ framebuffer = __webglFramebuffer[activeCubeFace];
+ isCube = true;
+ } else if (renderTarget.useRenderbuffer) {
+ framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
+ } 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;
+ }
+
+ const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
+
+ if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) {
+ 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 textureProperties = properties.get(renderTarget.texture);
+ const layer = activeCubeFace || 0;
+
+ _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
+ }
+
+ _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
+ };
+
+ this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
+ if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
+ console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
+ return;
+ }
+
+ let framebuffer = properties.get(renderTarget).__webglFramebuffer;
+
+ if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
+ framebuffer = framebuffer[activeCubeFaceIndex];
+ }
+
+ if (framebuffer) {
+ state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
+
+ try {
+ const texture = renderTarget.texture;
+ const textureFormat = texture.format;
+ const textureType = texture.type;
+
+ if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
+ console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
+ return;
+ }
+
+ const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && 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 && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
+ !halfFloatSupportedByExt) {
+ console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
+ return;
+ }
+
+ if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
+ // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
+ 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);
+ }
+ } else {
+ console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
+ }
+ } finally {
+ // restore framebuffer of current render target if necessary
+ const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
+ state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
+ }
+ }
+ };
+
+ this.copyFramebufferToTexture = function (position, texture, level = 0) {
+ if (texture.isFramebufferTexture !== true) {
+ console.error('THREE.WebGLRenderer: copyFramebufferToTexture() can only be used with FramebufferTexture.');
+ return;
+ }
+
+ const levelScale = Math.pow(2, -level);
+ const width = Math.floor(texture.image.width * levelScale);
+ const height = Math.floor(texture.image.height * levelScale);
+ textures.setTexture2D(texture, 0);
+
+ _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height);
+
+ state.unbindTexture();
+ };
+
+ this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
+ const width = srcTexture.image.width;
+ const height = srcTexture.image.height;
+ const glFormat = utils.convert(dstTexture.format);
+ const glType = utils.convert(dstTexture.type);
+ textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
+ // parameters, make sure they are correct for the dstTexture
+
+ _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
+
+ _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
+
+ _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
+
+ if (srcTexture.isDataTexture) {
+ _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
+ } else {
+ if (srcTexture.isCompressedTexture) {
+ _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
+ } else {
+ _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
+ }
+ } // Generate mipmaps only when copying level 0
+
+
+ if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
+ state.unbindTexture();
+ };
+
+ this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
+ if (_this.isWebGL1Renderer) {
+ console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
+ return;
+ }
+
+ const width = sourceBox.max.x - sourceBox.min.x + 1;
+ const height = sourceBox.max.y - sourceBox.min.y + 1;
+ const depth = sourceBox.max.z - sourceBox.min.z + 1;
+ const glFormat = utils.convert(dstTexture.format);
+ const glType = utils.convert(dstTexture.type);
+ let glTarget;
+
+ if (dstTexture.isDataTexture3D) {
+ textures.setTexture3D(dstTexture, 0);
+ glTarget = _gl.TEXTURE_3D;
+ } else if (dstTexture.isDataTexture2DArray) {
+ textures.setTexture2DArray(dstTexture, 0);
+ glTarget = _gl.TEXTURE_2D_ARRAY;
+ } else {
+ console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
+ return;
+ }
+
+ _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
+
+ _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
+
+ _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
+
+ const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
+
+ const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
+
+ const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
+
+ const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
+
+ const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
+
+ const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
+
+ _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
+
+ _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
+
+ _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
+
+ _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
+
+ _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
+
+ if (srcTexture.isDataTexture || srcTexture.isDataTexture3D) {
+ _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
+ } else {
+ if (srcTexture.isCompressedTexture) {
+ console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
+
+ _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
+ } else {
+ _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
+ }
+ }
+
+ _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
+
+ _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
+
+ _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
+
+ _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
+
+ _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
+
+
+ if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
+ state.unbindTexture();
+ };
+
+ this.initTexture = function (texture) {
+ 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
+ }));
+ }
+}
+
+WebGLRenderer.prototype.isWebGLRenderer = true;
+
+class WebGL1Renderer extends WebGLRenderer {}
+
+WebGL1Renderer.prototype.isWebGL1Renderer = true;
+
+class FogExp2 {
+ constructor(color, density = 0.00025) {
+ this.name = '';
+ this.color = new Color(color);
+ this.density = density;
+ }
+
+ clone() {
+ return new FogExp2(this.color, this.density);
+ }
+
+ toJSON() {
+ return {
+ type: 'FogExp2',
+ color: this.color.getHex(),
+ density: this.density
+ };
+ }
+
+}
+
+FogExp2.prototype.isFogExp2 = true;
+
+class Fog {
+ constructor(color, near = 1, far = 1000) {
+ this.name = '';
+ this.color = new Color(color);
+ this.near = near;
+ this.far = far;
+ }
+
+ clone() {
+ return new Fog(this.color, this.near, this.far);
+ }
+
+ toJSON() {
+ return {
+ type: 'Fog',
+ color: this.color.getHex(),
+ near: this.near,
+ far: this.far
+ };
+ }
+
+}
+
+Fog.prototype.isFog = true;
+
+class Scene extends Object3D {
+ constructor() {
+ super();
+ this.type = 'Scene';
+ this.background = null;
+ this.environment = null;
+ this.fog = null;
+ this.overrideMaterial = null;
+ this.autoUpdate = true; // checked by the renderer
+
+ 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();
+ if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
+ this.autoUpdate = source.autoUpdate;
+ this.matrixAutoUpdate = source.matrixAutoUpdate;
+ return this;
+ }
+
+ toJSON(meta) {
+ const data = super.toJSON(meta);
+ if (this.fog !== null) data.object.fog = this.fog.toJSON();
+ return data;
+ }
+
+}
+
+Scene.prototype.isScene = true;
+
+class InterleavedBuffer {
+ constructor(array, stride) {
+ this.array = array;
+ this.stride = stride;
+ this.count = array !== undefined ? array.length / stride : 0;
+ this.usage = StaticDrawUsage;
+ this.updateRange = {
+ offset: 0,
+ count: -1
+ };
+ this.version = 0;
+ this.uuid = generateUUID();
+ }
+
+ onUploadCallback() {}
+
+ set needsUpdate(value) {
+ if (value === true) this.version++;
+ }
+
+ setUsage(value) {
+ this.usage = value;
+ return this;
+ }
+
+ copy(source) {
+ this.array = new source.array.constructor(source.array);
+ this.count = source.count;
+ this.stride = source.stride;
+ this.usage = source.usage;
+ return this;
+ }
+
+ copyAt(index1, attribute, index2) {
+ index1 *= this.stride;
+ index2 *= attribute.stride;
+
+ for (let i = 0, l = this.stride; i < l; i++) {
+ this.array[index1 + i] = attribute.array[index2 + i];
+ }
+
+ return this;
+ }
+
+ set(value, offset = 0) {
+ this.array.set(value, offset);
+ return this;
+ }
+
+ clone(data) {
+ if (data.arrayBuffers === undefined) {
+ data.arrayBuffers = {};
+ }
+
+ if (this.array.buffer._uuid === undefined) {
+ this.array.buffer._uuid = generateUUID();
+ }
+
+ if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
+ 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;
+ }
+
+ onUpload(callback) {
+ this.onUploadCallback = callback;
+ return this;
+ }
+
+ toJSON(data) {
+ if (data.arrayBuffers === undefined) {
+ data.arrayBuffers = {};
+ } // generate UUID for array buffer if necessary
+
+
+ if (this.array.buffer._uuid === undefined) {
+ this.array.buffer._uuid = generateUUID();
+ }
+
+ if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
+ data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
+ } //
+
+
+ return {
+ uuid: this.uuid,
+ buffer: this.array.buffer._uuid,
+ type: this.array.constructor.name,
+ stride: this.stride
+ };
+ }
+
+}
+
+InterleavedBuffer.prototype.isInterleavedBuffer = true;
+
+const _vector$6 = /*@__PURE__*/new Vector3();
+
+class InterleavedBufferAttribute {
+ constructor(interleavedBuffer, itemSize, offset, normalized = false) {
+ this.name = '';
+ this.data = interleavedBuffer;
+ this.itemSize = itemSize;
+ this.offset = offset;
+ this.normalized = normalized === true;
+ }
+
+ get count() {
+ return this.data.count;
+ }
+
+ get array() {
+ return this.data.array;
+ }
+
+ set needsUpdate(value) {
+ this.data.needsUpdate = value;
+ }
+
+ applyMatrix4(m) {
+ for (let i = 0, l = this.data.count; i < l; i++) {
+ _vector$6.x = this.getX(i);
+ _vector$6.y = this.getY(i);
+ _vector$6.z = this.getZ(i);
+
+ _vector$6.applyMatrix4(m);
+
+ this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
+ }
+
+ return this;
+ }
+
+ applyNormalMatrix(m) {
+ for (let i = 0, l = this.count; i < l; i++) {
+ _vector$6.x = this.getX(i);
+ _vector$6.y = this.getY(i);
+ _vector$6.z = this.getZ(i);
+
+ _vector$6.applyNormalMatrix(m);
+
+ this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
+ }
+
+ return this;
+ }
+
+ transformDirection(m) {
+ for (let i = 0, l = this.count; i < l; i++) {
+ _vector$6.x = this.getX(i);
+ _vector$6.y = this.getY(i);
+ _vector$6.z = this.getZ(i);
+
+ _vector$6.transformDirection(m);
+
+ this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
+ }
+
+ return this;
+ }
+
+ setX(index, x) {
+ this.data.array[index * this.data.stride + this.offset] = x;
+ return this;
+ }
+
+ setY(index, y) {
+ this.data.array[index * this.data.stride + this.offset + 1] = y;
+ return this;
+ }
+
+ setZ(index, z) {
+ this.data.array[index * this.data.stride + this.offset + 2] = z;
+ return this;
+ }
+
+ setW(index, w) {
+ this.data.array[index * this.data.stride + this.offset + 3] = w;
+ return this;
+ }
+
+ getX(index) {
+ return this.data.array[index * this.data.stride + this.offset];
+ }
+
+ getY(index) {
+ return this.data.array[index * this.data.stride + this.offset + 1];
+ }
+
+ getZ(index) {
+ return this.data.array[index * this.data.stride + this.offset + 2];
+ }
+
+ getW(index) {
+ return this.data.array[index * this.data.stride + this.offset + 3];
+ }
+
+ setXY(index, x, y) {
+ index = index * this.data.stride + this.offset;
+ this.data.array[index + 0] = x;
+ this.data.array[index + 1] = y;
+ return this;
+ }
+
+ setXYZ(index, x, y, z) {
+ index = index * this.data.stride + this.offset;
+ this.data.array[index + 0] = x;
+ this.data.array[index + 1] = y;
+ this.data.array[index + 2] = z;
+ return this;
+ }
+
+ setXYZW(index, x, y, z, w) {
+ index = index * this.data.stride + this.offset;
+ 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;
+ }
+
+ clone(data) {
+ if (data === undefined) {
+ console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave 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 === undefined) {
+ data.interleavedBuffers = {};
+ }
+
+ if (data.interleavedBuffers[this.data.uuid] === undefined) {
+ data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
+ }
+
+ return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
+ }
+ }
+
+ toJSON(data) {
+ if (data === undefined) {
+ console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave 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]);
+ }
+ } // deinterleave data and save it as an ordinary buffer attribute for now
+
+
+ return {
+ itemSize: this.itemSize,
+ type: this.array.constructor.name,
+ array: array,
+ normalized: this.normalized
+ };
+ } else {
+ // save as true interlaved attribtue
+ if (data.interleavedBuffers === undefined) {
+ data.interleavedBuffers = {};
+ }
+
+ if (data.interleavedBuffers[this.data.uuid] === undefined) {
+ 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
+ };
+ }
+ }
+
+}
+
+InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
+
+/**
+ * parameters = {
+ * color: <hex>,
+ * map: new THREE.Texture( <Image> ),
+ * alphaMap: new THREE.Texture( <Image> ),
+ * rotation: <float>,
+ * sizeAttenuation: <bool>
+ * }
+ */
+
+class SpriteMaterial extends Material {
+ constructor(parameters) {
+ super();
+ this.type = 'SpriteMaterial';
+ this.color = new Color(0xffffff);
+ this.map = null;
+ this.alphaMap = null;
+ this.rotation = 0;
+ this.sizeAttenuation = true;
+ this.transparent = 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;
+ return this;
+ }
+
+}
+
+SpriteMaterial.prototype.isSpriteMaterial = true;
+
+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 = /*@__PURE__*/new Vector3();
+
+const _vB = /*@__PURE__*/new Vector3();
+
+const _vC = /*@__PURE__*/new Vector3();
+
+const _uvA = /*@__PURE__*/new Vector2();
+
+const _uvB = /*@__PURE__*/new Vector2();
+
+const _uvC = /*@__PURE__*/new Vector2();
+
+class Sprite extends Object3D {
+ constructor(material) {
+ super();
+ this.type = 'Sprite';
+
+ if (_geometry === undefined) {
+ _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 !== undefined ? material : new SpriteMaterial();
+ this.center = new Vector2(0.5, 0.5);
+ }
+
+ raycast(raycaster, intersects) {
+ if (raycaster.camera === null) {
+ console.error('THREE.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.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
+ transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
+ transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
+
+ _uvA.set(0, 0);
+
+ _uvB.set(1, 0);
+
+ _uvC.set(1, 1); // check first triangle
+
+
+ let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
+
+ if (intersect === null) {
+ // check second triangle
+ transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
+
+ _uvB.set(0, 1);
+
+ intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
+
+ if (intersect === null) {
+ return;
+ }
+ }
+
+ const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
+ if (distance < raycaster.near || distance > raycaster.far) return;
+ intersects.push({
+ distance: distance,
+ point: _intersectPoint.clone(),
+ uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
+ face: null,
+ object: this
+ });
+ }
+
+ copy(source) {
+ super.copy(source);
+ if (source.center !== undefined) this.center.copy(source.center);
+ this.material = source.material;
+ return this;
+ }
+
+}
+
+Sprite.prototype.isSprite = true;
+
+function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
+ // compute position in camera space
+ _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
+
+
+ if (sin !== undefined) {
+ _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; // transform to world space
+
+ vertexPosition.applyMatrix4(_viewWorldMatrix);
+}
+
+const _v1$2 = /*@__PURE__*/new Vector3();
+
+const _v2$1 = /*@__PURE__*/new Vector3();
+
+class LOD extends Object3D {
+ constructor() {
+ super();
+ this._currentLevel = 0;
+ this.type = 'LOD';
+ Object.defineProperties(this, {
+ levels: {
+ enumerable: true,
+ value: []
+ },
+ isLOD: {
+ value: true
+ }
+ });
+ 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);
+ }
+
+ this.autoUpdate = source.autoUpdate;
+ return this;
+ }
+
+ addLevel(object, distance = 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: distance,
+ object: object
+ });
+ this.add(object);
+ return this;
+ }
+
+ getCurrentLevel() {
+ return this._currentLevel;
+ }
+
+ getObjectForDistance(distance) {
+ const levels = this.levels;
+
+ if (levels.length > 0) {
+ let i, l;
+
+ for (i = 1, l = levels.length; i < l; i++) {
+ if (distance < levels[i].distance) {
+ break;
+ }
+ }
+
+ return levels[i - 1].object;
+ }
+
+ return null;
+ }
+
+ raycast(raycaster, intersects) {
+ 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, intersects);
+ }
+ }
+
+ 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++) {
+ if (distance >= levels[i].distance) {
+ 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
+ });
+ }
+
+ return data;
+ }
+
+}
+
+const _basePosition = /*@__PURE__*/new Vector3();
+
+const _skinIndex = /*@__PURE__*/new Vector4();
+
+const _skinWeight = /*@__PURE__*/new Vector4();
+
+const _vector$5 = /*@__PURE__*/new Vector3();
+
+const _matrix = /*@__PURE__*/new Matrix4();
+
+class SkinnedMesh extends Mesh {
+ constructor(geometry, material) {
+ super(geometry, material);
+ this.type = 'SkinnedMesh';
+ this.bindMode = 'attached';
+ this.bindMatrix = new Matrix4();
+ this.bindMatrixInverse = new Matrix4();
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.bindMode = source.bindMode;
+ this.bindMatrix.copy(source.bindMatrix);
+ this.bindMatrixInverse.copy(source.bindMatrixInverse);
+ this.skeleton = source.skeleton;
+ return this;
+ }
+
+ bind(skeleton, bindMatrix) {
+ this.skeleton = skeleton;
+
+ if (bindMatrix === undefined) {
+ this.updateMatrixWorld(true);
+ this.skeleton.calculateInverses();
+ bindMatrix = this.matrixWorld;
+ }
+
+ this.bindMatrix.copy(bindMatrix);
+ this.bindMatrixInverse.copy(bindMatrix).invert();
+ }
+
+ pose() {
+ this.skeleton.pose();
+ }
+
+ normalizeSkinWeights() {
+ const vector = new Vector4();
+ const skinWeight = this.geometry.attributes.skinWeight;
+
+ for (let i = 0, l = skinWeight.count; i < l; i++) {
+ vector.x = skinWeight.getX(i);
+ vector.y = skinWeight.getY(i);
+ vector.z = skinWeight.getZ(i);
+ vector.w = skinWeight.getW(i);
+ const scale = 1.0 / vector.manhattanLength();
+
+ if (scale !== Infinity) {
+ vector.multiplyScalar(scale);
+ } else {
+ vector.set(1, 0, 0, 0); // do something reasonable
+ }
+
+ skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
+ }
+ }
+
+ updateMatrixWorld(force) {
+ super.updateMatrixWorld(force);
+
+ if (this.bindMode === 'attached') {
+ this.bindMatrixInverse.copy(this.matrixWorld).invert();
+ } else if (this.bindMode === 'detached') {
+ this.bindMatrixInverse.copy(this.bindMatrix).invert();
+ } else {
+ console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
+ }
+ }
+
+ boneTransform(index, target) {
+ const skeleton = this.skeleton;
+ const geometry = this.geometry;
+
+ _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
+
+ _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
+
+ _basePosition.copy(target).applyMatrix4(this.bindMatrix);
+
+ target.set(0, 0, 0);
+
+ for (let i = 0; i < 4; i++) {
+ const weight = _skinWeight.getComponent(i);
+
+ if (weight !== 0) {
+ const boneIndex = _skinIndex.getComponent(i);
+
+ _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
+
+ target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
+ }
+ }
+
+ return target.applyMatrix4(this.bindMatrixInverse);
+ }
+
+}
+
+SkinnedMesh.prototype.isSkinnedMesh = true;
+
+class Bone extends Object3D {
+ constructor() {
+ super();
+ this.type = 'Bone';
+ }
+
+}
+
+Bone.prototype.isBone = true;
+
+class DataTexture extends Texture {
+ constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
+ super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
+ this.image = {
+ data: data,
+ width: width,
+ height: height
+ };
+ this.magFilter = magFilter;
+ this.minFilter = minFilter;
+ this.generateMipmaps = false;
+ this.flipY = false;
+ this.unpackAlignment = 1;
+ }
+
+}
+
+DataTexture.prototype.isDataTexture = true;
+
+const _offsetMatrix = /*@__PURE__*/new Matrix4();
+
+const _identityMatrix = /*@__PURE__*/new Matrix4();
+
+class Skeleton {
+ constructor(bones = [], boneInverses = []) {
+ this.uuid = generateUUID();
+ this.bones = bones.slice(0);
+ this.boneInverses = boneInverses;
+ this.boneMatrices = null;
+ this.boneTexture = null;
+ this.boneTextureSize = 0;
+ this.frame = -1;
+ this.init();
+ }
+
+ init() {
+ const bones = this.bones;
+ const boneInverses = this.boneInverses;
+ this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
+
+ if (boneInverses.length === 0) {
+ this.calculateInverses();
+ } else {
+ // handle special case
+ if (bones.length !== boneInverses.length) {
+ console.warn('THREE.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());
+ }
+ }
+ }
+ }
+
+ 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);
+ }
+ }
+
+ pose() {
+ // recover the bind-time world matrices
+ 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();
+ }
+ } // compute the local matrices, positions, rotations and scales
+
+
+ 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);
+ }
+ }
+ }
+
+ update() {
+ const bones = this.bones;
+ const boneInverses = this.boneInverses;
+ const boneMatrices = this.boneMatrices;
+ const boneTexture = this.boneTexture; // flatten bone matrices to array
+
+ for (let i = 0, il = bones.length; i < il; i++) {
+ // compute the offset between the current and the original transform
+ const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
+
+ _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
+
+ _offsetMatrix.toArray(boneMatrices, i * 16);
+ }
+
+ if (boneTexture !== null) {
+ boneTexture.needsUpdate = true;
+ }
+ }
+
+ clone() {
+ return new Skeleton(this.bones, this.boneInverses);
+ }
+
+ computeBoneTexture() {
+ // layout (1 matrix = 4 pixels)
+ // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
+ // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
+ // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
+ // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
+ // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
+ let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
+
+ size = ceilPowerOfTwo(size);
+ size = Math.max(size, 4);
+ const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
+
+ boneMatrices.set(this.boneMatrices); // copy current values
+
+ const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
+ boneTexture.needsUpdate = true;
+ this.boneMatrices = boneMatrices;
+ this.boneTexture = boneTexture;
+ this.boneTextureSize = size;
+ return this;
+ }
+
+ 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 undefined;
+ }
+
+ dispose() {
+ if (this.boneTexture !== null) {
+ this.boneTexture.dispose();
+ this.boneTexture = null;
+ }
+ }
+
+ 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 === undefined) {
+ console.warn('THREE.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;
+ }
+
+ toJSON() {
+ const data = {
+ metadata: {
+ version: 4.5,
+ 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 {
+ constructor(array, itemSize, normalized, meshPerAttribute = 1) {
+ if (typeof normalized === 'number') {
+ meshPerAttribute = normalized;
+ normalized = false;
+ console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
+ }
+
+ super(array, itemSize, normalized);
+ 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;
+ }
+
+}
+
+InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
+
+const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
+
+const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
+
+const _instanceIntersects = [];
+
+const _mesh = /*@__PURE__*/new Mesh();
+
+class InstancedMesh extends Mesh {
+ constructor(geometry, material, count) {
+ super(geometry, material);
+ this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
+ this.instanceColor = null;
+ this.count = count;
+ this.frustumCulled = false;
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.instanceMatrix.copy(source.instanceMatrix);
+ if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
+ this.count = source.count;
+ return this;
+ }
+
+ getColorAt(index, color) {
+ color.fromArray(this.instanceColor.array, index * 3);
+ }
+
+ getMatrixAt(index, matrix) {
+ matrix.fromArray(this.instanceMatrix.array, index * 16);
+ }
+
+ raycast(raycaster, intersects) {
+ const matrixWorld = this.matrixWorld;
+ const raycastTimes = this.count;
+ _mesh.geometry = this.geometry;
+ _mesh.material = this.material;
+ if (_mesh.material === undefined) return;
+
+ for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
+ // calculate the world matrix for each instance
+ this.getMatrixAt(instanceId, _instanceLocalMatrix);
+
+ _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
+
+
+ _mesh.matrixWorld = _instanceWorldMatrix;
+
+ _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
+
+
+ for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
+ const intersect = _instanceIntersects[i];
+ intersect.instanceId = instanceId;
+ intersect.object = this;
+ intersects.push(intersect);
+ }
+
+ _instanceIntersects.length = 0;
+ }
+ }
+
+ setColorAt(index, color) {
+ if (this.instanceColor === null) {
+ this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
+ }
+
+ color.toArray(this.instanceColor.array, index * 3);
+ }
+
+ setMatrixAt(index, matrix) {
+ matrix.toArray(this.instanceMatrix.array, index * 16);
+ }
+
+ updateMorphTargets() {}
+
+ dispose() {
+ this.dispatchEvent({
+ type: 'dispose'
+ });
+ }
+
+}
+
+InstancedMesh.prototype.isInstancedMesh = true;
+
+/**
+ * parameters = {
+ * color: <hex>,
+ * opacity: <float>,
+ *
+ * linewidth: <float>,
+ * linecap: "round",
+ * linejoin: "round"
+ * }
+ */
+
+class LineBasicMaterial extends Material {
+ constructor(parameters) {
+ super();
+ this.type = 'LineBasicMaterial';
+ this.color = new Color(0xffffff);
+ this.linewidth = 1;
+ this.linecap = 'round';
+ this.linejoin = 'round';
+ this.setValues(parameters);
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.color.copy(source.color);
+ this.linewidth = source.linewidth;
+ this.linecap = source.linecap;
+ this.linejoin = source.linejoin;
+ return this;
+ }
+
+}
+
+LineBasicMaterial.prototype.isLineBasicMaterial = true;
+
+const _start$1 = /*@__PURE__*/new Vector3();
+
+const _end$1 = /*@__PURE__*/new Vector3();
+
+const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
+
+const _ray$1 = /*@__PURE__*/new Ray();
+
+const _sphere$1 = /*@__PURE__*/new Sphere();
+
+class Line extends Object3D {
+ constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
+ super();
+ this.type = 'Line';
+ this.geometry = geometry;
+ this.material = material;
+ this.updateMorphTargets();
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.material = source.material;
+ this.geometry = source.geometry;
+ return this;
+ }
+
+ computeLineDistances() {
+ const geometry = this.geometry;
+
+ if (geometry.isBufferGeometry) {
+ // we assume non-indexed geometry
+ if (geometry.index === null) {
+ const positionAttribute = geometry.attributes.position;
+ const lineDistances = [0];
+
+ for (let i = 1, l = positionAttribute.count; i < l; i++) {
+ _start$1.fromBufferAttribute(positionAttribute, i - 1);
+
+ _end$1.fromBufferAttribute(positionAttribute, i);
+
+ lineDistances[i] = lineDistances[i - 1];
+ lineDistances[i] += _start$1.distanceTo(_end$1);
+ }
+
+ geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
+ } else {
+ console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
+ }
+ } else if (geometry.isGeometry) {
+ console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
+ }
+
+ return this;
+ }
+
+ raycast(raycaster, intersects) {
+ const geometry = this.geometry;
+ const matrixWorld = this.matrixWorld;
+ const threshold = raycaster.params.Line.threshold;
+ const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
+
+ 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 vStart = new Vector3();
+ const vEnd = new Vector3();
+ const interSegment = new Vector3();
+ const interRay = new Vector3();
+ const step = this.isLineSegments ? 2 : 1;
+
+ if (geometry.isBufferGeometry) {
+ 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);
+ vStart.fromBufferAttribute(positionAttribute, a);
+ vEnd.fromBufferAttribute(positionAttribute, b);
+
+ const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
+
+ if (distSq > localThresholdSq) continue;
+ interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
+
+ const distance = raycaster.ray.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(this.matrixWorld),
+ index: i,
+ face: null,
+ faceIndex: null,
+ object: 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 - 1; i < l; i += step) {
+ vStart.fromBufferAttribute(positionAttribute, i);
+ vEnd.fromBufferAttribute(positionAttribute, i + 1);
+
+ const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
+
+ if (distSq > localThresholdSq) continue;
+ interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
+
+ const distance = raycaster.ray.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(this.matrixWorld),
+ index: i,
+ face: null,
+ faceIndex: null,
+ object: this
+ });
+ }
+ }
+ } else if (geometry.isGeometry) {
+ console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
+ }
+ }
+
+ updateMorphTargets() {
+ const geometry = this.geometry;
+
+ if (geometry.isBufferGeometry) {
+ const morphAttributes = geometry.morphAttributes;
+ const keys = Object.keys(morphAttributes);
+
+ if (keys.length > 0) {
+ const morphAttribute = morphAttributes[keys[0]];
+
+ if (morphAttribute !== undefined) {
+ 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;
+ }
+ }
+ }
+ } else {
+ const morphTargets = geometry.morphTargets;
+
+ if (morphTargets !== undefined && morphTargets.length > 0) {
+ console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
+ }
+ }
+ }
+
+}
+
+Line.prototype.isLine = true;
+
+const _start = /*@__PURE__*/new Vector3();
+
+const _end = /*@__PURE__*/new Vector3();
+
+class LineSegments extends Line {
+ constructor(geometry, material) {
+ super(geometry, material);
+ this.type = 'LineSegments';
+ }
+
+ computeLineDistances() {
+ const geometry = this.geometry;
+
+ if (geometry.isBufferGeometry) {
+ // we assume non-indexed 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 {
+ console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
+ }
+ } else if (geometry.isGeometry) {
+ console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
+ }
+
+ return this;
+ }
+
+}
+
+LineSegments.prototype.isLineSegments = true;
+
+class LineLoop extends Line {
+ constructor(geometry, material) {
+ super(geometry, material);
+ this.type = 'LineLoop';
+ }
+
+}
+
+LineLoop.prototype.isLineLoop = true;
+
+/**
+ * parameters = {
+ * color: <hex>,
+ * opacity: <float>,
+ * map: new THREE.Texture( <Image> ),
+ * alphaMap: new THREE.Texture( <Image> ),
+ *
+ * size: <float>,
+ * sizeAttenuation: <bool>
+ *
+ * }
+ */
+
+class PointsMaterial extends Material {
+ constructor(parameters) {
+ super();
+ this.type = 'PointsMaterial';
+ this.color = new Color(0xffffff);
+ this.map = null;
+ this.alphaMap = null;
+ this.size = 1;
+ this.sizeAttenuation = 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;
+ return this;
+ }
+
+}
+
+PointsMaterial.prototype.isPointsMaterial = true;
+
+const _inverseMatrix = /*@__PURE__*/new Matrix4();
+
+const _ray = /*@__PURE__*/new Ray();
+
+const _sphere = /*@__PURE__*/new Sphere();
+
+const _position$2 = /*@__PURE__*/new Vector3();
+
+class Points extends Object3D {
+ constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
+ super();
+ this.type = 'Points';
+ this.geometry = geometry;
+ this.material = material;
+ this.updateMorphTargets();
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.material = source.material;
+ this.geometry = source.geometry;
+ return this;
+ }
+
+ raycast(raycaster, intersects) {
+ const geometry = this.geometry;
+ const matrixWorld = this.matrixWorld;
+ const threshold = raycaster.params.Points.threshold;
+ const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
+
+ 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;
+
+ if (geometry.isBufferGeometry) {
+ 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$2.fromBufferAttribute(positionAttribute, a);
+
+ testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, 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$2.fromBufferAttribute(positionAttribute, i);
+
+ testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
+ }
+ }
+ } else {
+ console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
+ }
+ }
+
+ updateMorphTargets() {
+ const geometry = this.geometry;
+
+ if (geometry.isBufferGeometry) {
+ const morphAttributes = geometry.morphAttributes;
+ const keys = Object.keys(morphAttributes);
+
+ if (keys.length > 0) {
+ const morphAttribute = morphAttributes[keys[0]];
+
+ if (morphAttribute !== undefined) {
+ 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;
+ }
+ }
+ }
+ } else {
+ const morphTargets = geometry.morphTargets;
+
+ if (morphTargets !== undefined && morphTargets.length > 0) {
+ console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
+ }
+ }
+ }
+
+}
+
+Points.prototype.isPoints = true;
+
+function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
+ const rayPointDistanceSq = _ray.distanceSqToPoint(point);
+
+ if (rayPointDistanceSq < localThresholdSq) {
+ const intersectPoint = new Vector3();
+
+ _ray.closestPointToPoint(point, intersectPoint);
+
+ intersectPoint.applyMatrix4(matrixWorld);
+ const distance = raycaster.ray.origin.distanceTo(intersectPoint);
+ if (distance < raycaster.near || distance > raycaster.far) return;
+ intersects.push({
+ distance: distance,
+ distanceToRay: Math.sqrt(rayPointDistanceSq),
+ point: intersectPoint,
+ index: index,
+ face: null,
+ object: object
+ });
+ }
+}
+
+class VideoTexture extends Texture {
+ constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
+ super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
+ this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
+ this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
+ this.generateMipmaps = false;
+ const scope = this;
+
+ function updateVideo() {
+ scope.needsUpdate = true;
+ video.requestVideoFrameCallback(updateVideo);
+ }
+
+ if ('requestVideoFrameCallback' in video) {
+ video.requestVideoFrameCallback(updateVideo);
+ }
+ }
+
+ clone() {
+ return new this.constructor(this.image).copy(this);
+ }
+
+ update() {
+ const video = this.image;
+ const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
+
+ if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
+ this.needsUpdate = true;
+ }
+ }
+
+}
+
+VideoTexture.prototype.isVideoTexture = true;
+
+class FramebufferTexture extends Texture {
+ constructor(width, height, format) {
+ super({
+ width,
+ height
+ });
+ this.format = format;
+ this.magFilter = NearestFilter;
+ this.minFilter = NearestFilter;
+ this.generateMipmaps = false;
+ this.needsUpdate = true;
+ }
+
+}
+
+FramebufferTexture.prototype.isFramebufferTexture = true;
+
+class CompressedTexture extends Texture {
+ constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
+ super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
+ this.image = {
+ width: width,
+ height: height
+ };
+ this.mipmaps = mipmaps; // no flipping for cube textures
+ // (also flipping doesn't work for compressed textures )
+
+ this.flipY = false; // can't generate mipmaps for compressed textures
+ // mips must be embedded in DDS files
+
+ this.generateMipmaps = false;
+ }
+
+}
+
+CompressedTexture.prototype.isCompressedTexture = true;
+
+class CanvasTexture extends Texture {
+ constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
+ super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
+ this.needsUpdate = true;
+ }
+
+}
+
+CanvasTexture.prototype.isCanvasTexture = true;
+
+class CircleGeometry extends BufferGeometry {
+ constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
+ super();
+ this.type = 'CircleGeometry';
+ this.parameters = {
+ radius: radius,
+ segments: segments,
+ thetaStart: thetaStart,
+ thetaLength: thetaLength
+ };
+ segments = Math.max(3, segments); // buffers
+
+ const indices = [];
+ const vertices = [];
+ const normals = [];
+ const uvs = []; // helper variables
+
+ const vertex = new Vector3();
+ const uv = new Vector2(); // center point
+
+ 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; // vertex
+
+ vertex.x = radius * Math.cos(segment);
+ vertex.y = radius * Math.sin(segment);
+ vertices.push(vertex.x, vertex.y, vertex.z); // normal
+
+ normals.push(0, 0, 1); // uvs
+
+ uv.x = (vertices[i] / radius + 1) / 2;
+ uv.y = (vertices[i + 1] / radius + 1) / 2;
+ uvs.push(uv.x, uv.y);
+ } // indices
+
+
+ for (let i = 1; i <= segments; i++) {
+ indices.push(i, i + 1, 0);
+ } // build geometry
+
+
+ this.setIndex(indices);
+ this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
+ this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
+ this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
+ }
+
+ static fromJSON(data) {
+ return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
+ }
+
+}
+
+class CylinderGeometry extends BufferGeometry {
+ constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
+ super();
+ this.type = 'CylinderGeometry';
+ this.parameters = {
+ radiusTop: radiusTop,
+ radiusBottom: radiusBottom,
+ height: height,
+ radialSegments: radialSegments,
+ heightSegments: heightSegments,
+ openEnded: openEnded,
+ thetaStart: thetaStart,
+ thetaLength: thetaLength
+ };
+ const scope = this;
+ radialSegments = Math.floor(radialSegments);
+ heightSegments = Math.floor(heightSegments); // buffers
+
+ const indices = [];
+ const vertices = [];
+ const normals = [];
+ const uvs = []; // helper variables
+
+ let index = 0;
+ const indexArray = [];
+ const halfHeight = height / 2;
+ let groupStart = 0; // generate geometry
+
+ generateTorso();
+
+ if (openEnded === false) {
+ if (radiusTop > 0) generateCap(true);
+ if (radiusBottom > 0) generateCap(false);
+ } // build geometry
+
+
+ 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 vertex = new Vector3();
+ let groupCount = 0; // this will be used to calculate the normal
+
+ const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
+
+ for (let y = 0; y <= heightSegments; y++) {
+ const indexRow = [];
+ const v = y / heightSegments; // calculate the radius of the current row
+
+ 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); // vertex
+
+ vertex.x = radius * sinTheta;
+ vertex.y = -v * height + halfHeight;
+ vertex.z = radius * cosTheta;
+ vertices.push(vertex.x, vertex.y, vertex.z); // normal
+
+ normal.set(sinTheta, slope, cosTheta).normalize();
+ normals.push(normal.x, normal.y, normal.z); // uv
+
+ uvs.push(u, 1 - v); // save index of vertex in respective row
+
+ indexRow.push(index++);
+ } // now save vertices of the row in our index array
+
+
+ indexArray.push(indexRow);
+ } // generate indices
+
+
+ for (let x = 0; x < radialSegments; x++) {
+ for (let y = 0; y < heightSegments; y++) {
+ // we use the index array to access the correct indices
+ const a = indexArray[y][x];
+ const b = indexArray[y + 1][x];
+ const c = indexArray[y + 1][x + 1];
+ const d = indexArray[y][x + 1]; // faces
+
+ indices.push(a, b, d);
+ indices.push(b, c, d); // update group counter
+
+ groupCount += 6;
+ }
+ } // add a group to the geometry. this will ensure multi material support
+
+
+ scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
+
+ groupStart += groupCount;
+ }
+
+ function generateCap(top) {
+ // save the index of the first center vertex
+ const centerIndexStart = index;
+ const uv = new Vector2();
+ const vertex = new Vector3();
+ let groupCount = 0;
+ const radius = top === true ? radiusTop : radiusBottom;
+ const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
+ // because the geometry needs one set of uvs per face,
+ // we must generate a center vertex per face/segment
+
+ for (let x = 1; x <= radialSegments; x++) {
+ // vertex
+ vertices.push(0, halfHeight * sign, 0); // normal
+
+ normals.push(0, sign, 0); // uv
+
+ uvs.push(0.5, 0.5); // increase index
+
+ index++;
+ } // save the index of the last center vertex
+
+
+ const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
+
+ 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); // vertex
+
+ vertex.x = radius * sinTheta;
+ vertex.y = halfHeight * sign;
+ vertex.z = radius * cosTheta;
+ vertices.push(vertex.x, vertex.y, vertex.z); // normal
+
+ normals.push(0, sign, 0); // uv
+
+ uv.x = cosTheta * 0.5 + 0.5;
+ uv.y = sinTheta * 0.5 * sign + 0.5;
+ uvs.push(uv.x, uv.y); // increase index
+
+ index++;
+ } // generate indices
+
+
+ for (let x = 0; x < radialSegments; x++) {
+ const c = centerIndexStart + x;
+ const i = centerIndexEnd + x;
+
+ if (top === true) {
+ // face top
+ indices.push(i, i + 1, c);
+ } else {
+ // face bottom
+ indices.push(i + 1, i, c);
+ }
+
+ groupCount += 3;
+ } // add a group to the geometry. this will ensure multi material support
+
+
+ scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
+
+ groupStart += groupCount;
+ }
+ }
+
+ 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 {
+ constructor(radius = 1, height = 1, radialSegments = 8, 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: radius,
+ height: height,
+ radialSegments: radialSegments,
+ heightSegments: heightSegments,
+ openEnded: openEnded,
+ thetaStart: thetaStart,
+ thetaLength: thetaLength
+ };
+ }
+
+ static fromJSON(data) {
+ return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
+ }
+
+}
+
+class PolyhedronGeometry extends BufferGeometry {
+ constructor(vertices = [], indices = [], radius = 1, detail = 0) {
+ super();
+ this.type = 'PolyhedronGeometry';
+ this.parameters = {
+ vertices: vertices,
+ indices: indices,
+ radius: radius,
+ detail: detail
+ }; // default buffer data
+
+ const vertexBuffer = [];
+ const uvBuffer = []; // the subdivision creates the vertex buffer data
+
+ subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
+
+ applyRadius(radius); // finally, create the uv data
+
+ generateUVs(); // build non-indexed geometry
+
+ 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(); // flat normals
+ } else {
+ this.normalizeNormals(); // smooth normals
+ } // helper functions
+
+
+ function subdivide(detail) {
+ const a = new Vector3();
+ const b = new Vector3();
+ const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
+
+ for (let i = 0; i < indices.length; i += 3) {
+ // get the vertices of the face
+ getVertexByIndex(indices[i + 0], a);
+ getVertexByIndex(indices[i + 1], b);
+ getVertexByIndex(indices[i + 2], c); // perform subdivision
+
+ subdivideFace(a, b, c, detail);
+ }
+ }
+
+ function subdivideFace(a, b, c, detail) {
+ const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
+
+ const v = []; // construct all of the vertices for this subdivision
+
+ 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 rows = cols - i;
+
+ for (let j = 0; j <= rows; j++) {
+ if (j === 0 && i === cols) {
+ v[i][j] = aj;
+ } else {
+ v[i][j] = aj.clone().lerp(bj, j / rows);
+ }
+ }
+ } // construct all of the faces
+
+
+ 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(radius) {
+ const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
+
+ for (let i = 0; i < vertexBuffer.length; i += 3) {
+ vertex.x = vertexBuffer[i + 0];
+ vertex.y = vertexBuffer[i + 1];
+ vertex.z = vertexBuffer[i + 2];
+ vertex.normalize().multiplyScalar(radius);
+ vertexBuffer[i + 0] = vertex.x;
+ vertexBuffer[i + 1] = vertex.y;
+ vertexBuffer[i + 2] = vertex.z;
+ }
+ }
+
+ function generateUVs() {
+ const vertex = new Vector3();
+
+ for (let i = 0; i < vertexBuffer.length; i += 3) {
+ vertex.x = vertexBuffer[i + 0];
+ vertex.y = vertexBuffer[i + 1];
+ vertex.z = vertexBuffer[i + 2];
+ const u = azimuth(vertex) / 2 / Math.PI + 0.5;
+ const v = inclination(vertex) / Math.PI + 0.5;
+ uvBuffer.push(u, 1 - v);
+ }
+
+ correctUVs();
+ correctSeam();
+ }
+
+ function correctSeam() {
+ // handle case when face straddles the seam, see #3269
+ for (let i = 0; i < uvBuffer.length; i += 6) {
+ // uv data of a single face
+ 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); // 0.9 is somewhat arbitrary
+
+ 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(vertex) {
+ vertexBuffer.push(vertex.x, vertex.y, vertex.z);
+ }
+
+ function getVertexByIndex(index, vertex) {
+ const stride = index * 3;
+ vertex.x = vertices[stride + 0];
+ vertex.y = vertices[stride + 1];
+ vertex.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, azimuth) {
+ if (azimuth < 0 && uv.x === 1) {
+ uvBuffer[stride] = uv.x - 1;
+ }
+
+ if (vector.x === 0 && vector.z === 0) {
+ uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
+ }
+ } // 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));
+ }
+ }
+
+ static fromJSON(data) {
+ return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
+ }
+
+}
+
+class DodecahedronGeometry extends PolyhedronGeometry {
+ 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: radius,
+ detail: detail
+ };
+ }
+
+ static fromJSON(data) {
+ return new DodecahedronGeometry(data.radius, data.detail);
+ }
+
+}
+
+const _v0 = new Vector3();
+
+const _v1$1 = new Vector3();
+
+const _normal = new Vector3();
+
+const _triangle = new Triangle();
+
+class EdgesGeometry extends BufferGeometry {
+ constructor(geometry = null, thresholdAngle = 1) {
+ super();
+ this.type = 'EdgesGeometry';
+ this.parameters = {
+ geometry: geometry,
+ thresholdAngle: 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); // create hashes for the edge from the vertices
+
+
+ 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)}`; // skip degenerate triangles
+
+ if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
+ continue;
+ } // iterate over every edge
+
+
+ for (let j = 0; j < 3; j++) {
+ // get the first and next vertex making up the edge
+ 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 we found a sibling edge add it into the vertex array if
+ // it meets the angle threshold and delete the edge from the map.
+ 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)) {
+ // if we've already got an edge here then skip adding a new one
+ edgeData[hash] = {
+ index0: indexArr[j],
+ index1: indexArr[jNext],
+ normal: _normal.clone()
+ };
+ }
+ }
+ } // iterate over all remaining, unmatched edges and add them to the vertex array
+
+
+ for (const key in edgeData) {
+ if (edgeData[key]) {
+ const {
+ index0,
+ index1
+ } = edgeData[key];
+
+ _v0.fromBufferAttribute(positionAttr, index0);
+
+ _v1$1.fromBufferAttribute(positionAttr, index1);
+
+ vertices.push(_v0.x, _v0.y, _v0.z);
+ vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
+ }
+ }
+
+ this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
+ }
+ }
+
+}
+
+/**
+ * Extensible curve object.
+ *
+ * Some common of curve methods:
+ * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
+ * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
+ * .getPoints(), .getSpacedPoints()
+ * .getLength()
+ * .updateArcLengths()
+ *
+ * This following curves inherit from THREE.Curve:
+ *
+ * -- 2D curves --
+ * THREE.ArcCurve
+ * THREE.CubicBezierCurve
+ * THREE.EllipseCurve
+ * THREE.LineCurve
+ * THREE.QuadraticBezierCurve
+ * THREE.SplineCurve
+ *
+ * -- 3D curves --
+ * THREE.CatmullRomCurve3
+ * THREE.CubicBezierCurve3
+ * THREE.LineCurve3
+ * THREE.QuadraticBezierCurve3
+ *
+ * A series of curves can be represented as a THREE.CurvePath.
+ *
+ **/
+
+class Curve {
+ constructor() {
+ this.type = 'Curve';
+ this.arcLengthDivisions = 200;
+ } // Virtual base class method to overwrite and implement in subclasses
+ // - t [0 .. 1]
+
+
+ getPoint() {
+ console.warn('THREE.Curve: .getPoint() not implemented.');
+ return null;
+ } // Get point at relative position in curve according to arc length
+ // - u [0 .. 1]
+
+
+ getPointAt(u, optionalTarget) {
+ const t = this.getUtoTmapping(u);
+ return this.getPoint(t, optionalTarget);
+ } // Get sequence of points using getPoint( t )
+
+
+ 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 )
+
+
+ getSpacedPoints(divisions = 5) {
+ const points = [];
+
+ for (let d = 0; d <= divisions; d++) {
+ points.push(this.getPointAt(d / divisions));
+ }
+
+ return points;
+ } // Get total curve arc length
+
+
+ getLength() {
+ const lengths = this.getLengths();
+ return lengths[lengths.length - 1];
+ } // Get list of 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; // { sums: cache, sum: sum }; Sum is in the last element.
+ }
+
+ updateArcLengths() {
+ this.needsUpdate = true;
+ this.getLengths();
+ } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
+
+
+ getUtoTmapping(u, distance) {
+ const arcLengths = this.getLengths();
+ let i = 0;
+ const il = arcLengths.length;
+ let targetArcLength; // The targeted u distance value to get
+
+ if (distance) {
+ targetArcLength = distance;
+ } else {
+ targetArcLength = u * arcLengths[il - 1];
+ } // binary search for the index with largest value smaller than target u distance
+
+
+ let 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;
+ } else if (comparison > 0) {
+ high = i - 1;
+ } else {
+ high = i;
+ break; // DONE
+ }
+ }
+
+ i = high;
+
+ if (arcLengths[i] === targetArcLength) {
+ return i / (il - 1);
+ } // we could get finer grain at lengths, or use simple interpolation between two points
+
+
+ const lengthBefore = arcLengths[i];
+ const lengthAfter = arcLengths[i + 1];
+ const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
+
+ const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
+
+ const 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
+
+
+ getTangent(t, optionalTarget) {
+ const delta = 0.0001;
+ let t1 = t - delta;
+ let t2 = t + delta; // Capping in case of danger
+
+ 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;
+ }
+
+ getTangentAt(u, optionalTarget) {
+ const t = this.getUtoTmapping(u);
+ return this.getTangent(t, optionalTarget);
+ }
+
+ computeFrenetFrames(segments, closed) {
+ // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
+ const normal = new Vector3();
+ const tangents = [];
+ const normals = [];
+ const binormals = [];
+ const vec = new Vector3();
+ const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
+
+ for (let i = 0; i <= segments; i++) {
+ const u = i / segments;
+ tangents[i] = this.getTangentAt(u, new Vector3());
+ } // select an initial normal vector perpendicular to the first tangent vector,
+ // and in the direction of the minimum tangent xyz component
+
+
+ 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]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
+
+ 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)); // 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 === 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++) {
+ // twist a little...
+ normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
+ binormals[i].crossVectors(tangents[i], normals[i]);
+ }
+ }
+
+ return {
+ tangents: tangents,
+ normals: normals,
+ binormals: binormals
+ };
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+ copy(source) {
+ this.arcLengthDivisions = source.arcLengthDivisions;
+ return this;
+ }
+
+ toJSON() {
+ const data = {
+ metadata: {
+ version: 4.5,
+ type: 'Curve',
+ generator: 'Curve.toJSON'
+ }
+ };
+ data.arcLengthDivisions = this.arcLengthDivisions;
+ data.type = this.type;
+ return data;
+ }
+
+ fromJSON(json) {
+ this.arcLengthDivisions = json.arcLengthDivisions;
+ return this;
+ }
+
+}
+
+class EllipseCurve extends Curve {
+ constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
+ super();
+ 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;
+ }
+
+ getPoint(t, optionalTarget) {
+ const point = optionalTarget || new Vector2();
+ const twoPi = Math.PI * 2;
+ let deltaAngle = this.aEndAngle - this.aStartAngle;
+ const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
+
+ 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; // Rotate the point about the center of the ellipse.
+
+ x = tx * cos - ty * sin + this.aX;
+ y = tx * sin + ty * cos + this.aY;
+ }
+
+ return point.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;
+ }
+
+}
+
+EllipseCurve.prototype.isEllipseCurve = true;
+
+class ArcCurve extends EllipseCurve {
+ constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
+ super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
+ this.type = 'ArcCurve';
+ }
+
+}
+
+ArcCurve.prototype.isArcCurve = true;
+
+/**
+ * Centripetal CatmullRom Curve - which is useful for avoiding
+ * cusps and self-intersections in non-uniform catmull rom curves.
+ * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
+ *
+ * curve.type accepts centripetal(default), chordal and catmullrom
+ * curve.tension is used for catmullrom which defaults to 0.5
+ */
+
+/*
+Based on an optimized c++ solution in
+ - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
+ - http://ideone.com/NoEbVM
+
+This CubicPoly class could be used for reusing some variables and calculations,
+but for three.js curve use, it could be possible inlined and flatten into a single function call
+which can be placed in CurveUtils.
+*/
+
+function CubicPoly() {
+ let c0 = 0,
+ c1 = 0,
+ c2 = 0,
+ c3 = 0;
+ /*
+ * Compute coefficients for a cubic polynomial
+ * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
+ * such that
+ * p(0) = x0, p(1) = x1
+ * and
+ * p'(0) = t0, p'(1) = t1.
+ */
+
+ 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) {
+ // compute tangents when parameterized in [t1,t2]
+ let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
+ let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
+
+ 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 = new Vector3();
+const px = new CubicPoly(),
+ py = new CubicPoly(),
+ pz = new CubicPoly();
+
+class CatmullRomCurve3 extends Curve {
+ constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
+ super();
+ this.type = 'CatmullRomCurve3';
+ this.points = points;
+ this.closed = closed;
+ this.curveType = curveType;
+ this.tension = tension;
+ }
+
+ getPoint(t, optionalTarget = new Vector3()) {
+ const point = 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; // 4 points (p1 & p2 defined below)
+
+ if (this.closed || intPoint > 0) {
+ p0 = points[(intPoint - 1) % l];
+ } else {
+ // extrapolate first point
+ tmp.subVectors(points[0], points[1]).add(points[0]);
+ p0 = tmp;
+ }
+
+ const p1 = points[intPoint % l];
+ const p2 = points[(intPoint + 1) % l];
+
+ if (this.closed || intPoint + 2 < l) {
+ p3 = points[(intPoint + 2) % l];
+ } else {
+ // extrapolate last point
+ tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
+ p3 = tmp;
+ }
+
+ if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
+ // init Centripetal / Chordal Catmull-Rom
+ 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); // safety check for repeated points
+
+ if (dt1 < 1e-4) dt1 = 1.0;
+ 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);
+ }
+
+ point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
+ return point;
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.points = [];
+
+ for (let i = 0, l = source.points.length; i < l; i++) {
+ const point = source.points[i];
+ this.points.push(point.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 point = this.points[i];
+ data.points.push(point.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 point = json.points[i];
+ this.points.push(new Vector3().fromArray(point));
+ }
+
+ this.closed = json.closed;
+ this.curveType = json.curveType;
+ this.tension = json.tension;
+ return this;
+ }
+
+}
+
+CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
+
+/**
+ * Bezier Curves formulas obtained from
+ * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
+ */
+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 {
+ constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
+ super();
+ this.type = 'CubicBezierCurve';
+ this.v0 = v0;
+ this.v1 = v1;
+ this.v2 = v2;
+ this.v3 = v3;
+ }
+
+ getPoint(t, optionalTarget = new Vector2()) {
+ const point = optionalTarget;
+ const v0 = this.v0,
+ v1 = this.v1,
+ v2 = this.v2,
+ v3 = this.v3;
+ point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
+ return point;
+ }
+
+ 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;
+ }
+
+}
+
+CubicBezierCurve.prototype.isCubicBezierCurve = true;
+
+class CubicBezierCurve3 extends Curve {
+ constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
+ super();
+ this.type = 'CubicBezierCurve3';
+ this.v0 = v0;
+ this.v1 = v1;
+ this.v2 = v2;
+ this.v3 = v3;
+ }
+
+ getPoint(t, optionalTarget = new Vector3()) {
+ const point = optionalTarget;
+ const v0 = this.v0,
+ v1 = this.v1,
+ v2 = this.v2,
+ v3 = this.v3;
+ point.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 point;
+ }
+
+ 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;
+ }
+
+}
+
+CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
+
+class LineCurve extends Curve {
+ constructor(v1 = new Vector2(), v2 = new Vector2()) {
+ super();
+ this.type = 'LineCurve';
+ this.v1 = v1;
+ this.v2 = v2;
+ }
+
+ getPoint(t, optionalTarget = new Vector2()) {
+ const point = optionalTarget;
+
+ if (t === 1) {
+ point.copy(this.v2);
+ } else {
+ point.copy(this.v2).sub(this.v1);
+ point.multiplyScalar(t).add(this.v1);
+ }
+
+ return point;
+ } // Line curve is linear, so we can overwrite default getPointAt
+
+
+ getPointAt(u, optionalTarget) {
+ return this.getPoint(u, optionalTarget);
+ }
+
+ getTangent(t, optionalTarget) {
+ const tangent = optionalTarget || new Vector2();
+ tangent.copy(this.v2).sub(this.v1).normalize();
+ return tangent;
+ }
+
+ 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;
+ }
+
+}
+
+LineCurve.prototype.isLineCurve = true;
+
+class LineCurve3 extends Curve {
+ constructor(v1 = new Vector3(), v2 = new Vector3()) {
+ super();
+ this.type = 'LineCurve3';
+ this.isLineCurve3 = true;
+ this.v1 = v1;
+ this.v2 = v2;
+ }
+
+ getPoint(t, optionalTarget = new Vector3()) {
+ const point = optionalTarget;
+
+ if (t === 1) {
+ point.copy(this.v2);
+ } else {
+ point.copy(this.v2).sub(this.v1);
+ point.multiplyScalar(t).add(this.v1);
+ }
+
+ return point;
+ } // Line curve is linear, so we can overwrite default getPointAt
+
+
+ getPointAt(u, optionalTarget) {
+ return this.getPoint(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 {
+ constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
+ super();
+ this.type = 'QuadraticBezierCurve';
+ this.v0 = v0;
+ this.v1 = v1;
+ this.v2 = v2;
+ }
+
+ getPoint(t, optionalTarget = new Vector2()) {
+ const point = optionalTarget;
+ const v0 = this.v0,
+ v1 = this.v1,
+ v2 = this.v2;
+ point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
+ return point;
+ }
+
+ 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;
+ }
+
+}
+
+QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
+
+class QuadraticBezierCurve3 extends Curve {
+ constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
+ super();
+ this.type = 'QuadraticBezierCurve3';
+ this.v0 = v0;
+ this.v1 = v1;
+ this.v2 = v2;
+ }
+
+ getPoint(t, optionalTarget = new Vector3()) {
+ const point = optionalTarget;
+ const v0 = this.v0,
+ v1 = this.v1,
+ v2 = this.v2;
+ point.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 point;
+ }
+
+ 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;
+ }
+
+}
+
+QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
+
+class SplineCurve extends Curve {
+ constructor(points = []) {
+ super();
+ this.type = 'SplineCurve';
+ this.points = points;
+ }
+
+ getPoint(t, optionalTarget = new Vector2()) {
+ const point = 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];
+ point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
+ return point;
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.points = [];
+
+ for (let i = 0, l = source.points.length; i < l; i++) {
+ const point = source.points[i];
+ this.points.push(point.clone());
+ }
+
+ return this;
+ }
+
+ toJSON() {
+ const data = super.toJSON();
+ data.points = [];
+
+ for (let i = 0, l = this.points.length; i < l; i++) {
+ const point = this.points[i];
+ data.points.push(point.toArray());
+ }
+
+ return data;
+ }
+
+ fromJSON(json) {
+ super.fromJSON(json);
+ this.points = [];
+
+ for (let i = 0, l = json.points.length; i < l; i++) {
+ const point = json.points[i];
+ this.points.push(new Vector2().fromArray(point));
+ }
+
+ return this;
+ }
+
+}
+
+SplineCurve.prototype.isSplineCurve = true;
+
+var Curves = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ ArcCurve: ArcCurve,
+ CatmullRomCurve3: CatmullRomCurve3,
+ CubicBezierCurve: CubicBezierCurve,
+ CubicBezierCurve3: CubicBezierCurve3,
+ EllipseCurve: EllipseCurve,
+ LineCurve: LineCurve,
+ LineCurve3: LineCurve3,
+ QuadraticBezierCurve: QuadraticBezierCurve,
+ QuadraticBezierCurve3: QuadraticBezierCurve3,
+ SplineCurve: SplineCurve
+});
+
+/**************************************************************
+ * Curved Path - a curve path is simply a array of connected
+ * curves, but retains the api of a curve
+ **************************************************************/
+
+class CurvePath extends Curve {
+ constructor() {
+ super();
+ this.type = 'CurvePath';
+ this.curves = [];
+ this.autoClose = false; // Automatically closes the path
+ }
+
+ add(curve) {
+ this.curves.push(curve);
+ }
+
+ closePath() {
+ // Add a line curve if start and end of lines are not connected
+ const startPoint = this.curves[0].getPoint(0);
+ const endPoint = this.curves[this.curves.length - 1].getPoint(1);
+
+ if (!startPoint.equals(endPoint)) {
+ this.curves.push(new 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')
+
+
+ getPoint(t, optionalTarget) {
+ const d = t * this.getLength();
+ const curveLengths = this.getCurveLengths();
+ let i = 0; // To think about boundaries points.
+
+ 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; // loop where sum != 0, sum > d , sum+1 <d
+ } // We cannot use the default THREE.Curve getPoint() with getLength() because in
+ // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
+ // getPoint() depends on getLength
+
+
+ getLength() {
+ const lens = this.getCurveLengths();
+ return lens[lens.length - 1];
+ } // cacheLengths must be recalculated.
+
+
+ updateArcLengths() {
+ this.needsUpdate = true;
+ this.cacheLengths = null;
+ this.getCurveLengths();
+ } // Compute lengths and cache them
+ // We cannot overwrite getLengths() because UtoT mapping uses it.
+
+
+ getCurveLengths() {
+ // We use cache values if curves and cache array are same length
+ if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
+ return this.cacheLengths;
+ } // Get length of sub-curve
+ // Push sums into cached array
+
+
+ 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 && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
+ const pts = curve.getPoints(resolution);
+
+ for (let j = 0; j < pts.length; j++) {
+ const point = pts[j];
+ if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
+
+ points.push(point);
+ last = point;
+ }
+ }
+
+ 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 {
+ constructor(points) {
+ super();
+ this.type = 'Path';
+ this.currentPoint = new Vector2();
+
+ if (points) {
+ this.setFromPoints(points);
+ }
+ }
+
+ 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;
+ }
+
+ moveTo(x, y) {
+ this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
+
+ return this;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ splineThru(pts
+ /*Array of Vector*/
+ ) {
+ 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;
+ }
+
+ 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;
+ }
+
+ absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
+ this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
+ return this;
+ }
+
+ 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;
+ }
+
+ 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) {
+ // if a previous curve is present, attempt to join
+ 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 {
+ constructor(points) {
+ super(points);
+ this.uuid = generateUUID();
+ this.type = 'Shape';
+ this.holes = [];
+ }
+
+ 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)
+
+
+ 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;
+ }
+
+}
+
+/**
+ * Port from https://github.com/mapbox/earcut (v2.2.2)
+ */
+const Earcut = {
+ triangulate: function (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, maxX, maxY, x, y, invSize;
+ if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
+
+ if (data.length > 80 * dim) {
+ minX = maxX = data[0];
+ minY = maxY = data[1];
+
+ for (let i = dim; i < outerLen; i += dim) {
+ x = data[i];
+ y = data[i + 1];
+ if (x < minX) minX = x;
+ if (y < minY) minY = y;
+ if (x > maxX) maxX = x;
+ if (y > maxY) maxY = y;
+ } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
+
+
+ invSize = Math.max(maxX - minX, maxY - minY);
+ invSize = invSize !== 0 ? 1 / invSize : 0;
+ }
+
+ earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
+ return triangles;
+ }
+}; // create a circular doubly linked list from polygon points in the specified winding order
+
+function linkedList(data, start, end, dim, clockwise) {
+ let i, last;
+
+ if (clockwise === signedArea(data, start, end, dim) > 0) {
+ for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
+ } else {
+ for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
+ }
+
+ if (last && equals(last, last.next)) {
+ removeNode(last);
+ last = last.next;
+ }
+
+ return last;
+} // eliminate colinear or duplicate points
+
+
+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;
+} // main ear slicing loop which triangulates a polygon (given as a linked list)
+
+
+function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
+ if (!ear) return; // interlink polygon nodes in z-order
+
+ if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
+ let stop = ear,
+ prev,
+ next; // iterate through ears, slicing them one by one
+
+ while (ear.prev !== ear.next) {
+ prev = ear.prev;
+ next = ear.next;
+
+ if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
+ // cut off the triangle
+ triangles.push(prev.i / dim);
+ triangles.push(ear.i / dim);
+ triangles.push(next.i / dim);
+ removeNode(ear); // skipping the next vertex leads to less sliver triangles
+
+ ear = next.next;
+ stop = next.next;
+ continue;
+ }
+
+ ear = next; // if we looped through the whole remaining polygon and can't find any more ears
+
+ if (ear === stop) {
+ // try filtering points and slicing again
+ if (!pass) {
+ earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
+ } else if (pass === 1) {
+ ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
+ earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
+ } else if (pass === 2) {
+ splitEarcut(ear, triangles, dim, minX, minY, invSize);
+ }
+
+ break;
+ }
+ }
+} // check whether a polygon node forms a valid ear with adjacent nodes
+
+
+function isEar(ear) {
+ const a = ear.prev,
+ b = ear,
+ c = ear.next;
+ if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
+ // now make sure we don't have other points inside the potential ear
+
+ let p = ear.next.next;
+
+ while (p !== ear.prev) {
+ if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, 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; // reflex, can't be an ear
+ // triangle bbox; min & max are calculated like this for speed
+
+ const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
+ minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
+ maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
+ maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; // z-order range for the current triangle bbox;
+
+ const minZ = zOrder(minTX, minTY, minX, minY, invSize),
+ maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
+ let p = ear.prevZ,
+ n = ear.nextZ; // look for points inside the triangle in both directions
+
+ while (p && p.z >= minZ && n && n.z <= maxZ) {
+ if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
+ p = p.prevZ;
+ if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
+ n = n.nextZ;
+ } // look for remaining points in decreasing z-order
+
+
+ while (p && p.z >= minZ) {
+ if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
+ p = p.prevZ;
+ } // look for remaining points in increasing z-order
+
+
+ while (n && n.z <= maxZ) {
+ if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
+ n = n.nextZ;
+ }
+
+ return true;
+} // go through all polygon nodes and cure small local self-intersections
+
+
+function cureLocalIntersections(start, triangles, dim) {
+ 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 / dim);
+ triangles.push(p.i / dim);
+ triangles.push(b.i / dim); // remove two nodes involved
+
+ removeNode(p);
+ removeNode(p.next);
+ p = start = b;
+ }
+
+ p = p.next;
+ } while (p !== start);
+
+ return filterPoints(p);
+} // try splitting polygon into two and triangulate them independently
+
+
+function splitEarcut(start, triangles, dim, minX, minY, invSize) {
+ // look for a valid diagonal that divides the polygon into two
+ let a = start;
+
+ do {
+ let b = a.next.next;
+
+ while (b !== a.prev) {
+ if (a.i !== b.i && isValidDiagonal(a, b)) {
+ // split the polygon in two by the diagonal
+ let c = splitPolygon(a, b); // filter colinear points around the cuts
+
+ a = filterPoints(a, a.next);
+ c = filterPoints(c, c.next); // run earcut on each half
+
+ earcutLinked(a, triangles, dim, minX, minY, invSize);
+ earcutLinked(c, triangles, dim, minX, minY, invSize);
+ return;
+ }
+
+ b = b.next;
+ }
+
+ a = a.next;
+ } while (a !== start);
+} // link every hole into the outer loop, producing a single-ring polygon without holes
+
+
+function eliminateHoles(data, holeIndices, outerNode, dim) {
+ const queue = [];
+ let i, len, start, end, list;
+
+ for (i = 0, len = holeIndices.length; i < len; i++) {
+ start = holeIndices[i] * dim;
+ end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
+ list = linkedList(data, start, end, dim, false);
+ if (list === list.next) list.steiner = true;
+ queue.push(getLeftmost(list));
+ }
+
+ queue.sort(compareX); // process holes from left to right
+
+ for (i = 0; i < queue.length; i++) {
+ eliminateHole(queue[i], outerNode);
+ outerNode = filterPoints(outerNode, outerNode.next);
+ }
+
+ return outerNode;
+}
+
+function compareX(a, b) {
+ return a.x - b.x;
+} // find a bridge between vertices that connects hole with an outer ring and and link it
+
+
+function eliminateHole(hole, outerNode) {
+ outerNode = findHoleBridge(hole, outerNode);
+
+ if (outerNode) {
+ const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
+
+ filterPoints(outerNode, outerNode.next);
+ filterPoints(b, b.next);
+ }
+} // David Eberly's algorithm for finding a bridge between hole and outer polygon
+
+
+function findHoleBridge(hole, outerNode) {
+ let p = outerNode;
+ const hx = hole.x;
+ const hy = hole.y;
+ let qx = -Infinity,
+ m; // find a segment intersected by a ray from the hole's leftmost point to the left;
+ // segment's endpoint with lesser x will be potential connection point
+
+ do {
+ 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;
+
+ if (x === hx) {
+ if (hy === p.y) return p;
+ if (hy === p.next.y) return p.next;
+ }
+
+ m = p.x < p.next.x ? p : p.next;
+ }
+ }
+
+ p = p.next;
+ } while (p !== outerNode);
+
+ if (!m) return null;
+ if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
+ // look for points inside the triangle of hole point, segment intersection and endpoint;
+ // if there are no points found, we have a valid connection;
+ // otherwise choose the point of the minimum angle with the ray as connection point
+
+ const stop = m,
+ mx = m.x,
+ my = m.y;
+ let tanMin = Infinity,
+ tan;
+ 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)) {
+ tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
+
+ 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;
+} // whether sector in vertex m contains sector in vertex p in the same coordinates
+
+
+function sectorContainsSector(m, p) {
+ return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
+} // interlink polygon nodes in z-order
+
+
+function indexCurve(start, minX, minY, invSize) {
+ let p = start;
+
+ do {
+ if (p.z === null) 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);
+} // Simon Tatham's linked list merge sort algorithm
+// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
+
+
+function sortLinked(list) {
+ let i,
+ p,
+ q,
+ e,
+ tail,
+ numMerges,
+ pSize,
+ qSize,
+ inSize = 1;
+
+ do {
+ p = list;
+ list = null;
+ tail = null;
+ numMerges = 0;
+
+ while (p) {
+ numMerges++;
+ q = p;
+ pSize = 0;
+
+ for (i = 0; i < inSize; i++) {
+ pSize++;
+ q = q.nextZ;
+ if (!q) break;
+ }
+
+ 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;
+} // z-order of a point given coords and inverse of the longer side of data bbox
+
+
+function zOrder(x, y, minX, minY, invSize) {
+ // coords are transformed into non-negative 15-bit integer range
+ x = 32767 * (x - minX) * invSize;
+ y = 32767 * (y - minY) * invSize;
+ x = (x | x << 8) & 0x00FF00FF;
+ x = (x | x << 4) & 0x0F0F0F0F;
+ x = (x | x << 2) & 0x33333333;
+ x = (x | x << 1) & 0x55555555;
+ y = (y | y << 8) & 0x00FF00FF;
+ y = (y | y << 4) & 0x0F0F0F0F;
+ y = (y | y << 2) & 0x33333333;
+ y = (y | y << 1) & 0x55555555;
+ return x | y << 1;
+} // find the leftmost node of a polygon ring
+
+
+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;
+} // check if a point lies within a convex triangle
+
+
+function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
+ return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
+} // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
+
+
+function isValidDiagonal(a, b) {
+ return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones'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); // special zero-length case
+} // signed area of a triangle
+
+
+function area(p, q, r) {
+ return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
+} // check if two points are equal
+
+
+function equals(p1, p2) {
+ return p1.x === p2.x && p1.y === p2.y;
+} // check if two segments intersect
+
+
+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; // general case
+
+ if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
+
+ if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
+
+ if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
+
+ if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
+
+ return false;
+} // for collinear points p, q, r, check if point q lies on segment pr
+
+
+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;
+} // check if a polygon diagonal intersects any polygon segments
+
+
+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;
+} // check if a polygon diagonal is locally inside the polygon
+
+
+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;
+} // check if the middle point of a polygon diagonal is inside the polygon
+
+
+function middleInside(a, b) {
+ let p = a,
+ inside = false;
+ const px = (a.x + b.x) / 2,
+ py = (a.y + b.y) / 2;
+
+ do {
+ if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) inside = !inside;
+ p = p.next;
+ } while (p !== a);
+
+ return inside;
+} // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
+// if one belongs to the outer ring and another to a hole, it merges it into a single ring
+
+
+function splitPolygon(a, b) {
+ const a2 = new Node(a.i, a.x, a.y),
+ b2 = new Node(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;
+} // create a node and optionally link it with previous one (in a circular doubly linked list)
+
+
+function insertNode(i, x, y, last) {
+ const p = new Node(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 Node(i, x, y) {
+ // vertex index in coordinates array
+ this.i = i; // vertex coordinates
+
+ this.x = x;
+ this.y = y; // previous and next vertex nodes in a polygon ring
+
+ this.prev = null;
+ this.next = null; // z-order curve value
+
+ this.z = null; // previous and next nodes in z-order
+
+ this.prevZ = null;
+ this.nextZ = null; // indicates whether this is a steiner point
+
+ this.steiner = false;
+}
+
+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 ShapeUtils {
+ // calculate area of the contour polygon
+ static area(contour) {
+ const n = contour.length;
+ let a = 0.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;
+ }
+
+ static isClockWise(pts) {
+ return ShapeUtils.area(pts) < 0;
+ }
+
+ static triangulateShape(contour, holes) {
+ const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
+
+ const holeIndices = []; // array of hole indices
+
+ const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
+
+ 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);
+ }
+}
+
+/**
+ * Creates extruded geometry from a path shape.
+ *
+ * parameters = {
+ *
+ * curveSegments: <int>, // number of points on the curves
+ * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
+ * depth: <float>, // Depth to extrude the shape
+ *
+ * bevelEnabled: <bool>, // turn on bevel
+ * bevelThickness: <float>, // how deep into the original shape bevel goes
+ * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
+ * bevelOffset: <float>, // how far from shape outline does bevel start
+ * bevelSegments: <int>, // number of bevel layers
+ *
+ * extrudePath: <THREE.Curve> // curve to extrude shape along
+ *
+ * UVGenerator: <Object> // object that provides UV generator functions
+ *
+ * }
+ */
+
+class ExtrudeGeometry extends BufferGeometry {
+ 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: shapes,
+ options: 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);
+ } // build geometry
+
+
+ this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
+ this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
+ this.computeVertexNormals(); // functions
+
+ function addShape(shape) {
+ const placeholder = []; // options
+
+ const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
+ const steps = options.steps !== undefined ? options.steps : 1;
+ let depth = options.depth !== undefined ? options.depth : 1;
+ let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
+ let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
+ let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
+ let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
+ let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
+ const extrudePath = options.extrudePath;
+ const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
+
+ if (options.amount !== undefined) {
+ console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
+ depth = options.amount;
+ } //
+
+
+ let extrudePts,
+ extrudeByPath = false;
+ let splineTube, binormal, normal, position2;
+
+ if (extrudePath) {
+ extrudePts = extrudePath.getSpacedPoints(steps);
+ extrudeByPath = true;
+ bevelEnabled = false; // bevels not supported for path extrusion
+ // SETUP TNB variables
+ // TODO1 - have a .isClosed in spline?
+
+ splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
+
+ binormal = new Vector3();
+ normal = new Vector3();
+ position2 = new Vector3();
+ } // Safeguards if bevels are not enabled
+
+
+ if (!bevelEnabled) {
+ bevelSegments = 0;
+ bevelThickness = 0;
+ bevelSize = 0;
+ bevelOffset = 0;
+ } // Variables initialization
+
+
+ const shapePoints = shape.extractPoints(curveSegments);
+ let vertices = shapePoints.shape;
+ const holes = shapePoints.holes;
+ const reverse = !ShapeUtils.isClockWise(vertices);
+
+ if (reverse) {
+ vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
+
+ for (let h = 0, hl = holes.length; h < hl; h++) {
+ const ahole = holes[h];
+
+ if (ShapeUtils.isClockWise(ahole)) {
+ holes[h] = ahole.reverse();
+ }
+ }
+ }
+
+ const faces = ShapeUtils.triangulateShape(vertices, holes);
+ /* Vertices */
+
+ const contour = vertices; // vertices has all points but contour has only points of circumference
+
+ for (let h = 0, hl = holes.length; h < hl; h++) {
+ const ahole = holes[h];
+ vertices = vertices.concat(ahole);
+ }
+
+ function scalePt2(pt, vec, size) {
+ if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
+ return vec.clone().multiplyScalar(size).add(pt);
+ }
+
+ const vlen = vertices.length,
+ flen = faces.length; // Find directions for point movement
+
+ function getBevelVec(inPt, inPrev, inNext) {
+ // computes for inPt the corresponding point inPt' on a new contour
+ // shifted 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.
+ let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
+ // good reading for geometry algorithms (here: line-line intersection)
+ // http://geomalgorithms.com/a05-_intersect-1.html
+
+ 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; // check for collinear edges
+
+ const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
+
+ if (Math.abs(collinear0) > Number.EPSILON) {
+ // not collinear
+ // length of vectors for normalizing
+ 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); // shift adjacent points by unit vectors to the left
+
+ 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; // scaling factor for v_prev to intersection point
+
+ 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); // 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
+
+ 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 {
+ // handle special case of collinear edges
+ let direction_eq = false; // assumes: opposite
+
+ 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) {
+ // 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 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; // (j)---(i)---(k)
+ // console.log('i,j,k', i, j , k)
+
+ contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
+ }
+
+ const holesMovements = [];
+ let oneHoleMovements,
+ verticesMovements = contourMovements.concat();
+
+ for (let h = 0, hl = holes.length; 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; // (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 (let b = 0; b < bevelSegments; b++) {
+ //for ( b = bevelSegments; b > 0; b -- ) {
+ const t = b / bevelSegments;
+ const z = bevelThickness * Math.cos(t * Math.PI / 2);
+ const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
+
+ for (let i = 0, il = contour.length; i < il; i++) {
+ const vert = scalePt2(contour[i], contourMovements[i], bs);
+ v(vert.x, vert.y, -z);
+ } // expand holes
+
+
+ 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], bs);
+ v(vert.x, vert.y, -z);
+ }
+ }
+ }
+
+ const bs = bevelSize + bevelOffset; // Back facing vertices
+
+ 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 {
+ // 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
+
+
+ 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 {
+ // 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 (let b = bevelSegments - 1; b >= 0; b--) {
+ const t = b / bevelSegments;
+ const z = bevelThickness * Math.cos(t * Math.PI / 2);
+ const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
+
+ for (let i = 0, il = contour.length; i < il; i++) {
+ const vert = scalePt2(contour[i], contourMovements[i], bs);
+ v(vert.x, vert.y, depth + z);
+ } // expand holes
+
+
+ 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], bs);
+
+ if (!extrudeByPath) {
+ v(vert.x, vert.y, depth + 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() {
+ const start = verticesArray.length / 3;
+
+ if (bevelEnabled) {
+ let layer = 0; // steps + 1
+
+ let offset = vlen * layer; // Bottom faces
+
+ for (let i = 0; i < flen; i++) {
+ const face = faces[i];
+ f3(face[2] + offset, face[1] + offset, face[0] + offset);
+ }
+
+ layer = steps + bevelSegments * 2;
+ offset = vlen * layer; // Top faces
+
+ for (let i = 0; i < flen; i++) {
+ const face = faces[i];
+ f3(face[0] + offset, face[1] + offset, face[2] + offset);
+ }
+ } else {
+ // Bottom faces
+ for (let i = 0; i < flen; i++) {
+ const face = faces[i];
+ f3(face[2], face[1], face[0]);
+ } // Top faces
+
+
+ for (let i = 0; i < flen; i++) {
+ const face = faces[i];
+ f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
+ }
+ }
+
+ scope.addGroup(start, verticesArray.length / 3 - start, 0);
+ } // Create faces for the z-sides of the shape
+
+
+ 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); //, true
+
+ layeroffset += ahole.length;
+ }
+
+ scope.addGroup(start, verticesArray.length / 3 - start, 1);
+ }
+
+ function sidewalls(contour, layeroffset) {
+ let i = contour.length;
+
+ while (--i >= 0) {
+ const j = i;
+ let k = i - 1;
+ if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
+
+ 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);
+ }
+ }
+ }
+
+ toJSON() {
+ const data = super.toJSON();
+ const shapes = this.parameters.shapes;
+ const options = this.parameters.options;
+ return toJSON$1(shapes, options, data);
+ }
+
+ 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 !== undefined) {
+ 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);
+ }
+
+ if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
+ return data;
+}
+
+class IcosahedronGeometry extends PolyhedronGeometry {
+ 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: radius,
+ detail: detail
+ };
+ }
+
+ static fromJSON(data) {
+ return new IcosahedronGeometry(data.radius, data.detail);
+ }
+
+}
+
+class LatheGeometry extends BufferGeometry {
+ 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: points,
+ segments: segments,
+ phiStart: phiStart,
+ phiLength: phiLength
+ };
+ segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
+
+ phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
+
+ const indices = [];
+ const vertices = [];
+ const uvs = [];
+ const initNormals = [];
+ const normals = []; // helper variables
+
+ const inverseSegments = 1.0 / segments;
+ const vertex = new Vector3();
+ const uv = new Vector2();
+ const normal = new Vector3();
+ const curNormal = new Vector3();
+ const prevNormal = new Vector3();
+ let dx = 0;
+ let dy = 0; // pre-compute normals for initial "meridian"
+
+ for (let j = 0; j <= points.length - 1; j++) {
+ switch (j) {
+ case 0:
+ // special handling for 1st vertex on path
+ dx = points[j + 1].x - points[j].x;
+ dy = points[j + 1].y - points[j].y;
+ normal.x = dy * 1.0;
+ normal.y = -dx;
+ normal.z = dy * 0.0;
+ prevNormal.copy(normal);
+ normal.normalize();
+ initNormals.push(normal.x, normal.y, normal.z);
+ break;
+
+ case points.length - 1:
+ // special handling for last Vertex on path
+ initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z);
+ break;
+
+ default:
+ // default handling for all vertices in between
+ dx = points[j + 1].x - points[j].x;
+ dy = points[j + 1].y - points[j].y;
+ normal.x = dy * 1.0;
+ normal.y = -dx;
+ normal.z = dy * 0.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);
+ }
+ } // generate vertices, uvs and normals
+
+
+ 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++) {
+ // vertex
+ vertex.x = points[j].x * sin;
+ vertex.y = points[j].y;
+ vertex.z = points[j].x * cos;
+ vertices.push(vertex.x, vertex.y, vertex.z); // uv
+
+ uv.x = i / segments;
+ uv.y = j / (points.length - 1);
+ uvs.push(uv.x, uv.y); // normal
+
+ 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);
+ }
+ } // indices
+
+
+ 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; // faces
+
+ indices.push(a, b, d);
+ indices.push(c, d, b);
+ }
+ } // build geometry
+
+
+ this.setIndex(indices);
+ this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
+ this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
+ this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
+ }
+
+ static fromJSON(data) {
+ return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
+ }
+
+}
+
+class OctahedronGeometry extends PolyhedronGeometry {
+ 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: radius,
+ detail: detail
+ };
+ }
+
+ static fromJSON(data) {
+ return new OctahedronGeometry(data.radius, data.detail);
+ }
+
+}
+
+class RingGeometry extends BufferGeometry {
+ constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
+ super();
+ this.type = 'RingGeometry';
+ this.parameters = {
+ innerRadius: innerRadius,
+ outerRadius: outerRadius,
+ thetaSegments: thetaSegments,
+ phiSegments: phiSegments,
+ thetaStart: thetaStart,
+ thetaLength: thetaLength
+ };
+ thetaSegments = Math.max(3, thetaSegments);
+ phiSegments = Math.max(1, phiSegments); // buffers
+
+ const indices = [];
+ const vertices = [];
+ const normals = [];
+ const uvs = []; // some helper variables
+
+ let radius = innerRadius;
+ const radiusStep = (outerRadius - innerRadius) / phiSegments;
+ const vertex = new Vector3();
+ const uv = new Vector2(); // generate vertices, normals and uvs
+
+ for (let j = 0; j <= phiSegments; j++) {
+ for (let i = 0; i <= thetaSegments; i++) {
+ // values are generate from the inside of the ring to the outside
+ const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
+
+ vertex.x = radius * Math.cos(segment);
+ vertex.y = radius * Math.sin(segment);
+ vertices.push(vertex.x, vertex.y, vertex.z); // normal
+
+ normals.push(0, 0, 1); // uv
+
+ uv.x = (vertex.x / outerRadius + 1) / 2;
+ uv.y = (vertex.y / outerRadius + 1) / 2;
+ uvs.push(uv.x, uv.y);
+ } // increase the radius for next row of vertices
+
+
+ radius += radiusStep;
+ } // indices
+
+
+ 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; // faces
+
+ indices.push(a, b, d);
+ indices.push(b, c, d);
+ }
+ } // build geometry
+
+
+ this.setIndex(indices);
+ this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
+ this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
+ this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
+ }
+
+ static fromJSON(data) {
+ return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
+ }
+
+}
+
+class ShapeGeometry extends BufferGeometry {
+ 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: shapes,
+ curveSegments: curveSegments
+ }; // buffers
+
+ const indices = [];
+ const vertices = [];
+ const normals = [];
+ const uvs = []; // helper variables
+
+ let groupStart = 0;
+ let groupCount = 0; // allow single and array values for "shapes" parameter
+
+ if (Array.isArray(shapes) === false) {
+ addShape(shapes);
+ } else {
+ for (let i = 0; i < shapes.length; i++) {
+ addShape(shapes[i]);
+ this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
+
+ groupStart += groupCount;
+ groupCount = 0;
+ }
+ } // build geometry
+
+
+ this.setIndex(indices);
+ this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
+ this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
+ this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
+
+ function addShape(shape) {
+ const indexOffset = vertices.length / 3;
+ const points = shape.extractPoints(curveSegments);
+ let shapeVertices = points.shape;
+ const shapeHoles = points.holes; // check direction of vertices
+
+ 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); // join vertices of inner and outer paths to a single array
+
+ for (let i = 0, l = shapeHoles.length; i < l; i++) {
+ const shapeHole = shapeHoles[i];
+ shapeVertices = shapeVertices.concat(shapeHole);
+ } // vertices, normals, uvs
+
+
+ for (let i = 0, l = shapeVertices.length; i < l; i++) {
+ const vertex = shapeVertices[i];
+ vertices.push(vertex.x, vertex.y, 0);
+ normals.push(0, 0, 1);
+ uvs.push(vertex.x, vertex.y); // world uvs
+ } // incides
+
+
+ for (let i = 0, l = faces.length; i < l; i++) {
+ const face = faces[i];
+ const a = face[0] + indexOffset;
+ const b = face[1] + indexOffset;
+ const c = face[2] + indexOffset;
+ indices.push(a, b, c);
+ groupCount += 3;
+ }
+ }
+ }
+
+ toJSON() {
+ const data = super.toJSON();
+ const shapes = this.parameters.shapes;
+ return toJSON(shapes, data);
+ }
+
+ 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 {
+ 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: radius,
+ widthSegments: widthSegments,
+ heightSegments: heightSegments,
+ phiStart: phiStart,
+ phiLength: phiLength,
+ thetaStart: thetaStart,
+ thetaLength: 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 vertex = new Vector3();
+ const normal = new Vector3(); // buffers
+
+ const indices = [];
+ const vertices = [];
+ const normals = [];
+ const uvs = []; // generate vertices, normals and uvs
+
+ for (let iy = 0; iy <= heightSegments; iy++) {
+ const verticesRow = [];
+ const v = iy / heightSegments; // special case for the poles
+
+ 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; // vertex
+
+ 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);
+ vertices.push(vertex.x, vertex.y, vertex.z); // normal
+
+ normal.copy(vertex).normalize();
+ normals.push(normal.x, normal.y, normal.z); // uv
+
+ uvs.push(u + uOffset, 1 - v);
+ verticesRow.push(index++);
+ }
+
+ grid.push(verticesRow);
+ } // indices
+
+
+ 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);
+ }
+ } // build geometry
+
+
+ this.setIndex(indices);
+ this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
+ this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
+ this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
+ }
+
+ static fromJSON(data) {
+ return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
+ }
+
+}
+
+class TetrahedronGeometry extends PolyhedronGeometry {
+ 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: radius,
+ detail: detail
+ };
+ }
+
+ static fromJSON(data) {
+ return new TetrahedronGeometry(data.radius, data.detail);
+ }
+
+}
+
+class TorusGeometry extends BufferGeometry {
+ constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
+ super();
+ this.type = 'TorusGeometry';
+ this.parameters = {
+ radius: radius,
+ tube: tube,
+ radialSegments: radialSegments,
+ tubularSegments: tubularSegments,
+ arc: arc
+ };
+ radialSegments = Math.floor(radialSegments);
+ tubularSegments = Math.floor(tubularSegments); // buffers
+
+ const indices = [];
+ const vertices = [];
+ const normals = [];
+ const uvs = []; // helper variables
+
+ const center = new Vector3();
+ const vertex = new Vector3();
+ const normal = new Vector3(); // generate vertices, normals and uvs
+
+ for (let j = 0; j <= radialSegments; j++) {
+ for (let i = 0; i <= tubularSegments; i++) {
+ const u = i / tubularSegments * arc;
+ const v = j / radialSegments * Math.PI * 2; // vertex
+
+ vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
+ vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
+ vertex.z = tube * Math.sin(v);
+ vertices.push(vertex.x, vertex.y, vertex.z); // normal
+
+ center.x = radius * Math.cos(u);
+ center.y = radius * Math.sin(u);
+ normal.subVectors(vertex, center).normalize();
+ normals.push(normal.x, normal.y, normal.z); // uv
+
+ uvs.push(i / tubularSegments);
+ uvs.push(j / radialSegments);
+ }
+ } // generate indices
+
+
+ for (let j = 1; j <= radialSegments; j++) {
+ for (let i = 1; i <= tubularSegments; i++) {
+ // indices
+ 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; // faces
+
+ indices.push(a, b, d);
+ indices.push(b, c, d);
+ }
+ } // build geometry
+
+
+ this.setIndex(indices);
+ this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
+ this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
+ this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
+ }
+
+ static fromJSON(data) {
+ return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
+ }
+
+}
+
+class TorusKnotGeometry extends BufferGeometry {
+ constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
+ super();
+ this.type = 'TorusKnotGeometry';
+ this.parameters = {
+ radius: radius,
+ tube: tube,
+ tubularSegments: tubularSegments,
+ radialSegments: radialSegments,
+ p: p,
+ q: q
+ };
+ tubularSegments = Math.floor(tubularSegments);
+ radialSegments = Math.floor(radialSegments); // buffers
+
+ const indices = [];
+ const vertices = [];
+ const normals = [];
+ const uvs = []; // helper variables
+
+ const vertex = new Vector3();
+ const normal = new Vector3();
+ const P1 = new Vector3();
+ const P2 = new Vector3();
+ const B = new Vector3();
+ const T = new Vector3();
+ const N = new Vector3(); // generate vertices, normals and uvs
+
+ for (let i = 0; i <= tubularSegments; ++i) {
+ // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
+ const u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
+ // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
+
+ calculatePositionOnCurve(u, p, q, radius, P1);
+ calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
+
+ T.subVectors(P2, P1);
+ N.addVectors(P2, P1);
+ B.crossVectors(T, N);
+ N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
+
+ B.normalize();
+ N.normalize();
+
+ for (let j = 0; j <= radialSegments; ++j) {
+ // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
+ // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
+ const v = j / radialSegments * Math.PI * 2;
+ const cx = -tube * Math.cos(v);
+ const cy = tube * Math.sin(v); // now calculate the final vertex position.
+ // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
+
+ vertex.x = P1.x + (cx * N.x + cy * B.x);
+ vertex.y = P1.y + (cx * N.y + cy * B.y);
+ vertex.z = P1.z + (cx * N.z + cy * B.z);
+ vertices.push(vertex.x, vertex.y, vertex.z); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
+
+ normal.subVectors(vertex, P1).normalize();
+ normals.push(normal.x, normal.y, normal.z); // uv
+
+ uvs.push(i / tubularSegments);
+ uvs.push(j / radialSegments);
+ }
+ } // generate indices
+
+
+ for (let j = 1; j <= tubularSegments; j++) {
+ for (let i = 1; i <= radialSegments; i++) {
+ // indices
+ 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; // faces
+
+ indices.push(a, b, d);
+ indices.push(b, c, d);
+ }
+ } // build geometry
+
+
+ this.setIndex(indices);
+ this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
+ this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
+ this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
+
+ function calculatePositionOnCurve(u, p, q, radius, position) {
+ const cu = Math.cos(u);
+ const su = Math.sin(u);
+ const quOverP = q / p * u;
+ const cs = Math.cos(quOverP);
+ position.x = radius * (2 + cs) * 0.5 * cu;
+ position.y = radius * (2 + cs) * su * 0.5;
+ position.z = radius * Math.sin(quOverP) * 0.5;
+ }
+ }
+
+ static fromJSON(data) {
+ return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
+ }
+
+}
+
+class TubeGeometry extends BufferGeometry {
+ 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: path,
+ tubularSegments: tubularSegments,
+ radius: radius,
+ radialSegments: radialSegments,
+ closed: closed
+ };
+ const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
+
+ this.tangents = frames.tangents;
+ this.normals = frames.normals;
+ this.binormals = frames.binormals; // helper variables
+
+ const vertex = new Vector3();
+ const normal = new Vector3();
+ const uv = new Vector2();
+ let P = new Vector3(); // buffer
+
+ const vertices = [];
+ const normals = [];
+ const uvs = [];
+ const indices = []; // create buffer data
+
+ generateBufferData(); // build geometry
+
+ this.setIndex(indices);
+ this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
+ this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
+ this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
+
+ function generateBufferData() {
+ for (let i = 0; i < tubularSegments; i++) {
+ generateSegment(i);
+ } // if the geometry is not closed, generate the last row of vertices and normals
+ // at the regular position on the given path
+ //
+ // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
+
+
+ generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
+ // this makes it easy compute correct values for closed geometries
+
+ generateUVs(); // finally create faces
+
+ generateIndices();
+ }
+
+ function generateSegment(i) {
+ // we use getPointAt to sample evenly distributed points from the given path
+ P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
+
+ const N = frames.normals[i];
+ const B = frames.binormals[i]; // generate normals and vertices for the current segment
+
+ 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
+
+ normal.x = cos * N.x + sin * B.x;
+ normal.y = cos * N.y + sin * B.y;
+ normal.z = cos * N.z + sin * B.z;
+ normal.normalize();
+ normals.push(normal.x, normal.y, normal.z); // vertex
+
+ vertex.x = P.x + radius * normal.x;
+ vertex.y = P.y + radius * normal.y;
+ vertex.z = P.z + radius * normal.z;
+ vertices.push(vertex.x, vertex.y, vertex.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; // faces
+
+ 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);
+ }
+ }
+ }
+ }
+
+ toJSON() {
+ const data = super.toJSON();
+ data.path = this.parameters.path.toJSON();
+ return data;
+ }
+
+ static fromJSON(data) {
+ // This only works for built-in curves (e.g. CatmullRomCurve3).
+ // User defined curves or instances of CurvePath will not be deserialized.
+ return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
+ }
+
+}
+
+class WireframeGeometry extends BufferGeometry {
+ constructor(geometry = null) {
+ super();
+ this.type = 'WireframeGeometry';
+ this.parameters = {
+ geometry: geometry
+ };
+
+ if (geometry !== null) {
+ // buffer
+ const vertices = [];
+ const edges = new Set(); // helper variables
+
+ const start = new Vector3();
+ const end = new Vector3();
+
+ if (geometry.index !== null) {
+ // indexed BufferGeometry
+ 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
+ }];
+ } // create a data structure that contains all eges without duplicates
+
+
+ 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 {
+ // non-indexed BufferGeometry
+ const position = geometry.attributes.position;
+
+ for (let i = 0, l = position.count / 3; i < l; i++) {
+ for (let j = 0; j < 3; j++) {
+ // three edges per triangle, an edge is represented as (index1, index2)
+ // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
+ 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);
+ }
+ }
+ }
+ } // build geometry
+
+
+ this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
+ }
+ }
+
+}
+
+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}`; // coincident edge
+
+ if (edges.has(hash1) === true || edges.has(hash2) === true) {
+ return false;
+ } else {
+ edges.add(hash1, hash2);
+ return true;
+ }
+}
+
+var Geometries = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ BoxGeometry: BoxGeometry,
+ BoxBufferGeometry: BoxGeometry,
+ CircleGeometry: CircleGeometry,
+ CircleBufferGeometry: CircleGeometry,
+ ConeGeometry: ConeGeometry,
+ ConeBufferGeometry: ConeGeometry,
+ CylinderGeometry: CylinderGeometry,
+ CylinderBufferGeometry: CylinderGeometry,
+ DodecahedronGeometry: DodecahedronGeometry,
+ DodecahedronBufferGeometry: DodecahedronGeometry,
+ EdgesGeometry: EdgesGeometry,
+ ExtrudeGeometry: ExtrudeGeometry,
+ ExtrudeBufferGeometry: ExtrudeGeometry,
+ IcosahedronGeometry: IcosahedronGeometry,
+ IcosahedronBufferGeometry: IcosahedronGeometry,
+ LatheGeometry: LatheGeometry,
+ LatheBufferGeometry: LatheGeometry,
+ OctahedronGeometry: OctahedronGeometry,
+ OctahedronBufferGeometry: OctahedronGeometry,
+ PlaneGeometry: PlaneGeometry,
+ PlaneBufferGeometry: PlaneGeometry,
+ PolyhedronGeometry: PolyhedronGeometry,
+ PolyhedronBufferGeometry: PolyhedronGeometry,
+ RingGeometry: RingGeometry,
+ RingBufferGeometry: RingGeometry,
+ ShapeGeometry: ShapeGeometry,
+ ShapeBufferGeometry: ShapeGeometry,
+ SphereGeometry: SphereGeometry,
+ SphereBufferGeometry: SphereGeometry,
+ TetrahedronGeometry: TetrahedronGeometry,
+ TetrahedronBufferGeometry: TetrahedronGeometry,
+ TorusGeometry: TorusGeometry,
+ TorusBufferGeometry: TorusGeometry,
+ TorusKnotGeometry: TorusKnotGeometry,
+ TorusKnotBufferGeometry: TorusKnotGeometry,
+ TubeGeometry: TubeGeometry,
+ TubeBufferGeometry: TubeGeometry,
+ WireframeGeometry: WireframeGeometry
+});
+
+/**
+ * parameters = {
+ * color: <THREE.Color>
+ * }
+ */
+
+class ShadowMaterial extends Material {
+ constructor(parameters) {
+ super();
+ this.type = 'ShadowMaterial';
+ this.color = new Color(0x000000);
+ this.transparent = true;
+ this.setValues(parameters);
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.color.copy(source.color);
+ return this;
+ }
+
+}
+
+ShadowMaterial.prototype.isShadowMaterial = true;
+
+/**
+ * parameters = {
+ * color: <hex>,
+ * roughness: <float>,
+ * metalness: <float>,
+ * opacity: <float>,
+ *
+ * map: new THREE.Texture( <Image> ),
+ *
+ * lightMap: new THREE.Texture( <Image> ),
+ * lightMapIntensity: <float>
+ *
+ * aoMap: new THREE.Texture( <Image> ),
+ * aoMapIntensity: <float>
+ *
+ * emissive: <hex>,
+ * emissiveIntensity: <float>
+ * emissiveMap: new THREE.Texture( <Image> ),
+ *
+ * bumpMap: new THREE.Texture( <Image> ),
+ * bumpScale: <float>,
+ *
+ * normalMap: new THREE.Texture( <Image> ),
+ * normalMapType: THREE.TangentSpaceNormalMap,
+ * normalScale: <Vector2>,
+ *
+ * displacementMap: new THREE.Texture( <Image> ),
+ * displacementScale: <float>,
+ * displacementBias: <float>,
+ *
+ * roughnessMap: new THREE.Texture( <Image> ),
+ *
+ * metalnessMap: new THREE.Texture( <Image> ),
+ *
+ * alphaMap: new THREE.Texture( <Image> ),
+ *
+ * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
+ * envMapIntensity: <float>
+ *
+ * refractionRatio: <float>,
+ *
+ * wireframe: <boolean>,
+ * wireframeLinewidth: <float>,
+ *
+ * flatShading: <bool>
+ * }
+ */
+
+class MeshStandardMaterial extends Material {
+ constructor(parameters) {
+ super();
+ this.defines = {
+ 'STANDARD': ''
+ };
+ this.type = 'MeshStandardMaterial';
+ this.color = new Color(0xffffff); // diffuse
+
+ this.roughness = 1.0;
+ this.metalness = 0.0;
+ this.map = null;
+ this.lightMap = null;
+ this.lightMapIntensity = 1.0;
+ this.aoMap = null;
+ this.aoMapIntensity = 1.0;
+ this.emissive = new Color(0x000000);
+ this.emissiveIntensity = 1.0;
+ 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.envMapIntensity = 1.0;
+ this.refractionRatio = 0.98;
+ this.wireframe = false;
+ this.wireframeLinewidth = 1;
+ this.wireframeLinecap = 'round';
+ this.wireframeLinejoin = 'round';
+ this.flatShading = false;
+ 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.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;
+ return this;
+ }
+
+}
+
+MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
+
+/**
+ * parameters = {
+ * clearcoat: <float>,
+ * clearcoatMap: new THREE.Texture( <Image> ),
+ * clearcoatRoughness: <float>,
+ * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
+ * clearcoatNormalScale: <Vector2>,
+ * clearcoatNormalMap: new THREE.Texture( <Image> ),
+ *
+ * ior: <float>,
+ * reflectivity: <float>,
+ *
+ * sheen: <float>,
+ * sheenColor: <Color>,
+ * sheenColorMap: new THREE.Texture( <Image> ),
+ * sheenRoughness: <float>,
+ * sheenRoughnessMap: new THREE.Texture( <Image> ),
+ *
+ * transmission: <float>,
+ * transmissionMap: new THREE.Texture( <Image> ),
+ *
+ * thickness: <float>,
+ * thicknessMap: new THREE.Texture( <Image> ),
+ * attenuationDistance: <float>,
+ * attenuationColor: <Color>,
+ *
+ * specularIntensity: <float>,
+ * specularIntensityMap: new THREE.Texture( <Image> ),
+ * specularColor: <Color>,
+ * specularColorMap: new THREE.Texture( <Image> )
+ * }
+ */
+
+class MeshPhysicalMaterial extends MeshStandardMaterial {
+ constructor(parameters) {
+ super();
+ this.defines = {
+ 'STANDARD': '',
+ 'PHYSICAL': ''
+ };
+ this.type = 'MeshPhysicalMaterial';
+ this.clearcoatMap = null;
+ this.clearcoatRoughness = 0.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.sheenColor = new Color(0x000000);
+ this.sheenColorMap = null;
+ this.sheenRoughness = 1.0;
+ this.sheenRoughnessMap = null;
+ this.transmissionMap = null;
+ this.thickness = 0;
+ this.thicknessMap = null;
+ this.attenuationDistance = 0.0;
+ this.attenuationColor = new Color(1, 1, 1);
+ this.specularIntensity = 1.0;
+ this.specularIntensityMap = null;
+ this.specularColor = new Color(1, 1, 1);
+ this.specularColorMap = null;
+ this._sheen = 0.0;
+ this._clearcoat = 0;
+ this._transmission = 0;
+ this.setValues(parameters);
+ }
+
+ get sheen() {
+ return this._sheen;
+ }
+
+ set sheen(value) {
+ if (this._sheen > 0 !== value > 0) {
+ this.version++;
+ }
+
+ this._sheen = value;
+ }
+
+ get clearcoat() {
+ return this._clearcoat;
+ }
+
+ set clearcoat(value) {
+ if (this._clearcoat > 0 !== value > 0) {
+ this.version++;
+ }
+
+ this._clearcoat = value;
+ }
+
+ 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.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.ior = source.ior;
+ 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;
+ }
+
+}
+
+MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
+
+/**
+ * parameters = {
+ * color: <hex>,
+ * specular: <hex>,
+ * shininess: <float>,
+ * opacity: <float>,
+ *
+ * map: new THREE.Texture( <Image> ),
+ *
+ * lightMap: new THREE.Texture( <Image> ),
+ * lightMapIntensity: <float>
+ *
+ * aoMap: new THREE.Texture( <Image> ),
+ * aoMapIntensity: <float>
+ *
+ * emissive: <hex>,
+ * emissiveIntensity: <float>
+ * emissiveMap: new THREE.Texture( <Image> ),
+ *
+ * bumpMap: new THREE.Texture( <Image> ),
+ * bumpScale: <float>,
+ *
+ * normalMap: new THREE.Texture( <Image> ),
+ * normalMapType: THREE.TangentSpaceNormalMap,
+ * normalScale: <Vector2>,
+ *
+ * displacementMap: new THREE.Texture( <Image> ),
+ * displacementScale: <float>,
+ * displacementBias: <float>,
+ *
+ * specularMap: new THREE.Texture( <Image> ),
+ *
+ * alphaMap: new THREE.Texture( <Image> ),
+ *
+ * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
+ * combine: THREE.MultiplyOperation,
+ * reflectivity: <float>,
+ * refractionRatio: <float>,
+ *
+ * wireframe: <boolean>,
+ * wireframeLinewidth: <float>,
+ *
+ * flatShading: <bool>
+ * }
+ */
+
+class MeshPhongMaterial extends Material {
+ constructor(parameters) {
+ super();
+ this.type = 'MeshPhongMaterial';
+ this.color = new Color(0xffffff); // diffuse
+
+ this.specular = new Color(0x111111);
+ this.shininess = 30;
+ this.map = null;
+ this.lightMap = null;
+ this.lightMapIntensity = 1.0;
+ this.aoMap = null;
+ this.aoMapIntensity = 1.0;
+ this.emissive = new Color(0x000000);
+ this.emissiveIntensity = 1.0;
+ 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.combine = MultiplyOperation;
+ this.reflectivity = 1;
+ this.refractionRatio = 0.98;
+ this.wireframe = false;
+ this.wireframeLinewidth = 1;
+ this.wireframeLinecap = 'round';
+ this.wireframeLinejoin = 'round';
+ this.flatShading = false;
+ 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.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.flatShading = source.flatShading;
+ return this;
+ }
+
+}
+
+MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
+
+/**
+ * parameters = {
+ * color: <hex>,
+ *
+ * map: new THREE.Texture( <Image> ),
+ * gradientMap: new THREE.Texture( <Image> ),
+ *
+ * lightMap: new THREE.Texture( <Image> ),
+ * lightMapIntensity: <float>
+ *
+ * aoMap: new THREE.Texture( <Image> ),
+ * aoMapIntensity: <float>
+ *
+ * emissive: <hex>,
+ * emissiveIntensity: <float>
+ * emissiveMap: new THREE.Texture( <Image> ),
+ *
+ * bumpMap: new THREE.Texture( <Image> ),
+ * bumpScale: <float>,
+ *
+ * normalMap: new THREE.Texture( <Image> ),
+ * normalMapType: THREE.TangentSpaceNormalMap,
+ * normalScale: <Vector2>,
+ *
+ * displacementMap: new THREE.Texture( <Image> ),
+ * displacementScale: <float>,
+ * displacementBias: <float>,
+ *
+ * alphaMap: new THREE.Texture( <Image> ),
+ *
+ * wireframe: <boolean>,
+ * wireframeLinewidth: <float>,
+ *
+ * }
+ */
+
+class MeshToonMaterial extends Material {
+ constructor(parameters) {
+ super();
+ this.defines = {
+ 'TOON': ''
+ };
+ this.type = 'MeshToonMaterial';
+ this.color = new Color(0xffffff);
+ this.map = null;
+ this.gradientMap = null;
+ this.lightMap = null;
+ this.lightMapIntensity = 1.0;
+ this.aoMap = null;
+ this.aoMapIntensity = 1.0;
+ this.emissive = new Color(0x000000);
+ this.emissiveIntensity = 1.0;
+ 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.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;
+ return this;
+ }
+
+}
+
+MeshToonMaterial.prototype.isMeshToonMaterial = true;
+
+/**
+ * parameters = {
+ * opacity: <float>,
+ *
+ * bumpMap: new THREE.Texture( <Image> ),
+ * bumpScale: <float>,
+ *
+ * normalMap: new THREE.Texture( <Image> ),
+ * normalMapType: THREE.TangentSpaceNormalMap,
+ * normalScale: <Vector2>,
+ *
+ * displacementMap: new THREE.Texture( <Image> ),
+ * displacementScale: <float>,
+ * displacementBias: <float>,
+ *
+ * wireframe: <boolean>,
+ * wireframeLinewidth: <float>
+ *
+ * flatShading: <bool>
+ * }
+ */
+
+class MeshNormalMaterial extends Material {
+ constructor(parameters) {
+ super();
+ 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.fog = false;
+ 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;
+ }
+
+}
+
+MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
+
+/**
+ * parameters = {
+ * color: <hex>,
+ * opacity: <float>,
+ *
+ * map: new THREE.Texture( <Image> ),
+ *
+ * lightMap: new THREE.Texture( <Image> ),
+ * lightMapIntensity: <float>
+ *
+ * aoMap: new THREE.Texture( <Image> ),
+ * aoMapIntensity: <float>
+ *
+ * emissive: <hex>,
+ * emissiveIntensity: <float>
+ * emissiveMap: new THREE.Texture( <Image> ),
+ *
+ * specularMap: new THREE.Texture( <Image> ),
+ *
+ * alphaMap: new THREE.Texture( <Image> ),
+ *
+ * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
+ * combine: THREE.Multiply,
+ * reflectivity: <float>,
+ * refractionRatio: <float>,
+ *
+ * wireframe: <boolean>,
+ * wireframeLinewidth: <float>,
+ *
+ * }
+ */
+
+class MeshLambertMaterial extends Material {
+ constructor(parameters) {
+ super();
+ this.type = 'MeshLambertMaterial';
+ this.color = new Color(0xffffff); // diffuse
+
+ this.map = null;
+ this.lightMap = null;
+ this.lightMapIntensity = 1.0;
+ this.aoMap = null;
+ this.aoMapIntensity = 1.0;
+ this.emissive = new Color(0x000000);
+ this.emissiveIntensity = 1.0;
+ this.emissiveMap = null;
+ this.specularMap = null;
+ this.alphaMap = null;
+ this.envMap = null;
+ this.combine = MultiplyOperation;
+ this.reflectivity = 1;
+ this.refractionRatio = 0.98;
+ this.wireframe = false;
+ this.wireframeLinewidth = 1;
+ this.wireframeLinecap = 'round';
+ this.wireframeLinejoin = 'round';
+ 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.specularMap = source.specularMap;
+ this.alphaMap = source.alphaMap;
+ this.envMap = source.envMap;
+ 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;
+ return this;
+ }
+
+}
+
+MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
+
+/**
+ * parameters = {
+ * color: <hex>,
+ * opacity: <float>,
+ *
+ * matcap: new THREE.Texture( <Image> ),
+ *
+ * map: new THREE.Texture( <Image> ),
+ *
+ * bumpMap: new THREE.Texture( <Image> ),
+ * bumpScale: <float>,
+ *
+ * normalMap: new THREE.Texture( <Image> ),
+ * normalMapType: THREE.TangentSpaceNormalMap,
+ * normalScale: <Vector2>,
+ *
+ * displacementMap: new THREE.Texture( <Image> ),
+ * displacementScale: <float>,
+ * displacementBias: <float>,
+ *
+ * alphaMap: new THREE.Texture( <Image> ),
+ *
+ * flatShading: <bool>
+ * }
+ */
+
+class MeshMatcapMaterial extends Material {
+ constructor(parameters) {
+ super();
+ this.defines = {
+ 'MATCAP': ''
+ };
+ this.type = 'MeshMatcapMaterial';
+ this.color = new Color(0xffffff); // diffuse
+
+ 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.flatShading = false;
+ 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.flatShading = source.flatShading;
+ return this;
+ }
+
+}
+
+MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
+
+/**
+ * parameters = {
+ * color: <hex>,
+ * opacity: <float>,
+ *
+ * linewidth: <float>,
+ *
+ * scale: <float>,
+ * dashSize: <float>,
+ * gapSize: <float>
+ * }
+ */
+
+class LineDashedMaterial extends LineBasicMaterial {
+ constructor(parameters) {
+ super();
+ 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;
+ }
+
+}
+
+LineDashedMaterial.prototype.isLineDashedMaterial = true;
+
+var Materials = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ ShadowMaterial: ShadowMaterial,
+ SpriteMaterial: SpriteMaterial,
+ RawShaderMaterial: RawShaderMaterial,
+ ShaderMaterial: ShaderMaterial,
+ PointsMaterial: PointsMaterial,
+ MeshPhysicalMaterial: MeshPhysicalMaterial,
+ MeshStandardMaterial: MeshStandardMaterial,
+ MeshPhongMaterial: MeshPhongMaterial,
+ MeshToonMaterial: MeshToonMaterial,
+ MeshNormalMaterial: MeshNormalMaterial,
+ MeshLambertMaterial: MeshLambertMaterial,
+ MeshDepthMaterial: MeshDepthMaterial,
+ MeshDistanceMaterial: MeshDistanceMaterial,
+ MeshBasicMaterial: MeshBasicMaterial,
+ MeshMatcapMaterial: MeshMatcapMaterial,
+ LineDashedMaterial: LineDashedMaterial,
+ LineBasicMaterial: LineBasicMaterial,
+ Material: Material
+});
+
+const AnimationUtils = {
+ // same as Array.prototype.slice, but also works on typed arrays
+ arraySlice: function (array, from, to) {
+ if (AnimationUtils.isTypedArray(array)) {
+ // in ios9 array.subarray(from, undefined) will return empty array
+ // but array.subarray(from) or array.subarray(from, len) is correct
+ return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
+ }
+
+ return array.slice(from, to);
+ },
+ // converts an array to a specific type
+ convertArray: function (array, type, forceClone) {
+ if (!array || // let 'undefined' and 'null' pass
+ !forceClone && array.constructor === type) return array;
+
+ if (typeof type.BYTES_PER_ELEMENT === 'number') {
+ return new type(array); // create typed array
+ }
+
+ return Array.prototype.slice.call(array); // create Array
+ },
+ isTypedArray: function (object) {
+ return ArrayBuffer.isView(object) && !(object instanceof DataView);
+ },
+ // returns an array by which times and values can be sorted
+ getKeyframeOrder: function (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;
+ },
+ // uses the array previously returned by 'getKeyframeOrder' to sort data
+ sortedArray: function (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 for parsing AOS keyframe formats
+ flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
+ let i = 1,
+ key = jsonKeys[0];
+
+ while (key !== undefined && key[valuePropertyName] === undefined) {
+ key = jsonKeys[i++];
+ }
+
+ if (key === undefined) return; // no data
+
+ let value = key[valuePropertyName];
+ if (value === undefined) return; // no data
+
+ if (Array.isArray(value)) {
+ do {
+ value = key[valuePropertyName];
+
+ if (value !== undefined) {
+ times.push(key.time);
+ values.push.apply(values, value); // push all elements
+ }
+
+ key = jsonKeys[i++];
+ } while (key !== undefined);
+ } else if (value.toArray !== undefined) {
+ // ...assume THREE.Math-ish
+ do {
+ value = key[valuePropertyName];
+
+ if (value !== undefined) {
+ times.push(key.time);
+ value.toArray(values, values.length);
+ }
+
+ key = jsonKeys[i++];
+ } while (key !== undefined);
+ } else {
+ // otherwise push as-is
+ do {
+ value = key[valuePropertyName];
+
+ if (value !== undefined) {
+ times.push(key.time);
+ values.push(value);
+ }
+
+ key = jsonKeys[i++];
+ } while (key !== undefined);
+ }
+ },
+ subclip: function (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 = AnimationUtils.convertArray(times, track.times.constructor);
+ track.values = AnimationUtils.convertArray(values, track.values.constructor);
+ tracks.push(track);
+ }
+
+ clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
+
+ 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];
+ }
+ } // shift all tracks such that clip begins at t=0
+
+
+ for (let i = 0; i < clip.tracks.length; ++i) {
+ clip.tracks[i].shift(-1 * minStartTime);
+ }
+
+ clip.resetDuration();
+ return clip;
+ },
+ makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
+ if (fps <= 0) fps = 30;
+ const numTracks = referenceClip.tracks.length;
+ const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
+
+ for (let i = 0; i < numTracks; ++i) {
+ const referenceTrack = referenceClip.tracks[i];
+ const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
+
+ if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
+
+ const targetTrack = targetClip.tracks.find(function (track) {
+ return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
+ });
+ if (targetTrack === undefined) 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; // Find the value to subtract out of the track
+
+ if (referenceTime <= referenceTrack.times[0]) {
+ // Reference frame is earlier than the first keyframe, so just use the first keyframe
+ const startIndex = referenceOffset;
+ const endIndex = referenceValueSize - referenceOffset;
+ referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
+ } else if (referenceTime >= referenceTrack.times[lastIndex]) {
+ // Reference frame is after the last keyframe, so just use the last keyframe
+ const startIndex = lastIndex * referenceValueSize + referenceOffset;
+ const endIndex = startIndex + referenceValueSize - referenceOffset;
+ referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
+ } else {
+ // Interpolate to the reference value
+ const interpolant = referenceTrack.createInterpolant();
+ const startIndex = referenceOffset;
+ const endIndex = referenceValueSize - referenceOffset;
+ interpolant.evaluate(referenceTime);
+ referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
+ } // Conjugate the quaternion
+
+
+ if (referenceTrackType === 'quaternion') {
+ const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
+ referenceQuat.toArray(referenceValue);
+ } // Subtract the reference value from all of the track values
+
+
+ const numTimes = targetTrack.times.length;
+
+ for (let j = 0; j < numTimes; ++j) {
+ const valueStart = j * targetValueSize + targetOffset;
+
+ if (referenceTrackType === 'quaternion') {
+ // Multiply the conjugate for quaternion track types
+ Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
+ } else {
+ const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
+
+ for (let k = 0; k < valueEnd; ++k) {
+ targetTrack.values[valueStart + k] -= referenceValue[k];
+ }
+ }
+ }
+ }
+
+ targetClip.blendMode = AdditiveAnimationBlendMode;
+ return targetClip;
+ }
+};
+
+/**
+ * Abstract base class of interpolants over parametric samples.
+ *
+ * The parameter domain is one dimensional, typically the time or a path
+ * along a curve defined by the data.
+ *
+ * The sample values can have any dimensionality and derived classes may
+ * apply special interpretations to the data.
+ *
+ * This class provides the interval seek in a Template Method, deferring
+ * the actual interpolation to derived classes.
+ *
+ * Time complexity is O(1) for linear access crossing at most two points
+ * and O(log N) for random access, where N is the number of positions.
+ *
+ * References:
+ *
+ * http://www.oodesign.com/template-method-pattern.html
+ *
+ */
+class Interpolant {
+ constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
+ this.parameterPositions = parameterPositions;
+ this._cachedIndex = 0;
+ this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
+ this.sampleValues = sampleValues;
+ this.valueSize = sampleSize;
+ this.settings = null;
+ this.DefaultSettings_ = {};
+ }
+
+ evaluate(t) {
+ const pp = this.parameterPositions;
+ let i1 = this._cachedIndex,
+ t1 = pp[i1],
+ t0 = pp[i1 - 1];
+
+ validate_interval: {
+ seek: {
+ let right;
+
+ linear_scan: {
+ //- See http://jsperf.com/comparison-to-undefined/3
+ //- slower code:
+ //-
+ //- if ( t >= t1 || t1 === undefined ) {
+ forward_scan: if (!(t < t1)) {
+ for (let giveUpAt = i1 + 2;;) {
+ if (t1 === undefined) {
+ if (t < t0) break forward_scan; // after end
+
+ i1 = pp.length;
+ this._cachedIndex = i1;
+ return this.afterEnd_(i1 - 1, t, t0);
+ }
+
+ if (i1 === giveUpAt) break; // this loop
+
+ t0 = t1;
+ t1 = pp[++i1];
+
+ if (t < t1) {
+ // we have arrived at the sought interval
+ break seek;
+ }
+ } // prepare binary search on the right side of the index
+
+
+ right = pp.length;
+ break linear_scan;
+ } //- slower code:
+ //- if ( t < t0 || t0 === undefined ) {
+
+
+ if (!(t >= t0)) {
+ // looping?
+ const t1global = pp[1];
+
+ if (t < t1global) {
+ i1 = 2; // + 1, using the scan for the details
+
+ t0 = t1global;
+ } // linear reverse scan
+
+
+ for (let giveUpAt = i1 - 2;;) {
+ if (t0 === undefined) {
+ // before start
+ this._cachedIndex = 0;
+ return this.beforeStart_(0, t, t1);
+ }
+
+ if (i1 === giveUpAt) break; // this loop
+
+ t1 = t0;
+ t0 = pp[--i1 - 1];
+
+ if (t >= t0) {
+ // we have arrived at the sought interval
+ break seek;
+ }
+ } // prepare binary search on the left side of the index
+
+
+ right = i1;
+ i1 = 0;
+ break linear_scan;
+ } // the interval is valid
+
+
+ break validate_interval;
+ } // linear scan
+ // binary search
+
+
+ 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]; // check boundary cases, again
+
+ if (t0 === undefined) {
+ this._cachedIndex = 0;
+ return this.beforeStart_(0, t, t1);
+ }
+
+ if (t1 === undefined) {
+ i1 = pp.length;
+ this._cachedIndex = i1;
+ return this.afterEnd_(i1 - 1, t0, t);
+ }
+ } // seek
+
+
+ this._cachedIndex = i1;
+ this.intervalChanged_(i1, t0, t1);
+ } // validate_interval
+
+
+ return this.interpolate_(i1, t0, t, t1);
+ }
+
+ getSettings_() {
+ return this.settings || this.DefaultSettings_;
+ }
+
+ copySampleValue_(index) {
+ // copies a sample value to the result buffer
+ 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;
+ } // Template methods for derived classes:
+
+
+ interpolate_() {
+ throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
+ }
+
+ intervalChanged_() {// empty
+ }
+
+} // ALIAS DEFINITIONS
+
+
+Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
+Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
+
+/**
+ * Fast and simple cubic spline interpolant.
+ *
+ * It was derived from a Hermitian construction setting the first derivative
+ * at each sample position to the linear slope between neighboring positions
+ * over their parameter interval.
+ */
+
+class CubicInterpolant extends Interpolant {
+ 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 === undefined) {
+ switch (this.getSettings_().endingStart) {
+ case ZeroSlopeEnding:
+ // f'(t0) = 0
+ iPrev = i1;
+ tPrev = 2 * t0 - t1;
+ break;
+
+ case WrapAroundEnding:
+ // use the other end of the curve
+ iPrev = pp.length - 2;
+ tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
+ break;
+
+ default:
+ // ZeroCurvatureEnding
+ // f''(t0) = 0 a.k.a. Natural Spline
+ iPrev = i1;
+ tPrev = t1;
+ }
+ }
+
+ if (tNext === undefined) {
+ switch (this.getSettings_().endingEnd) {
+ case ZeroSlopeEnding:
+ // f'(tN) = 0
+ iNext = i1;
+ tNext = 2 * t1 - t0;
+ break;
+
+ case WrapAroundEnding:
+ // use the other end of the curve
+ iNext = 1;
+ tNext = t1 + pp[1] - pp[0];
+ break;
+
+ default:
+ // ZeroCurvatureEnding
+ // f''(tN) = 0, a.k.a. Natural Spline
+ 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; // evaluate polynomials
+
+ 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; // combine data linearly
+
+ 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 {
+ 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;
+ }
+
+}
+
+/**
+ *
+ * Interpolant that evaluates to the sample value at the position preceeding
+ * the parameter.
+ */
+
+class DiscreteInterpolant extends Interpolant {
+ constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
+ super(parameterPositions, sampleValues, sampleSize, resultBuffer);
+ }
+
+ interpolate_(i1
+ /*, t0, t, t1 */
+ ) {
+ return this.copySampleValue_(i1 - 1);
+ }
+
+}
+
+class KeyframeTrack {
+ constructor(name, times, values, interpolation) {
+ if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
+ if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
+ this.name = name;
+ this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
+ this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
+ this.setInterpolation(interpolation || this.DefaultInterpolation);
+ } // Serialization (in static context, because of constructor invocation
+ // and automatic invocation of .toJSON):
+
+
+ static toJSON(track) {
+ const trackType = track.constructor;
+ let json; // derived classes can define a static toJSON method
+
+ if (trackType.toJSON !== this.toJSON) {
+ json = trackType.toJSON(track);
+ } else {
+ // by default, we assume the data can be serialized as-is
+ json = {
+ 'name': track.name,
+ 'times': AnimationUtils.convertArray(track.times, Array),
+ 'values': AnimationUtils.convertArray(track.values, Array)
+ };
+ const interpolation = track.getInterpolation();
+
+ if (interpolation !== track.DefaultInterpolation) {
+ json.interpolation = interpolation;
+ }
+ }
+
+ json.type = track.ValueTypeName; // mandatory
+
+ return json;
+ }
+
+ InterpolantFactoryMethodDiscrete(result) {
+ return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
+ }
+
+ InterpolantFactoryMethodLinear(result) {
+ return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
+ }
+
+ InterpolantFactoryMethodSmooth(result) {
+ return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
+ }
+
+ setInterpolation(interpolation) {
+ let factoryMethod;
+
+ switch (interpolation) {
+ case InterpolateDiscrete:
+ factoryMethod = this.InterpolantFactoryMethodDiscrete;
+ break;
+
+ case InterpolateLinear:
+ factoryMethod = this.InterpolantFactoryMethodLinear;
+ break;
+
+ case InterpolateSmooth:
+ factoryMethod = this.InterpolantFactoryMethodSmooth;
+ break;
+ }
+
+ if (factoryMethod === undefined) {
+ const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
+
+ if (this.createInterpolant === undefined) {
+ // fall back to default, unless the default itself is messed up
+ if (interpolation !== this.DefaultInterpolation) {
+ this.setInterpolation(this.DefaultInterpolation);
+ } else {
+ throw new Error(message); // fatal, in this case
+ }
+ }
+
+ console.warn('THREE.KeyframeTrack:', message);
+ return this;
+ }
+
+ this.createInterpolant = factoryMethod;
+ return this;
+ }
+
+ getInterpolation() {
+ switch (this.createInterpolant) {
+ case this.InterpolantFactoryMethodDiscrete:
+ return InterpolateDiscrete;
+
+ case this.InterpolantFactoryMethodLinear:
+ return InterpolateLinear;
+
+ case this.InterpolantFactoryMethodSmooth:
+ return InterpolateSmooth;
+ }
+ }
+
+ getValueSize() {
+ return this.values.length / this.times.length;
+ } // move all keyframes either forwards or backwards in time
+
+
+ shift(timeOffset) {
+ if (timeOffset !== 0.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)
+
+
+ scale(timeScale) {
+ if (timeScale !== 1.0) {
+ 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 range [startTime, endTime].
+ // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
+
+
+ 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; // inclusive -> exclusive bound
+
+ if (from !== 0 || to !== nKeys) {
+ // empty tracks are forbidden, so keep at least one keyframe
+ if (from >= to) {
+ to = Math.max(to, 1);
+ from = to - 1;
+ }
+
+ const stride = this.getValueSize();
+ this.times = AnimationUtils.arraySlice(times, from, to);
+ this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
+ }
+
+ return this;
+ } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
+
+
+ validate() {
+ let valid = true;
+ const valueSize = this.getValueSize();
+
+ if (valueSize - Math.floor(valueSize) !== 0) {
+ console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
+ valid = false;
+ }
+
+ const times = this.times,
+ values = this.values,
+ nKeys = times.length;
+
+ if (nKeys === 0) {
+ console.error('THREE.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)) {
+ console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
+ valid = false;
+ break;
+ }
+
+ if (prevTime !== null && prevTime > currTime) {
+ console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
+ valid = false;
+ break;
+ }
+
+ prevTime = currTime;
+ }
+
+ if (values !== undefined) {
+ if (AnimationUtils.isTypedArray(values)) {
+ for (let i = 0, n = values.length; i !== n; ++i) {
+ const value = values[i];
+
+ if (isNaN(value)) {
+ console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
+ valid = false;
+ break;
+ }
+ }
+ }
+ }
+
+ return valid;
+ } // removes equivalent sequential keys as common in morph target sequences
+ // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
+
+
+ optimize() {
+ // times or values may be shared with other tracks, so overwriting is unsafe
+ const times = AnimationUtils.arraySlice(this.times),
+ values = AnimationUtils.arraySlice(this.values),
+ 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]; // remove adjacent keyframes scheduled at the same time
+
+ if (time !== timeNext && (i !== 1 || time !== times[0])) {
+ if (!smoothInterpolation) {
+ // remove unnecessary keyframes same as their neighbors
+ 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;
+ }
+ } // in-place compaction
+
+
+ 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;
+ }
+ } // flush last keyframe (compaction looks ahead)
+
+
+ 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 = AnimationUtils.arraySlice(times, 0, writeIndex);
+ this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
+ } else {
+ this.times = times;
+ this.values = values;
+ }
+
+ return this;
+ }
+
+ clone() {
+ const times = AnimationUtils.arraySlice(this.times, 0);
+ const values = AnimationUtils.arraySlice(this.values, 0);
+ const TypedKeyframeTrack = this.constructor;
+ const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
+
+ track.createInterpolant = this.createInterpolant;
+ return track;
+ }
+
+}
+
+KeyframeTrack.prototype.TimeBufferType = Float32Array;
+KeyframeTrack.prototype.ValueBufferType = Float32Array;
+KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
+
+/**
+ * A Track of Boolean keyframe values.
+ */
+
+class BooleanKeyframeTrack extends KeyframeTrack {}
+
+BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
+BooleanKeyframeTrack.prototype.ValueBufferType = Array;
+BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
+BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
+BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
+
+/**
+ * A Track of keyframe values that represent color.
+ */
+
+class ColorKeyframeTrack extends KeyframeTrack {}
+
+ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
+
+/**
+ * A Track of numeric keyframe values.
+ */
+
+class NumberKeyframeTrack extends KeyframeTrack {}
+
+NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
+
+/**
+ * Spherical linear unit quaternion interpolant.
+ */
+
+class QuaternionLinearInterpolant extends Interpolant {
+ 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;
+ }
+
+}
+
+/**
+ * A Track of quaternion keyframe values.
+ */
+
+class QuaternionKeyframeTrack extends KeyframeTrack {
+ InterpolantFactoryMethodLinear(result) {
+ return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
+ }
+
+}
+
+QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
+
+QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
+QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
+
+/**
+ * A Track that interpolates Strings
+ */
+
+class StringKeyframeTrack extends KeyframeTrack {}
+
+StringKeyframeTrack.prototype.ValueTypeName = 'string';
+StringKeyframeTrack.prototype.ValueBufferType = Array;
+StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
+StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
+StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
+
+/**
+ * A Track of vectored keyframe values.
+ */
+
+class VectorKeyframeTrack extends KeyframeTrack {}
+
+VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
+
+class AnimationClip {
+ constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
+ this.name = name;
+ this.tracks = tracks;
+ this.duration = duration;
+ this.blendMode = blendMode;
+ this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
+
+ if (this.duration < 0) {
+ this.resetDuration();
+ }
+ }
+
+ static parse(json) {
+ const tracks = [],
+ jsonTracks = json.tracks,
+ frameTime = 1.0 / (json.fps || 1.0);
+
+ 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;
+ return clip;
+ }
+
+ static toJSON(clip) {
+ const tracks = [],
+ clipTracks = clip.tracks;
+ const json = {
+ 'name': clip.name,
+ 'duration': clip.duration,
+ 'tracks': tracks,
+ 'uuid': clip.uuid,
+ 'blendMode': clip.blendMode
+ };
+
+ for (let i = 0, n = clipTracks.length; i !== n; ++i) {
+ tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
+ }
+
+ return json;
+ }
+
+ 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 = AnimationUtils.getKeyframeOrder(times);
+ times = AnimationUtils.sortedArray(times, 1, order);
+ values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
+ // last frame as well for perfect loop.
+
+ if (!noLoop && times[0] === 0) {
+ times.push(numMorphTargets);
+ values.push(values[0]);
+ }
+
+ tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
+ }
+
+ return new this(name, -1, tracks);
+ }
+
+ 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;
+ }
+
+ static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
+ const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
+ // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
+
+ const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
+ // patterns like Walk_001, Walk_002, Run_001, Run_002
+
+ 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;
+ } // parse the animation.hierarchy format
+
+
+ static parseAnimation(animation, bones) {
+ if (!animation) {
+ console.error('THREE.AnimationClip: No animation in JSONLoader data.');
+ return null;
+ }
+
+ const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
+ // only return track if there are actually keys.
+ if (animationKeys.length !== 0) {
+ const times = [];
+ const values = [];
+ AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
+
+ 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; // automatic length determination in AnimationClip.
+
+ let duration = animation.length || -1;
+ const hierarchyTracks = animation.hierarchy || [];
+
+ for (let h = 0; h < hierarchyTracks.length; h++) {
+ const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
+
+ if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
+
+ if (animationKeys[0].morphTargets) {
+ // figure out all morph targets used in this track
+ 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;
+ }
+ }
+ } // create a track for each morph target with all zero
+ // morphTargetInfluences except for the keys in which
+ // the morphTarget is named.
+
+
+ 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 || 1.0);
+ } else {
+ // ...assume skeletal animation
+ 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;
+ }
+
+ 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;
+ }
+
+ trim() {
+ for (let i = 0; i < this.tracks.length; i++) {
+ this.tracks[i].trim(0, this.duration);
+ }
+
+ return this;
+ }
+
+ validate() {
+ let valid = true;
+
+ for (let i = 0; i < this.tracks.length; i++) {
+ valid = valid && this.tracks[i].validate();
+ }
+
+ return valid;
+ }
+
+ optimize() {
+ for (let i = 0; i < this.tracks.length; i++) {
+ this.tracks[i].optimize();
+ }
+
+ return this;
+ }
+
+ clone() {
+ const tracks = [];
+
+ for (let i = 0; i < this.tracks.length; i++) {
+ tracks.push(this.tracks[i].clone());
+ }
+
+ return new this.constructor(this.name, this.duration, tracks, this.blendMode);
+ }
+
+ 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 === undefined) {
+ throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
+ }
+
+ const trackType = getTrackTypeForValueTypeName(json.type);
+
+ if (json.times === undefined) {
+ const times = [],
+ values = [];
+ AnimationUtils.flattenJSON(json.keys, times, values, 'value');
+ json.times = times;
+ json.values = values;
+ } // derived classes can define a static parse method
+
+
+ if (trackType.parse !== undefined) {
+ return trackType.parse(json);
+ } else {
+ // by default, we assume a constructor compatible with the base
+ return new trackType(json.name, json.times, json.values, json.interpolation);
+ }
+}
+
+const Cache = {
+ enabled: false,
+ files: {},
+ add: function (key, file) {
+ if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
+
+ this.files[key] = file;
+ },
+ get: function (key) {
+ if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
+
+ return this.files[key];
+ },
+ remove: function (key) {
+ delete this.files[key];
+ },
+ clear: function () {
+ this.files = {};
+ }
+};
+
+class LoadingManager {
+ constructor(onLoad, onProgress, onError) {
+ const scope = this;
+ let isLoading = false;
+ let itemsLoaded = 0;
+ let itemsTotal = 0;
+ let urlModifier = undefined;
+ const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
+ // in the constructor
+
+ this.onStart = undefined;
+ this.onLoad = onLoad;
+ this.onProgress = onProgress;
+ this.onError = onError;
+
+ this.itemStart = function (url) {
+ itemsTotal++;
+
+ if (isLoading === false) {
+ if (scope.onStart !== undefined) {
+ scope.onStart(url, itemsLoaded, itemsTotal);
+ }
+ }
+
+ isLoading = true;
+ };
+
+ this.itemEnd = function (url) {
+ itemsLoaded++;
+
+ if (scope.onProgress !== undefined) {
+ scope.onProgress(url, itemsLoaded, itemsTotal);
+ }
+
+ if (itemsLoaded === itemsTotal) {
+ isLoading = false;
+
+ if (scope.onLoad !== undefined) {
+ scope.onLoad();
+ }
+ }
+ };
+
+ this.itemError = function (url) {
+ if (scope.onError !== undefined) {
+ 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; // see #17920
+
+ if (regex.test(file)) {
+ return loader;
+ }
+ }
+
+ return null;
+ };
+ }
+
+}
+
+const DefaultLoadingManager = new LoadingManager();
+
+class Loader {
+ constructor(manager) {
+ this.manager = manager !== undefined ? manager : DefaultLoadingManager;
+ this.crossOrigin = 'anonymous';
+ this.withCredentials = false;
+ this.path = '';
+ this.resourcePath = '';
+ this.requestHeader = {};
+ }
+
+ load() {}
+
+ loadAsync(url, onProgress) {
+ const scope = this;
+ return new Promise(function (resolve, reject) {
+ scope.load(url, resolve, onProgress, reject);
+ });
+ }
+
+ parse() {}
+
+ setCrossOrigin(crossOrigin) {
+ this.crossOrigin = crossOrigin;
+ return this;
+ }
+
+ setWithCredentials(value) {
+ this.withCredentials = value;
+ return this;
+ }
+
+ setPath(path) {
+ this.path = path;
+ return this;
+ }
+
+ setResourcePath(resourcePath) {
+ this.resourcePath = resourcePath;
+ return this;
+ }
+
+ setRequestHeader(requestHeader) {
+ this.requestHeader = requestHeader;
+ return this;
+ }
+
+}
+
+const loading = {};
+
+class FileLoader extends Loader {
+ constructor(manager) {
+ super(manager);
+ }
+
+ load(url, onLoad, onProgress, onError) {
+ if (url === undefined) url = '';
+ if (this.path !== undefined) url = this.path + url;
+ url = this.manager.resolveURL(url);
+ const cached = Cache.get(url);
+
+ if (cached !== undefined) {
+ this.manager.itemStart(url);
+ setTimeout(() => {
+ if (onLoad) onLoad(cached);
+ this.manager.itemEnd(url);
+ }, 0);
+ return cached;
+ } // Check if request is duplicate
+
+
+ if (loading[url] !== undefined) {
+ loading[url].push({
+ onLoad: onLoad,
+ onProgress: onProgress,
+ onError: onError
+ });
+ return;
+ } // Initialise array for duplicate requests
+
+
+ loading[url] = [];
+ loading[url].push({
+ onLoad: onLoad,
+ onProgress: onProgress,
+ onError: onError
+ }); // create request
+
+ const req = new Request(url, {
+ headers: new Headers(this.requestHeader),
+ credentials: this.withCredentials ? 'include' : 'same-origin' // An abort controller could be added within a future PR
+
+ }); // record states ( avoid data race )
+
+ const mimeType = this.mimeType;
+ const responseType = this.responseType; // start the fetch
+
+ fetch(req).then(response => {
+ if (response.status === 200 || response.status === 0) {
+ // Some browsers return HTTP Status 0 when using non-http protocol
+ // e.g. 'file://' or 'data://'. Handle as success.
+ if (response.status === 0) {
+ console.warn('THREE.FileLoader: HTTP Status 0 received.');
+ }
+
+ if (typeof ReadableStream === 'undefined' || response.body.getReader === undefined) {
+ return response;
+ }
+
+ const callbacks = loading[url];
+ const reader = response.body.getReader();
+ const contentLength = response.headers.get('Content-Length');
+ const total = contentLength ? parseInt(contentLength) : 0;
+ const lengthComputable = total !== 0;
+ let loaded = 0; // periodically read data into the new stream tracking while download progress
+
+ 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();
+ }
+ });
+ }
+ }
+
+ });
+ return new Response(stream);
+ } else {
+ throw Error(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`);
+ }
+ }).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 === undefined) {
+ return response.text();
+ } else {
+ // sniff encoding
+ const re = /charset="?([^;"\s]*)"?/i;
+ const exec = re.exec(mimeType);
+ const label = exec && exec[1] ? exec[1].toLowerCase() : undefined;
+ const decoder = new TextDecoder(label);
+ return response.arrayBuffer().then(ab => decoder.decode(ab));
+ }
+
+ }
+ }).then(data => {
+ // Add to cache only on HTTP success, so that we do not cache
+ // error response bodies as proper responses to requests.
+ Cache.add(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 => {
+ // Abort errors and other errors are handled the same
+ const callbacks = loading[url];
+
+ if (callbacks === undefined) {
+ // When onLoad was called and url was deleted in `loading`
+ 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);
+ }
+
+ setResponseType(value) {
+ this.responseType = value;
+ return this;
+ }
+
+ setMimeType(value) {
+ this.mimeType = value;
+ return this;
+ }
+
+}
+
+class AnimationLoader extends Loader {
+ constructor(manager) {
+ super(manager);
+ }
+
+ 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 {
+ console.error(e);
+ }
+
+ scope.manager.itemError(url);
+ }
+ }, onProgress, onError);
+ }
+
+ parse(json) {
+ const animations = [];
+
+ for (let i = 0; i < json.length; i++) {
+ const clip = AnimationClip.parse(json[i]);
+ animations.push(clip);
+ }
+
+ return animations;
+ }
+
+}
+
+/**
+ * Abstract Base class to block based textures loader (dds, pvr, ...)
+ *
+ * Sub classes have to implement the parse() method which will be used in load().
+ */
+
+class CompressedTextureLoader extends Loader {
+ constructor(manager) {
+ super(manager);
+ }
+
+ 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 {
+ // compressed cubemap texture stored in a single DDS file
+ 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;
+ }
+
+}
+
+class ImageLoader extends Loader {
+ constructor(manager) {
+ super(manager);
+ }
+
+ load(url, onLoad, onProgress, onError) {
+ if (this.path !== undefined) url = this.path + url;
+ url = this.manager.resolveURL(url);
+ const scope = this;
+ const cached = Cache.get(url);
+
+ if (cached !== undefined) {
+ scope.manager.itemStart(url);
+ setTimeout(function () {
+ if (onLoad) onLoad(cached);
+ scope.manager.itemEnd(url);
+ }, 0);
+ return cached;
+ }
+
+ const image = createElementNS('img');
+
+ function onImageLoad() {
+ removeEventListeners();
+ Cache.add(url, this);
+ if (onLoad) onLoad(this);
+ scope.manager.itemEnd(url);
+ }
+
+ function onImageError(event) {
+ removeEventListeners();
+ if (onError) onError(event);
+ 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.substr(0, 5) !== 'data:') {
+ if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
+ }
+
+ scope.manager.itemStart(url);
+ image.src = url;
+ return image;
+ }
+
+}
+
+class CubeTextureLoader extends Loader {
+ constructor(manager) {
+ super(manager);
+ }
+
+ load(urls, onLoad, onProgress, onError) {
+ const texture = new CubeTexture();
+ 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);
+ }
+ }, undefined, onError);
+ }
+
+ for (let i = 0; i < urls.length; ++i) {
+ loadTexture(i);
+ }
+
+ return texture;
+ }
+
+}
+
+/**
+ * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
+ *
+ * Sub classes have to implement the parse() method which will be used in load().
+ */
+
+class DataTextureLoader extends Loader {
+ constructor(manager) {
+ super(manager);
+ }
+
+ 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) {
+ const texData = scope.parse(buffer);
+ if (!texData) return;
+
+ if (texData.image !== undefined) {
+ texture.image = texData.image;
+ } else if (texData.data !== undefined) {
+ texture.image.width = texData.width;
+ texture.image.height = texData.height;
+ texture.image.data = texData.data;
+ }
+
+ texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
+ texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
+ texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
+ texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
+ texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
+
+ if (texData.encoding !== undefined) {
+ texture.encoding = texData.encoding;
+ }
+
+ if (texData.flipY !== undefined) {
+ texture.flipY = texData.flipY;
+ }
+
+ if (texData.format !== undefined) {
+ texture.format = texData.format;
+ }
+
+ if (texData.type !== undefined) {
+ texture.type = texData.type;
+ }
+
+ if (texData.mipmaps !== undefined) {
+ texture.mipmaps = texData.mipmaps;
+ texture.minFilter = LinearMipmapLinearFilter; // presumably...
+ }
+
+ if (texData.mipmapCount === 1) {
+ texture.minFilter = LinearFilter;
+ }
+
+ if (texData.generateMipmaps !== undefined) {
+ texture.generateMipmaps = texData.generateMipmaps;
+ }
+
+ texture.needsUpdate = true;
+ if (onLoad) onLoad(texture, texData);
+ }, onProgress, onError);
+ return texture;
+ }
+
+}
+
+class TextureLoader extends Loader {
+ constructor(manager) {
+ super(manager);
+ }
+
+ 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 !== undefined) {
+ onLoad(texture);
+ }
+ }, onProgress, onError);
+ return texture;
+ }
+
+}
+
+class Light extends Object3D {
+ constructor(color, intensity = 1) {
+ super();
+ this.type = 'Light';
+ this.color = new Color(color);
+ this.intensity = intensity;
+ }
+
+ dispose() {// Empty here in base class; some subclasses override.
+ }
+
+ copy(source) {
+ super.copy(source);
+ 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;
+ if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
+ if (this.distance !== undefined) data.object.distance = this.distance;
+ if (this.angle !== undefined) data.object.angle = this.angle;
+ if (this.decay !== undefined) data.object.decay = this.decay;
+ if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
+ if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
+ return data;
+ }
+
+}
+
+Light.prototype.isLight = true;
+
+class HemisphereLight extends Light {
+ constructor(skyColor, groundColor, intensity) {
+ super(skyColor, intensity);
+ this.type = 'HemisphereLight';
+ this.position.copy(Object3D.DefaultUp);
+ this.updateMatrix();
+ this.groundColor = new Color(groundColor);
+ }
+
+ copy(source) {
+ Light.prototype.copy.call(this, source);
+ this.groundColor.copy(source.groundColor);
+ return this;
+ }
+
+}
+
+HemisphereLight.prototype.isHemisphereLight = true;
+
+const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
+
+const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
+
+const _lookTarget$1 = /*@__PURE__*/new Vector3();
+
+class LightShadow {
+ constructor(camera) {
+ this.camera = camera;
+ this.bias = 0;
+ this.normalBias = 0;
+ this.radius = 1;
+ this.blurSamples = 8;
+ this.mapSize = new Vector2(512, 512);
+ 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)];
+ }
+
+ getViewportCount() {
+ return this._viewportCount;
+ }
+
+ getFrustum() {
+ return this._frustum;
+ }
+
+ 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);
+
+ 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);
+ }
+
+ getViewport(viewportIndex) {
+ return this._viewports[viewportIndex];
+ }
+
+ getFrameExtents() {
+ return this._frameExtents;
+ }
+
+ dispose() {
+ if (this.map) {
+ this.map.dispose();
+ }
+
+ if (this.mapPass) {
+ this.mapPass.dispose();
+ }
+ }
+
+ copy(source) {
+ this.camera = source.camera.clone();
+ this.bias = source.bias;
+ this.radius = source.radius;
+ this.mapSize.copy(source.mapSize);
+ return this;
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+ toJSON() {
+ const object = {};
+ 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;
+ }
+
+}
+
+class SpotLightShadow extends LightShadow {
+ constructor() {
+ super(new PerspectiveCamera(50, 1, 0.5, 500));
+ this.focus = 1;
+ }
+
+ updateMatrices(light) {
+ const camera = this.camera;
+ const fov = RAD2DEG * 2 * light.angle * this.focus;
+ const aspect = this.mapSize.width / this.mapSize.height;
+ const far = light.distance || camera.far;
+
+ if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
+ camera.fov = fov;
+ camera.aspect = aspect;
+ camera.far = far;
+ camera.updateProjectionMatrix();
+ }
+
+ super.updateMatrices(light);
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.focus = source.focus;
+ return this;
+ }
+
+}
+
+SpotLightShadow.prototype.isSpotLightShadow = true;
+
+class SpotLight extends Light {
+ constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
+ super(color, intensity);
+ this.type = 'SpotLight';
+ this.position.copy(Object3D.DefaultUp);
+ this.updateMatrix();
+ this.target = new Object3D();
+ this.distance = distance;
+ this.angle = angle;
+ this.penumbra = penumbra;
+ this.decay = decay; // for physically correct lights, should be 2.
+
+ this.shadow = new SpotLightShadow();
+ }
+
+ get power() {
+ // compute the light's luminous power (in lumens) from its intensity (in candela)
+ // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
+ return this.intensity * Math.PI;
+ }
+
+ set power(power) {
+ // set the light's intensity (in candela) from the desired luminous power (in lumens)
+ this.intensity = power / Math.PI;
+ }
+
+ dispose() {
+ this.shadow.dispose();
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.distance = source.distance;
+ this.angle = source.angle;
+ this.penumbra = source.penumbra;
+ this.decay = source.decay;
+ this.target = source.target.clone();
+ this.shadow = source.shadow.clone();
+ return this;
+ }
+
+}
+
+SpotLight.prototype.isSpotLight = true;
+
+const _projScreenMatrix = /*@__PURE__*/new Matrix4();
+
+const _lightPositionWorld = /*@__PURE__*/new Vector3();
+
+const _lookTarget = /*@__PURE__*/new Vector3();
+
+class PointLightShadow extends LightShadow {
+ constructor() {
+ super(new PerspectiveCamera(90, 1, 0.5, 500));
+ this._frameExtents = new Vector2(4, 2);
+ this._viewportCount = 6;
+ this._viewports = [// These viewports map a cube-map onto a 2D texture with the
+ // following orientation:
+ //
+ // xzXZ
+ // y Y
+ //
+ // X - Positive x direction
+ // x - Negative x direction
+ // Y - Positive y direction
+ // y - Negative y direction
+ // Z - Positive z direction
+ // z - Negative z direction
+ // positive X
+ new Vector4(2, 1, 1, 1), // negative X
+ new Vector4(0, 1, 1, 1), // positive Z
+ new Vector4(3, 1, 1, 1), // negative Z
+ new Vector4(1, 1, 1, 1), // positive Y
+ new Vector4(3, 0, 1, 1), // negative Y
+ new Vector4(1, 0, 1, 1)];
+ this._cubeDirections = [new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0)];
+ this._cubeUps = [new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1)];
+ }
+
+ updateMatrices(light, viewportIndex = 0) {
+ const camera = this.camera;
+ const shadowMatrix = this.matrix;
+ const far = light.distance || camera.far;
+
+ if (far !== camera.far) {
+ camera.far = far;
+ camera.updateProjectionMatrix();
+ }
+
+ _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
+
+ camera.position.copy(_lightPositionWorld);
+
+ _lookTarget.copy(camera.position);
+
+ _lookTarget.add(this._cubeDirections[viewportIndex]);
+
+ camera.up.copy(this._cubeUps[viewportIndex]);
+ camera.lookAt(_lookTarget);
+ camera.updateMatrixWorld();
+ shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
+
+ _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
+
+ this._frustum.setFromProjectionMatrix(_projScreenMatrix);
+ }
+
+}
+
+PointLightShadow.prototype.isPointLightShadow = true;
+
+class PointLight extends Light {
+ constructor(color, intensity, distance = 0, decay = 1) {
+ super(color, intensity);
+ this.type = 'PointLight';
+ this.distance = distance;
+ this.decay = decay; // for physically correct lights, should be 2.
+
+ this.shadow = new PointLightShadow();
+ }
+
+ get power() {
+ // compute the light's luminous power (in lumens) from its intensity (in candela)
+ // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
+ return this.intensity * 4 * Math.PI;
+ }
+
+ set power(power) {
+ // set the light's intensity (in candela) from the desired luminous power (in lumens)
+ this.intensity = power / (4 * Math.PI);
+ }
+
+ dispose() {
+ this.shadow.dispose();
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.distance = source.distance;
+ this.decay = source.decay;
+ this.shadow = source.shadow.clone();
+ return this;
+ }
+
+}
+
+PointLight.prototype.isPointLight = true;
+
+class DirectionalLightShadow extends LightShadow {
+ constructor() {
+ super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
+ }
+
+}
+
+DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
+
+class DirectionalLight extends Light {
+ constructor(color, intensity) {
+ super(color, intensity);
+ this.type = 'DirectionalLight';
+ this.position.copy(Object3D.DefaultUp);
+ this.updateMatrix();
+ this.target = new Object3D();
+ this.shadow = new DirectionalLightShadow();
+ }
+
+ dispose() {
+ this.shadow.dispose();
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.target = source.target.clone();
+ this.shadow = source.shadow.clone();
+ return this;
+ }
+
+}
+
+DirectionalLight.prototype.isDirectionalLight = true;
+
+class AmbientLight extends Light {
+ constructor(color, intensity) {
+ super(color, intensity);
+ this.type = 'AmbientLight';
+ }
+
+}
+
+AmbientLight.prototype.isAmbientLight = true;
+
+class RectAreaLight extends Light {
+ constructor(color, intensity, width = 10, height = 10) {
+ super(color, intensity);
+ this.type = 'RectAreaLight';
+ this.width = width;
+ this.height = height;
+ }
+
+ get power() {
+ // compute the light's luminous power (in lumens) from its intensity (in nits)
+ return this.intensity * this.width * this.height * Math.PI;
+ }
+
+ set power(power) {
+ // set the light's intensity (in nits) from the desired luminous power (in lumens)
+ 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;
+ }
+
+}
+
+RectAreaLight.prototype.isRectAreaLight = true;
+
+/**
+ * Primary reference:
+ * https://graphics.stanford.edu/papers/envmap/envmap.pdf
+ *
+ * Secondary reference:
+ * https://www.ppsloan.org/publications/StupidSH36.pdf
+ */
+// 3-band SH defined by 9 coefficients
+
+class SphericalHarmonics3 {
+ constructor() {
+ this.coefficients = [];
+
+ for (let i = 0; i < 9; i++) {
+ this.coefficients.push(new Vector3());
+ }
+ }
+
+ set(coefficients) {
+ for (let i = 0; i < 9; i++) {
+ this.coefficients[i].copy(coefficients[i]);
+ }
+
+ return this;
+ }
+
+ zero() {
+ for (let i = 0; i < 9; i++) {
+ this.coefficients[i].set(0, 0, 0);
+ }
+
+ return this;
+ } // get the radiance in the direction of the normal
+ // target is a Vector3
+
+
+ getAt(normal, target) {
+ // normal is assumed to be unit length
+ const x = normal.x,
+ y = normal.y,
+ z = normal.z;
+ const coeff = this.coefficients; // band 0
+
+ target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
+
+ target.addScaledVector(coeff[1], 0.488603 * y);
+ target.addScaledVector(coeff[2], 0.488603 * z);
+ target.addScaledVector(coeff[3], 0.488603 * x); // band 2
+
+ target.addScaledVector(coeff[4], 1.092548 * (x * y));
+ target.addScaledVector(coeff[5], 1.092548 * (y * z));
+ target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
+ target.addScaledVector(coeff[7], 1.092548 * (x * z));
+ target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
+ return target;
+ } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
+ // target is a Vector3
+ // https://graphics.stanford.edu/papers/envmap/envmap.pdf
+
+
+ getIrradianceAt(normal, target) {
+ // normal is assumed to be unit length
+ const x = normal.x,
+ y = normal.y,
+ z = normal.z;
+ const coeff = this.coefficients; // band 0
+
+ target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
+ // band 1
+
+ target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
+
+ target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
+ target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
+
+ target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
+
+ target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
+ target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
+
+ target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
+ target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
+
+ return target;
+ }
+
+ add(sh) {
+ for (let i = 0; i < 9; i++) {
+ this.coefficients[i].add(sh.coefficients[i]);
+ }
+
+ return this;
+ }
+
+ addScaledSH(sh, s) {
+ for (let i = 0; i < 9; i++) {
+ this.coefficients[i].addScaledVector(sh.coefficients[i], s);
+ }
+
+ return this;
+ }
+
+ scale(s) {
+ for (let i = 0; i < 9; i++) {
+ this.coefficients[i].multiplyScalar(s);
+ }
+
+ return this;
+ }
+
+ lerp(sh, alpha) {
+ for (let i = 0; i < 9; i++) {
+ this.coefficients[i].lerp(sh.coefficients[i], alpha);
+ }
+
+ return this;
+ }
+
+ equals(sh) {
+ for (let i = 0; i < 9; i++) {
+ if (!this.coefficients[i].equals(sh.coefficients[i])) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ copy(sh) {
+ return this.set(sh.coefficients);
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+ fromArray(array, offset = 0) {
+ const coefficients = this.coefficients;
+
+ for (let i = 0; i < 9; i++) {
+ coefficients[i].fromArray(array, offset + i * 3);
+ }
+
+ return this;
+ }
+
+ toArray(array = [], offset = 0) {
+ const coefficients = this.coefficients;
+
+ for (let i = 0; i < 9; i++) {
+ coefficients[i].toArray(array, offset + i * 3);
+ }
+
+ return array;
+ } // evaluate the basis functions
+ // shBasis is an Array[ 9 ]
+
+
+ static getBasisAt(normal, shBasis) {
+ // normal is assumed to be unit length
+ const x = normal.x,
+ y = normal.y,
+ z = normal.z; // band 0
+
+ shBasis[0] = 0.282095; // band 1
+
+ shBasis[1] = 0.488603 * y;
+ shBasis[2] = 0.488603 * z;
+ shBasis[3] = 0.488603 * x; // band 2
+
+ 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);
+ }
+
+}
+
+SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
+
+class LightProbe extends Light {
+ constructor(sh = new SphericalHarmonics3(), intensity = 1) {
+ super(undefined, intensity);
+ this.sh = sh;
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.sh.copy(source.sh);
+ return this;
+ }
+
+ fromJSON(json) {
+ this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
+
+ this.sh.fromArray(json.sh);
+ return this;
+ }
+
+ toJSON(meta) {
+ const data = super.toJSON(meta);
+ data.object.sh = this.sh.toArray();
+ return data;
+ }
+
+}
+
+LightProbe.prototype.isLightProbe = true;
+
+class MaterialLoader extends Loader {
+ constructor(manager) {
+ super(manager);
+ this.textures = {};
+ }
+
+ 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 {
+ console.error(e);
+ }
+
+ scope.manager.itemError(url);
+ }
+ }, onProgress, onError);
+ }
+
+ parse(json) {
+ const textures = this.textures;
+
+ function getTexture(name) {
+ if (textures[name] === undefined) {
+ console.warn('THREE.MaterialLoader: Undefined texture', name);
+ }
+
+ return textures[name];
+ }
+
+ const material = new Materials[json.type]();
+ if (json.uuid !== undefined) material.uuid = json.uuid;
+ if (json.name !== undefined) material.name = json.name;
+ if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
+ if (json.roughness !== undefined) material.roughness = json.roughness;
+ if (json.metalness !== undefined) material.metalness = json.metalness;
+ if (json.sheen !== undefined) material.sheen = json.sheen;
+ if (json.sheenColor !== undefined) material.sheenColor = new Color().setHex(json.sheenColor);
+ if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
+ if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
+ if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
+ if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
+ if (json.specularColor !== undefined && material.specularColor !== undefined) material.specularColor.setHex(json.specularColor);
+ if (json.shininess !== undefined) material.shininess = json.shininess;
+ if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
+ if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
+ if (json.transmission !== undefined) material.transmission = json.transmission;
+ if (json.thickness !== undefined) material.thickness = json.thickness;
+ if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
+ if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
+ if (json.fog !== undefined) material.fog = json.fog;
+ if (json.flatShading !== undefined) material.flatShading = json.flatShading;
+ if (json.blending !== undefined) material.blending = json.blending;
+ if (json.combine !== undefined) material.combine = json.combine;
+ if (json.side !== undefined) material.side = json.side;
+ if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
+ if (json.opacity !== undefined) material.opacity = json.opacity;
+ if (json.transparent !== undefined) material.transparent = json.transparent;
+ if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
+ if (json.depthTest !== undefined) material.depthTest = json.depthTest;
+ if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
+ if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
+ if (json.alphaWrite !== undefined) material.alphaWrite = json.alphaWrite;
+ if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
+ if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
+ if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
+ if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
+ if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
+ if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
+ if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
+ if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
+ if (json.wireframe !== undefined) material.wireframe = json.wireframe;
+ if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
+ if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
+ if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
+ if (json.rotation !== undefined) material.rotation = json.rotation;
+ if (json.linewidth !== 1) material.linewidth = json.linewidth;
+ if (json.dashSize !== undefined) material.dashSize = json.dashSize;
+ if (json.gapSize !== undefined) material.gapSize = json.gapSize;
+ if (json.scale !== undefined) material.scale = json.scale;
+ if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
+ if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
+ if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
+ if (json.dithering !== undefined) material.dithering = json.dithering;
+ if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
+ if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
+ if (json.visible !== undefined) material.visible = json.visible;
+ if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
+ if (json.userData !== undefined) material.userData = json.userData;
+
+ if (json.vertexColors !== undefined) {
+ if (typeof json.vertexColors === 'number') {
+ material.vertexColors = json.vertexColors > 0 ? true : false;
+ } else {
+ material.vertexColors = json.vertexColors;
+ }
+ } // Shader Material
+
+
+ if (json.uniforms !== undefined) {
+ 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 !== undefined) material.defines = json.defines;
+ if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
+ if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
+
+ if (json.extensions !== undefined) {
+ for (const key in json.extensions) {
+ material.extensions[key] = json.extensions[key];
+ }
+ } // Deprecated
+
+
+ if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
+ // for PointsMaterial
+
+ if (json.size !== undefined) material.size = json.size;
+ if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
+
+ if (json.map !== undefined) material.map = getTexture(json.map);
+ if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
+ if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
+ if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
+ if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
+ if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
+ if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
+
+ if (json.normalScale !== undefined) {
+ let normalScale = json.normalScale;
+
+ if (Array.isArray(normalScale) === false) {
+ // Blender exporter used to export a scalar. See #7459
+ normalScale = [normalScale, normalScale];
+ }
+
+ material.normalScale = new Vector2().fromArray(normalScale);
+ }
+
+ if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
+ if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
+ if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
+ if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
+ if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
+ if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
+ if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
+ if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
+ if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
+ if (json.specularColorMap !== undefined) material.specularColorMap = getTexture(json.specularColorMap);
+ if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
+ if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
+ if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
+ if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
+ if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
+ if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
+ if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
+ if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
+ if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
+ if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
+ if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
+ if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
+ if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
+ if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
+ if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
+ if (json.sheenColorMap !== undefined) material.sheenColorMap = getTexture(json.sheenColorMap);
+ if (json.sheenRoughnessMap !== undefined) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap);
+ return material;
+ }
+
+ setTextures(value) {
+ this.textures = value;
+ return this;
+ }
+
+}
+
+class LoaderUtils {
+ static decodeText(array) {
+ if (typeof TextDecoder !== 'undefined') {
+ return new TextDecoder().decode(array);
+ } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
+ // throws a "maximum call stack size exceeded" error for large arrays.
+
+
+ let s = '';
+
+ for (let i = 0, il = array.length; i < il; i++) {
+ // Implicitly assumes little-endian.
+ s += String.fromCharCode(array[i]);
+ }
+
+ try {
+ // merges multi-byte utf-8 characters.
+ return decodeURIComponent(escape(s));
+ } catch (e) {
+ // see #16358
+ return s;
+ }
+ }
+
+ static extractUrlBase(url) {
+ const index = url.lastIndexOf('/');
+ if (index === -1) return './';
+ return url.substr(0, index + 1);
+ }
+
+ static resolveURL(url, path) {
+ // Invalid URL
+ if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
+
+ if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
+ path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
+ } // Absolute URL http://,https://,//
+
+
+ if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
+
+ if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
+
+ if (/^blob:.*$/i.test(url)) return url; // Relative URL
+
+ return path + url;
+ }
+
+}
+
+class InstancedBufferGeometry extends BufferGeometry {
+ constructor() {
+ super();
+ this.type = 'InstancedBufferGeometry';
+ this.instanceCount = Infinity;
+ }
+
+ copy(source) {
+ super.copy(source);
+ this.instanceCount = source.instanceCount;
+ return this;
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+ toJSON() {
+ const data = super.toJSON(this);
+ data.instanceCount = this.instanceCount;
+ data.isInstancedBufferGeometry = true;
+ return data;
+ }
+
+}
+
+InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
+
+class BufferGeometryLoader extends Loader {
+ constructor(manager) {
+ super(manager);
+ }
+
+ 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 {
+ console.error(e);
+ }
+
+ scope.manager.itemError(url);
+ }
+ }, onProgress, onError);
+ }
+
+ parse(json) {
+ const interleavedBufferMap = {};
+ const arrayBufferMap = {};
+
+ function getInterleavedBuffer(json, uuid) {
+ if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
+ const interleavedBuffers = json.interleavedBuffers;
+ const interleavedBuffer = interleavedBuffers[uuid];
+ const buffer = getArrayBuffer(json, 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(json, uuid) {
+ if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
+ const arrayBuffers = json.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 !== undefined) {
+ 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 !== undefined) bufferAttribute.name = attribute.name;
+ if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
+
+ if (attribute.updateRange !== undefined) {
+ bufferAttribute.updateRange.offset = attribute.updateRange.offset;
+ bufferAttribute.updateRange.count = attribute.updateRange.count;
+ }
+
+ 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 !== undefined) 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 !== undefined) {
+ 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 !== undefined) {
+ const center = new Vector3();
+
+ if (boundingSphere.center !== undefined) {
+ center.fromArray(boundingSphere.center);
+ }
+
+ geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
+ }
+
+ if (json.name) geometry.name = json.name;
+ if (json.userData) geometry.userData = json.userData;
+ return geometry;
+ }
+
+}
+
+class ObjectLoader extends Loader {
+ constructor(manager) {
+ super(manager);
+ }
+
+ 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 (error) {
+ if (onError !== undefined) onError(error);
+ console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
+ return;
+ }
+
+ const metadata = json.metadata;
+
+ if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
+ console.error('THREE.ObjectLoader: Can\'t load ' + url);
+ return;
+ }
+
+ scope.parse(json, onLoad);
+ }, onProgress, onError);
+ }
+
+ 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);
+ const json = JSON.parse(text);
+ const metadata = json.metadata;
+
+ if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
+ throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
+ }
+
+ return await scope.parseAsync(json);
+ }
+
+ 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 !== undefined) 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); //
+
+ if (onLoad !== undefined) {
+ let hasImages = false;
+
+ for (const uuid in images) {
+ if (images[uuid] instanceof HTMLImageElement) {
+ hasImages = true;
+ break;
+ }
+ }
+
+ if (hasImages === false) onLoad(object);
+ }
+
+ return 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);
+ return object;
+ }
+
+ parseShapes(json) {
+ const shapes = {};
+
+ if (json !== undefined) {
+ 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 = {}; // generate bone lookup table
+
+ object.traverse(function (child) {
+ if (child.isBone) bones[child.uuid] = child;
+ }); // create skeletons
+
+ if (json !== undefined) {
+ 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 !== undefined) {
+ 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;
+
+ case 'Geometry':
+ console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
+ break;
+
+ default:
+ if (data.type in Geometries) {
+ geometry = Geometries[data.type].fromJSON(data, shapes);
+ } else {
+ console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
+ }
+
+ }
+
+ geometry.uuid = data.uuid;
+ if (data.name !== undefined) geometry.name = data.name;
+ if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
+ geometries[data.uuid] = geometry;
+ }
+ }
+
+ return geometries;
+ }
+
+ parseMaterials(json, textures) {
+ const cache = {}; // MultiMaterial
+
+ const materials = {};
+
+ if (json !== undefined) {
+ const loader = new MaterialLoader();
+ loader.setTextures(textures);
+
+ for (let i = 0, l = json.length; i < l; i++) {
+ const data = json[i];
+
+ if (data.type === 'MultiMaterial') {
+ // Deprecated
+ const array = [];
+
+ for (let j = 0; j < data.materials.length; j++) {
+ const material = data.materials[j];
+
+ if (cache[material.uuid] === undefined) {
+ cache[material.uuid] = loader.parse(material);
+ }
+
+ array.push(cache[material.uuid]);
+ }
+
+ materials[data.uuid] = array;
+ } else {
+ if (cache[data.uuid] === undefined) {
+ cache[data.uuid] = loader.parse(data);
+ }
+
+ materials[data.uuid] = cache[data.uuid];
+ }
+ }
+ }
+
+ return materials;
+ }
+
+ parseAnimations(json) {
+ const animations = {};
+
+ if (json !== undefined) {
+ 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);
+ }, undefined, 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 !== undefined && 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)) {
+ // load array of images e.g CubeTexture
+ images[image.uuid] = [];
+
+ 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) {
+ images[image.uuid].push(deserializedImage);
+ } else {
+ // special case: handle array of data textures for cube textures
+ images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
+ }
+ }
+ }
+ } else {
+ // load single image
+ const deserializedImage = deserializeImage(image.url);
+
+ if (deserializedImage !== null) {
+ images[image.uuid] = 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 !== undefined && 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)) {
+ // load array of images e.g CubeTexture
+ images[image.uuid] = [];
+
+ 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) {
+ images[image.uuid].push(deserializedImage);
+ } else {
+ // special case: handle array of data textures for cube textures
+ images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
+ }
+ }
+ }
+ } else {
+ // load single image
+ const deserializedImage = await deserializeImage(image.url);
+
+ if (deserializedImage !== null) {
+ images[image.uuid] = deserializedImage;
+ }
+ }
+ }
+ }
+
+ return images;
+ }
+
+ parseTextures(json, images) {
+ function parseConstant(value, type) {
+ if (typeof value === 'number') return value;
+ console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
+ return type[value];
+ }
+
+ const textures = {};
+
+ if (json !== undefined) {
+ for (let i = 0, l = json.length; i < l; i++) {
+ const data = json[i];
+
+ if (data.image === undefined) {
+ console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
+ }
+
+ if (images[data.image] === undefined) {
+ console.warn('THREE.ObjectLoader: Undefined image', data.image);
+ }
+
+ let texture;
+ const image = images[data.image];
+
+ if (Array.isArray(image)) {
+ texture = new CubeTexture(image);
+ if (image.length === 6) texture.needsUpdate = true;
+ } else {
+ if (image && image.data) {
+ texture = new DataTexture(image.data, image.width, image.height);
+ } else {
+ texture = new Texture(image);
+ }
+
+ if (image) texture.needsUpdate = true; // textures can have undefined image data
+ }
+
+ texture.uuid = data.uuid;
+ if (data.name !== undefined) texture.name = data.name;
+ if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
+ if (data.offset !== undefined) texture.offset.fromArray(data.offset);
+ if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
+ if (data.center !== undefined) texture.center.fromArray(data.center);
+ if (data.rotation !== undefined) texture.rotation = data.rotation;
+
+ if (data.wrap !== undefined) {
+ texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
+ texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
+ }
+
+ if (data.format !== undefined) texture.format = data.format;
+ if (data.type !== undefined) texture.type = data.type;
+ if (data.encoding !== undefined) texture.encoding = data.encoding;
+ if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
+ if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
+ if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
+ if (data.flipY !== undefined) texture.flipY = data.flipY;
+ if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
+ if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
+ if (data.userData !== undefined) texture.userData = data.userData;
+ textures[data.uuid] = texture;
+ }
+ }
+
+ return textures;
+ }
+
+ parseObject(data, geometries, materials, textures, animations) {
+ let object;
+
+ function getGeometry(name) {
+ if (geometries[name] === undefined) {
+ console.warn('THREE.ObjectLoader: Undefined geometry', name);
+ }
+
+ return geometries[name];
+ }
+
+ function getMaterial(name) {
+ if (name === undefined) return undefined;
+
+ if (Array.isArray(name)) {
+ const array = [];
+
+ for (let i = 0, l = name.length; i < l; i++) {
+ const uuid = name[i];
+
+ if (materials[uuid] === undefined) {
+ console.warn('THREE.ObjectLoader: Undefined material', uuid);
+ }
+
+ array.push(materials[uuid]);
+ }
+
+ return array;
+ }
+
+ if (materials[name] === undefined) {
+ console.warn('THREE.ObjectLoader: Undefined material', name);
+ }
+
+ return materials[name];
+ }
+
+ function getTexture(uuid) {
+ if (textures[uuid] === undefined) {
+ console.warn('THREE.ObjectLoader: Undefined texture', uuid);
+ }
+
+ return textures[uuid];
+ }
+
+ let geometry, material;
+
+ switch (data.type) {
+ case 'Scene':
+ object = new Scene();
+
+ if (data.background !== undefined) {
+ if (Number.isInteger(data.background)) {
+ object.background = new Color(data.background);
+ } else {
+ object.background = getTexture(data.background);
+ }
+ }
+
+ if (data.environment !== undefined) {
+ object.environment = getTexture(data.environment);
+ }
+
+ if (data.fog !== undefined) {
+ 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);
+ }
+ }
+
+ break;
+
+ case 'PerspectiveCamera':
+ object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
+ if (data.focus !== undefined) object.focus = data.focus;
+ if (data.zoom !== undefined) object.zoom = data.zoom;
+ if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
+ if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
+ if (data.view !== undefined) 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 !== undefined) object.zoom = data.zoom;
+ if (data.view !== undefined) 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);
+ 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);
+ break;
+
+ case 'HemisphereLight':
+ object = new HemisphereLight(data.color, data.groundColor, data.intensity);
+ break;
+
+ case 'LightProbe':
+ object = new LightProbe().fromJSON(data);
+ break;
+
+ case 'SkinnedMesh':
+ geometry = getGeometry(data.geometry);
+ material = getMaterial(data.material);
+ object = new SkinnedMesh(geometry, material);
+ if (data.bindMode !== undefined) object.bindMode = data.bindMode;
+ if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
+ if (data.skeleton !== undefined) 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 !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
+ 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 !== undefined) object.name = data.name;
+
+ if (data.matrix !== undefined) {
+ object.matrix.fromArray(data.matrix);
+ if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
+ if (object.matrixAutoUpdate) object.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.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
+ if (data.scale !== undefined) object.scale.fromArray(data.scale);
+ }
+
+ if (data.castShadow !== undefined) object.castShadow = data.castShadow;
+ if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
+
+ if (data.shadow) {
+ if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
+ if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
+ if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
+ if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
+ if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
+ }
+
+ if (data.visible !== undefined) object.visible = data.visible;
+ if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
+ if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
+ if (data.userData !== undefined) object.userData = data.userData;
+ if (data.layers !== undefined) object.layers.mask = data.layers;
+
+ if (data.children !== undefined) {
+ 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 !== undefined) {
+ 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 !== undefined) 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 !== undefined) {
+ object.addLevel(child, level.distance);
+ }
+ }
+ }
+
+ return object;
+ }
+
+ bindSkeletons(object, skeletons) {
+ if (Object.keys(skeletons).length === 0) return;
+ object.traverse(function (child) {
+ if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
+ const skeleton = skeletons[child.skeleton];
+
+ if (skeleton === undefined) {
+ console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
+ } else {
+ child.bind(skeleton, child.bindMatrix);
+ }
+ }
+ });
+ }
+ /* DEPRECATED */
+
+
+ setTexturePath(value) {
+ console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
+ return this.setResourcePath(value);
+ }
+
+}
+
+const TEXTURE_MAPPING = {
+ UVMapping: UVMapping,
+ CubeReflectionMapping: CubeReflectionMapping,
+ CubeRefractionMapping: CubeRefractionMapping,
+ EquirectangularReflectionMapping: EquirectangularReflectionMapping,
+ EquirectangularRefractionMapping: EquirectangularRefractionMapping,
+ CubeUVReflectionMapping: CubeUVReflectionMapping,
+ CubeUVRefractionMapping: CubeUVRefractionMapping
+};
+const TEXTURE_WRAPPING = {
+ RepeatWrapping: RepeatWrapping,
+ ClampToEdgeWrapping: ClampToEdgeWrapping,
+ MirroredRepeatWrapping: MirroredRepeatWrapping
+};
+const TEXTURE_FILTER = {
+ NearestFilter: NearestFilter,
+ NearestMipmapNearestFilter: NearestMipmapNearestFilter,
+ NearestMipmapLinearFilter: NearestMipmapLinearFilter,
+ LinearFilter: LinearFilter,
+ LinearMipmapNearestFilter: LinearMipmapNearestFilter,
+ LinearMipmapLinearFilter: LinearMipmapLinearFilter
+};
+
+class ImageBitmapLoader extends Loader {
+ constructor(manager) {
+ super(manager);
+
+ if (typeof createImageBitmap === 'undefined') {
+ console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
+ }
+
+ if (typeof fetch === 'undefined') {
+ console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
+ }
+
+ this.options = {
+ premultiplyAlpha: 'none'
+ };
+ }
+
+ setOptions(options) {
+ this.options = options;
+ return this;
+ }
+
+ load(url, onLoad, onProgress, onError) {
+ if (url === undefined) url = '';
+ if (this.path !== undefined) url = this.path + url;
+ url = this.manager.resolveURL(url);
+ const scope = this;
+ const cached = Cache.get(url);
+
+ if (cached !== undefined) {
+ scope.manager.itemStart(url);
+ setTimeout(function () {
+ if (onLoad) onLoad(cached);
+ scope.manager.itemEnd(url);
+ }, 0);
+ return cached;
+ }
+
+ const fetchOptions = {};
+ fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
+ fetchOptions.headers = this.requestHeader;
+ 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(url, imageBitmap);
+ if (onLoad) onLoad(imageBitmap);
+ scope.manager.itemEnd(url);
+ }).catch(function (e) {
+ if (onError) onError(e);
+ scope.manager.itemError(url);
+ scope.manager.itemEnd(url);
+ });
+ scope.manager.itemStart(url);
+ }
+
+}
+
+ImageBitmapLoader.prototype.isImageBitmapLoader = true;
+
+let _context;
+
+const AudioContext = {
+ getContext: function () {
+ if (_context === undefined) {
+ _context = new (window.AudioContext || window.webkitAudioContext)();
+ }
+
+ return _context;
+ },
+ setContext: function (value) {
+ _context = value;
+ }
+};
+
+class AudioLoader extends Loader {
+ constructor(manager) {
+ super(manager);
+ }
+
+ 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 {
+ // Create a copy of the buffer. The `decodeAudioData` method
+ // detaches the buffer when complete, preventing reuse.
+ const bufferCopy = buffer.slice(0);
+ const context = AudioContext.getContext();
+ context.decodeAudioData(bufferCopy, function (audioBuffer) {
+ onLoad(audioBuffer);
+ });
+ } catch (e) {
+ if (onError) {
+ onError(e);
+ } else {
+ console.error(e);
+ }
+
+ scope.manager.itemError(url);
+ }
+ }, onProgress, onError);
+ }
+
+}
+
+class HemisphereLightProbe extends LightProbe {
+ constructor(skyColor, groundColor, intensity = 1) {
+ super(undefined, intensity);
+ const color1 = new Color().set(skyColor);
+ const color2 = new Color().set(groundColor);
+ const sky = new Vector3(color1.r, color1.g, color1.b);
+ const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
+
+ const c0 = Math.sqrt(Math.PI);
+ const c1 = c0 * Math.sqrt(0.75);
+ this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
+ this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
+ }
+
+}
+
+HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
+
+class AmbientLightProbe extends LightProbe {
+ constructor(color, intensity = 1) {
+ super(undefined, intensity);
+ const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
+
+ this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
+ }
+
+}
+
+AmbientLightProbe.prototype.isAmbientLightProbe = true;
+
+const _eyeRight = /*@__PURE__*/new Matrix4();
+
+const _eyeLeft = /*@__PURE__*/new Matrix4();
+
+const _projectionMatrix = /*@__PURE__*/new Matrix4();
+
+class StereoCamera {
+ 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
+ };
+ }
+
+ 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; // Off-axis stereoscopic effect based on
+ // http://paulbourke.net/stereographics/stereorender/
+
+ _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; // translate xOffset
+
+ _eyeLeft.elements[12] = -eyeSepHalf;
+ _eyeRight.elements[12] = eyeSepHalf; // for left eye
+
+ 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); // for right eye
+
+ 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);
+ }
+
+}
+
+class Clock {
+ constructor(autoStart = true) {
+ this.autoStart = autoStart;
+ this.startTime = 0;
+ this.oldTime = 0;
+ this.elapsedTime = 0;
+ this.running = false;
+ }
+
+ start() {
+ this.startTime = now();
+ this.oldTime = this.startTime;
+ this.elapsedTime = 0;
+ this.running = true;
+ }
+
+ stop() {
+ this.getElapsedTime();
+ this.running = false;
+ this.autoStart = false;
+ }
+
+ getElapsedTime() {
+ this.getDelta();
+ return this.elapsedTime;
+ }
+
+ getDelta() {
+ let diff = 0;
+
+ if (this.autoStart && !this.running) {
+ this.start();
+ return 0;
+ }
+
+ if (this.running) {
+ const newTime = now();
+ diff = (newTime - this.oldTime) / 1000;
+ this.oldTime = newTime;
+ this.elapsedTime += diff;
+ }
+
+ return diff;
+ }
+
+}
+
+function now() {
+ return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
+}
+
+const _position$1 = /*@__PURE__*/new Vector3();
+
+const _quaternion$1 = /*@__PURE__*/new Quaternion();
+
+const _scale$1 = /*@__PURE__*/new Vector3();
+
+const _orientation$1 = /*@__PURE__*/new Vector3();
+
+class AudioListener extends Object3D {
+ 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; // private
+
+ this._clock = new Clock();
+ }
+
+ getInput() {
+ return this.gain;
+ }
+
+ 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;
+ }
+
+ getFilter() {
+ return this.filter;
+ }
+
+ 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;
+ }
+
+ getMasterVolume() {
+ return this.gain.gain.value;
+ }
+
+ setMasterVolume(value) {
+ this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
+ return this;
+ }
+
+ updateMatrixWorld(force) {
+ super.updateMatrixWorld(force);
+ const listener = this.context.listener;
+ const up = this.up;
+ this.timeDelta = this._clock.getDelta();
+ this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
+
+ _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
+
+ if (listener.positionX) {
+ // code path for Chrome (see #14393)
+ 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(_orientation$1.x, endTime);
+ listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
+ listener.forwardZ.linearRampToValueAtTime(_orientation$1.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(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
+ }
+ }
+
+}
+
+class Audio extends Object3D {
+ 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 = undefined;
+ 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 = [];
+ }
+
+ getOutput() {
+ return this.gain;
+ }
+
+ setNodeSource(audioNode) {
+ this.hasPlaybackControl = false;
+ this.sourceType = 'audioNode';
+ this.source = audioNode;
+ this.connect();
+ return this;
+ }
+
+ setMediaElementSource(mediaElement) {
+ this.hasPlaybackControl = false;
+ this.sourceType = 'mediaNode';
+ this.source = this.context.createMediaElementSource(mediaElement);
+ this.connect();
+ return this;
+ }
+
+ setMediaStreamSource(mediaStream) {
+ this.hasPlaybackControl = false;
+ this.sourceType = 'mediaStreamNode';
+ this.source = this.context.createMediaStreamSource(mediaStream);
+ this.connect();
+ return this;
+ }
+
+ setBuffer(audioBuffer) {
+ this.buffer = audioBuffer;
+ this.sourceType = 'buffer';
+ if (this.autoplay) this.play();
+ return this;
+ }
+
+ play(delay = 0) {
+ if (this.isPlaying === true) {
+ console.warn('THREE.Audio: Audio is already playing.');
+ return;
+ }
+
+ if (this.hasPlaybackControl === false) {
+ console.warn('THREE.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();
+ }
+
+ pause() {
+ if (this.hasPlaybackControl === false) {
+ console.warn('THREE.Audio: this Audio has no playback control.');
+ return;
+ }
+
+ if (this.isPlaying === true) {
+ // update current progress
+ this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
+
+ if (this.loop === true) {
+ // ensure _progress does not exceed duration with looped audios
+ this._progress = this._progress % (this.duration || this.buffer.duration);
+ }
+
+ this.source.stop();
+ this.source.onended = null;
+ this.isPlaying = false;
+ }
+
+ return this;
+ }
+
+ stop() {
+ if (this.hasPlaybackControl === false) {
+ console.warn('THREE.Audio: this Audio has no playback control.');
+ return;
+ }
+
+ this._progress = 0;
+ this.source.stop();
+ this.source.onended = null;
+ this.isPlaying = false;
+ return this;
+ }
+
+ 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;
+ }
+
+ disconnect() {
+ 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;
+ }
+
+ getFilters() {
+ return this.filters;
+ }
+
+ setFilters(value) {
+ if (!value) value = [];
+
+ if (this._connected === true) {
+ this.disconnect();
+ this.filters = value.slice();
+ this.connect();
+ } else {
+ this.filters = value.slice();
+ }
+
+ return this;
+ }
+
+ setDetune(value) {
+ this.detune = value;
+ if (this.source.detune === undefined) return; // only set detune when available
+
+ if (this.isPlaying === true) {
+ this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
+ }
+
+ return this;
+ }
+
+ getDetune() {
+ return this.detune;
+ }
+
+ getFilter() {
+ return this.getFilters()[0];
+ }
+
+ setFilter(filter) {
+ return this.setFilters(filter ? [filter] : []);
+ }
+
+ setPlaybackRate(value) {
+ if (this.hasPlaybackControl === false) {
+ console.warn('THREE.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;
+ }
+
+ getPlaybackRate() {
+ return this.playbackRate;
+ }
+
+ onEnded() {
+ this.isPlaying = false;
+ }
+
+ getLoop() {
+ if (this.hasPlaybackControl === false) {
+ console.warn('THREE.Audio: this Audio has no playback control.');
+ return false;
+ }
+
+ return this.loop;
+ }
+
+ setLoop(value) {
+ if (this.hasPlaybackControl === false) {
+ console.warn('THREE.Audio: this Audio has no playback control.');
+ return;
+ }
+
+ this.loop = value;
+
+ if (this.isPlaying === true) {
+ this.source.loop = this.loop;
+ }
+
+ return this;
+ }
+
+ setLoopStart(value) {
+ this.loopStart = value;
+ return this;
+ }
+
+ setLoopEnd(value) {
+ this.loopEnd = value;
+ return this;
+ }
+
+ getVolume() {
+ return this.gain.gain.value;
+ }
+
+ setVolume(value) {
+ this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
+ return this;
+ }
+
+}
+
+const _position = /*@__PURE__*/new Vector3();
+
+const _quaternion = /*@__PURE__*/new Quaternion();
+
+const _scale = /*@__PURE__*/new Vector3();
+
+const _orientation = /*@__PURE__*/new Vector3();
+
+class PositionalAudio extends Audio {
+ constructor(listener) {
+ super(listener);
+ this.panner = this.context.createPanner();
+ this.panner.panningModel = 'HRTF';
+ this.panner.connect(this.gain);
+ }
+
+ getOutput() {
+ return this.panner;
+ }
+
+ getRefDistance() {
+ return this.panner.refDistance;
+ }
+
+ setRefDistance(value) {
+ this.panner.refDistance = value;
+ return this;
+ }
+
+ getRolloffFactor() {
+ return this.panner.rolloffFactor;
+ }
+
+ setRolloffFactor(value) {
+ this.panner.rolloffFactor = value;
+ return this;
+ }
+
+ getDistanceModel() {
+ return this.panner.distanceModel;
+ }
+
+ setDistanceModel(value) {
+ this.panner.distanceModel = value;
+ return this;
+ }
+
+ getMaxDistance() {
+ return this.panner.maxDistance;
+ }
+
+ setMaxDistance(value) {
+ this.panner.maxDistance = value;
+ return this;
+ }
+
+ 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) {
+ // code path for Chrome and Firefox (see #14393)
+ 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 {
+ 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);
+ }
+
+ getFrequencyData() {
+ this.analyser.getByteFrequencyData(this.data);
+ return this.data;
+ }
+
+ 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 {
+ constructor(binding, typeName, valueSize) {
+ this.binding = binding;
+ this.valueSize = valueSize;
+ let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
+ //
+ // interpolators can use .buffer as their .result
+ // the data then goes to 'incoming'
+ //
+ // 'accu0' and 'accu1' are used frame-interleaved for
+ // the cumulative result and are compared to detect
+ // changes
+ //
+ // 'orig' stores the original state of the property
+ //
+ // 'add' is used for additive cumulative results
+ //
+ // 'work' is optional and is only present for quaternion types. It is used
+ // to store intermediate quaternion multiplication results
+
+ 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; // Use the regular mix function and for additive on these types,
+ // additive is not relevant for non-numeric types
+
+ 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;
+ } // accumulate data in the 'incoming' region into 'accu<i>'
+
+
+ accumulate(accuIndex, weight) {
+ // note: happily accumulating nothing when weight = 0, the caller knows
+ // the weight and shouldn't have made the call in the first place
+ const buffer = this.buffer,
+ stride = this.valueSize,
+ offset = accuIndex * stride + stride;
+ let currentWeight = this.cumulativeWeight;
+
+ if (currentWeight === 0) {
+ // accuN := incoming * weight
+ for (let i = 0; i !== stride; ++i) {
+ buffer[offset + i] = buffer[i];
+ }
+
+ currentWeight = weight;
+ } else {
+ // accuN := accuN + incoming * weight
+ currentWeight += weight;
+ const mix = weight / currentWeight;
+
+ this._mixBufferRegion(buffer, offset, 0, mix, stride);
+ }
+
+ this.cumulativeWeight = currentWeight;
+ } // accumulate data in the 'incoming' region into 'add'
+
+
+ accumulateAdditive(weight) {
+ const buffer = this.buffer,
+ stride = this.valueSize,
+ offset = stride * this._addIndex;
+
+ if (this.cumulativeWeightAdditive === 0) {
+ // add = identity
+ this._setIdentity();
+ } // add := add + incoming * weight
+
+
+ this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
+
+ this.cumulativeWeightAdditive += weight;
+ } // apply the state of 'accu<i>' to the binding when accus differ
+
+
+ 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) {
+ // accuN := accuN + original * ( 1 - cumulativeWeight )
+ const originalValueOffset = stride * this._origIndex;
+
+ this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
+ }
+
+ if (weightAdditive > 0) {
+ // accuN := accuN + additive accuN
+ 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]) {
+ // value has changed -> update scene graph
+ binding.setValue(buffer, offset);
+ break;
+ }
+ }
+ } // remember 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); // accu[0..1] := orig -- initially detect changes against the original
+
+ for (let i = stride, e = originalValueOffset; i !== e; ++i) {
+ buffer[i] = buffer[originalValueOffset + i % stride];
+ } // Add to identity for additive
+
+
+ this._setIdentity();
+
+ this.cumulativeWeight = 0;
+ this.cumulativeWeightAdditive = 0;
+ } // apply the state previously taken via 'saveOriginalState' to the binding
+
+
+ restoreOriginalState() {
+ const originalValueOffset = this.valueSize * 3;
+ this.binding.setValue(this.buffer, originalValueOffset);
+ }
+
+ _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; // Store result in intermediate buffer offset
+
+ Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
+
+ 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;
+ }
+ }
+
+}
+
+// Characters [].:/ are reserved for track binding syntax.
+const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
+
+const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
+// only latin characters, and the unicode \p{L} is not yet supported. So
+// instead, we exclude reserved characters and match everything else.
+
+
+const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
+
+const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
+// be matched to parse the rest of the track name.
+
+
+const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
+
+
+const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
+// characters. Accessor may contain any character except closing bracket.
+
+
+const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
+// contain any non-bracket characters.
+
+
+const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
+
+const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
+
+const _supportedObjectNames = ['material', 'materials', 'bones'];
+
+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(); // bind all binding
+
+ const firstValidIndex = this._targetGroup.nCachedObjects_,
+ binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
+
+ if (binding !== undefined) 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();
+ }
+ }
+
+} // Note: This class uses a State pattern on a per-method basis:
+// 'bind' sets 'this.getValue' / 'setValue' and shadows the
+// prototype version of these methods with one that represents
+// the bound state. When the property is not found, the methods
+// become no-ops.
+
+
+class PropertyBinding {
+ constructor(rootNode, path, parsedPath) {
+ this.path = path;
+ this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
+ this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
+ this.rootNode = rootNode; // initial state of these methods that calls 'bind'
+
+ this.getValue = this._getValue_unbound;
+ this.setValue = this._setValue_unbound;
+ }
+
+ 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}
+ */
+
+
+ static sanitizeNodeName(name) {
+ return name.replace(/\s/g, '_').replace(_reservedRe, '');
+ }
+
+ static parseTrackName(trackName) {
+ const matches = _trackRe.exec(trackName);
+
+ if (!matches) {
+ 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 !== undefined && lastDot !== -1) {
+ const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
+ // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
+ // 'bar' could be the objectName, or part of a nodeName (which can
+ // include '.' characters).
+
+ 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;
+ }
+
+ static findNode(root, nodeName) {
+ if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
+ return root;
+ } // search into skeleton bones.
+
+
+ if (root.skeleton) {
+ const bone = root.skeleton.getBoneByName(nodeName);
+
+ if (bone !== undefined) {
+ return bone;
+ }
+ } // search into node subtree.
+
+
+ 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);
+ } // create getter / setter pair for a property in the scene graph
+
+
+ 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.rootNode;
+ this.node = targetObject;
+ } // set fail state so we can just 'return' on error
+
+
+ this.getValue = this._getValue_unavailable;
+ this.setValue = this._setValue_unavailable; // ensure there is a value node
+
+ if (!targetObject) {
+ console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
+ return;
+ }
+
+ if (objectName) {
+ let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
+
+ switch (objectName) {
+ case 'materials':
+ if (!targetObject.material) {
+ console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
+ return;
+ }
+
+ if (!targetObject.material.materials) {
+ console.error('THREE.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) {
+ console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
+ return;
+ } // potential future optimization: skip this if propertyIndex is already an integer
+ // and convert the integer string to a true integer.
+
+
+ targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
+
+ for (let i = 0; i < targetObject.length; i++) {
+ if (targetObject[i].name === objectIndex) {
+ objectIndex = i;
+ break;
+ }
+ }
+
+ break;
+
+ default:
+ if (targetObject[objectName] === undefined) {
+ console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
+ return;
+ }
+
+ targetObject = targetObject[objectName];
+ }
+
+ if (objectIndex !== undefined) {
+ if (targetObject[objectIndex] === undefined) {
+ console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
+ return;
+ }
+
+ targetObject = targetObject[objectIndex];
+ }
+ } // resolve property
+
+
+ const nodeProperty = targetObject[propertyName];
+
+ if (nodeProperty === undefined) {
+ const nodeName = parsedPath.nodeName;
+ console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
+ return;
+ } // determine versioning scheme
+
+
+ let versioning = this.Versioning.None;
+ this.targetObject = targetObject;
+
+ if (targetObject.needsUpdate !== undefined) {
+ // material
+ versioning = this.Versioning.NeedsUpdate;
+ } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
+ // node transform
+ versioning = this.Versioning.MatrixWorldNeedsUpdate;
+ } // determine how the property gets bound
+
+
+ let bindingType = this.BindingType.Direct;
+
+ if (propertyIndex !== undefined) {
+ // access a sub element of the property array (only primitives are supported right now)
+ if (propertyName === 'morphTargetInfluences') {
+ // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
+ // support resolving morphTarget names into indices.
+ if (!targetObject.geometry) {
+ console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
+ return;
+ }
+
+ if (targetObject.geometry.isBufferGeometry) {
+ if (!targetObject.geometry.morphAttributes) {
+ console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
+ return;
+ }
+
+ if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
+ propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
+ }
+ } else {
+ console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
+ return;
+ }
+ }
+
+ bindingType = this.BindingType.ArrayElement;
+ this.resolvedProperty = nodeProperty;
+ this.propertyIndex = propertyIndex;
+ } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
+ // must use copy for Object3D.Euler/Quaternion
+ bindingType = this.BindingType.HasFromToArray;
+ this.resolvedProperty = nodeProperty;
+ } else if (Array.isArray(nodeProperty)) {
+ bindingType = this.BindingType.EntireArray;
+ this.resolvedProperty = nodeProperty;
+ } else {
+ this.propertyName = propertyName;
+ } // select getter / setter
+
+
+ this.getValue = this.GetterByBindingType[bindingType];
+ this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
+ }
+
+ unbind() {
+ this.node = null; // back to the prototype version of getValue / setValue
+ // note: avoiding to mutate the shape of 'this' via 'delete'
+
+ 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]];
+
+/**
+ *
+ * A group of objects that receives a shared animation state.
+ *
+ * Usage:
+ *
+ * - Add objects you would otherwise pass as 'root' to the
+ * constructor or the .clipAction method of AnimationMixer.
+ *
+ * - Instead pass this object as 'root'.
+ *
+ * - You can also add and remove objects later when the mixer
+ * is running.
+ *
+ * Note:
+ *
+ * Objects of this class appear as one object to the mixer,
+ * so cache control of the individual objects must be done
+ * on the group.
+ *
+ * Limitation:
+ *
+ * - The animated properties must be compatible among the
+ * all objects in the group.
+ *
+ * - A single property can either be controlled through a
+ * target group or directly, but not both.
+ */
+
+class AnimationObjectGroup {
+ constructor() {
+ this.uuid = generateUUID(); // cached objects followed by the active ones
+
+ this._objects = Array.prototype.slice.call(arguments);
+ this.nCachedObjects_ = 0; // threshold
+ // note: read by PropertyBinding.Composite
+
+ const indices = {};
+ this._indicesByUUID = indices; // for bookkeeping
+
+ for (let i = 0, n = arguments.length; i !== n; ++i) {
+ indices[arguments[i].uuid] = i;
+ }
+
+ this._paths = []; // inside: string
+
+ this._parsedPaths = []; // inside: { we don't care, here }
+
+ this._bindings = []; // inside: Array< PropertyBinding >
+
+ this._bindingsIndicesByPath = {}; // inside: indices in these arrays
+
+ 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;
+ }
+
+ };
+ }
+
+ add() {
+ const objects = this._objects,
+ indicesByUUID = this._indicesByUUID,
+ paths = this._paths,
+ parsedPaths = this._parsedPaths,
+ bindings = this._bindings,
+ nBindings = bindings.length;
+ let knownObject = undefined,
+ 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 === undefined) {
+ // unknown object -> add it to the ACTIVE region
+ index = nObjects++;
+ indicesByUUID[uuid] = index;
+ objects.push(object); // accounting is done, now do the same for all bindings
+
+ 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]; // move existing object to the ACTIVE region
+
+ const firstActiveIndex = --nCachedObjects,
+ lastCachedObject = objects[firstActiveIndex];
+ indicesByUUID[lastCachedObject.uuid] = index;
+ objects[index] = lastCachedObject;
+ indicesByUUID[uuid] = firstActiveIndex;
+ objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
+
+ 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 === undefined) {
+ // since we do not bother to create new bindings
+ // for objects that are cached, the binding may
+ // or may not exist
+ binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
+ }
+
+ bindingsForPath[firstActiveIndex] = binding;
+ }
+ } else if (objects[index] !== knownObject) {
+ console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
+ } // else the object is already where we want it to be
+
+ } // for arguments
+
+
+ this.nCachedObjects_ = nCachedObjects;
+ }
+
+ 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 !== undefined && index >= nCachedObjects) {
+ // move existing object into the CACHED region
+ const lastCachedIndex = nCachedObjects++,
+ firstActiveObject = objects[lastCachedIndex];
+ indicesByUUID[firstActiveObject.uuid] = index;
+ objects[index] = firstActiveObject;
+ indicesByUUID[uuid] = lastCachedIndex;
+ objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
+
+ 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;
+ }
+ }
+ } // for arguments
+
+
+ this.nCachedObjects_ = nCachedObjects;
+ } // remove & forget
+
+
+ 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 !== undefined) {
+ delete indicesByUUID[uuid];
+
+ if (index < nCachedObjects) {
+ // object is cached, shrink the CACHED region
+ const firstActiveIndex = --nCachedObjects,
+ lastCachedObject = objects[firstActiveIndex],
+ lastIndex = --nObjects,
+ lastObject = objects[lastIndex]; // last cached object takes this object's place
+
+ indicesByUUID[lastCachedObject.uuid] = index;
+ objects[index] = lastCachedObject; // last object goes to the activated slot and pop
+
+ indicesByUUID[lastObject.uuid] = firstActiveIndex;
+ objects[firstActiveIndex] = lastObject;
+ objects.pop(); // accounting is done, now do the same for all bindings
+
+ 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 {
+ // object is active, just swap with the last and pop
+ const lastIndex = --nObjects,
+ lastObject = objects[lastIndex];
+
+ if (lastIndex > 0) {
+ indicesByUUID[lastObject.uuid] = index;
+ }
+
+ objects[index] = lastObject;
+ objects.pop(); // accounting is done, now do the same for all bindings
+
+ for (let j = 0, m = nBindings; j !== m; ++j) {
+ const bindingsForPath = bindings[j];
+ bindingsForPath[index] = bindingsForPath[lastIndex];
+ bindingsForPath.pop();
+ }
+ } // cached or active
+
+ } // if object is known
+
+ } // for arguments
+
+
+ this.nCachedObjects_ = nCachedObjects;
+ } // Internal interface used by befriended PropertyBinding.Composite:
+
+
+ subscribe_(path, parsedPath) {
+ // returns an array of bindings for the given path that is changed
+ // according to the contained objects in the group
+ const indicesByPath = this._bindingsIndicesByPath;
+ let index = indicesByPath[path];
+ const bindings = this._bindings;
+ if (index !== undefined) 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) {
+ // tells the group to forget about a property path and no longer
+ // update the array previously obtained with 'subscribe_'
+ const indicesByPath = this._bindingsIndicesByPath,
+ index = indicesByPath[path];
+
+ if (index !== undefined) {
+ 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();
+ }
+ }
+
+}
+
+AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
+
+class AnimationAction {
+ 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;
+ interpolant.settings = interpolantSettings;
+ }
+
+ this._interpolantSettings = interpolantSettings;
+ this._interpolants = interpolants; // bound by the mixer
+ // inside: PropertyMixer (managed by the mixer)
+
+ this._propertyBindings = new Array(nTracks);
+ this._cacheIndex = null; // for the memory manager
+
+ this._byClipCacheIndex = null; // for the memory manager
+
+ this._timeScaleInterpolant = null;
+ this._weightInterpolant = null;
+ this.loop = LoopRepeat;
+ this._loopCount = -1; // global mixer time when the action is to be started
+ // it's set back to 'null' upon start of the action
+
+ this._startTime = null; // scaled local time of the action
+ // gets clamped or wrapped to 0..clip.duration according to loop
+
+ this.time = 0;
+ this.timeScale = 1;
+ this._effectiveTimeScale = 1;
+ this.weight = 1;
+ this._effectiveWeight = 1;
+ this.repetitions = Infinity; // no. of repetitions when looping
+
+ this.paused = false; // true -> zero effective time scale
+
+ this.enabled = true; // false -> zero effective weight
+
+ this.clampWhenFinished = false; // keep feeding the last frame?
+
+ this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
+
+ this.zeroSlopeAtEnd = true; // clips for start, loop and end
+ } // State & Scheduling
+
+
+ play() {
+ this._mixer._activateAction(this);
+
+ return this;
+ }
+
+ stop() {
+ this._mixer._deactivateAction(this);
+
+ return this.reset();
+ }
+
+ reset() {
+ this.paused = false;
+ this.enabled = true;
+ this.time = 0; // restart clip
+
+ this._loopCount = -1; // forget previous loops
+
+ this._startTime = null; // forget scheduling
+
+ return this.stopFading().stopWarping();
+ }
+
+ isRunning() {
+ return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
+ } // return true when play has been called
+
+
+ isScheduled() {
+ return this._mixer._isActiveAction(this);
+ }
+
+ startAt(time) {
+ this._startTime = time;
+ return this;
+ }
+
+ setLoop(mode, repetitions) {
+ this.loop = mode;
+ this.repetitions = repetitions;
+ return this;
+ } // Weight
+ // set the weight stopping any scheduled fading
+ // although .enabled = false yields an effective weight of zero, this
+ // method does *not* change .enabled, because it would be confusing
+
+
+ setEffectiveWeight(weight) {
+ this.weight = weight; // note: same logic as when updated at runtime
+
+ this._effectiveWeight = this.enabled ? weight : 0;
+ return this.stopFading();
+ } // return the weight considering fading and .enabled
+
+
+ getEffectiveWeight() {
+ return this._effectiveWeight;
+ }
+
+ fadeIn(duration) {
+ return this._scheduleFading(duration, 0, 1);
+ }
+
+ fadeOut(duration) {
+ return this._scheduleFading(duration, 1, 0);
+ }
+
+ crossFadeFrom(fadeOutAction, duration, warp) {
+ fadeOutAction.fadeOut(duration);
+ this.fadeIn(duration);
+
+ if (warp) {
+ const fadeInDuration = this._clip.duration,
+ fadeOutDuration = fadeOutAction._clip.duration,
+ startEndRatio = fadeOutDuration / fadeInDuration,
+ endStartRatio = fadeInDuration / fadeOutDuration;
+ fadeOutAction.warp(1.0, startEndRatio, duration);
+ this.warp(endStartRatio, 1.0, duration);
+ }
+
+ return this;
+ }
+
+ crossFadeTo(fadeInAction, duration, warp) {
+ return fadeInAction.crossFadeFrom(this, duration, warp);
+ }
+
+ stopFading() {
+ const weightInterpolant = this._weightInterpolant;
+
+ if (weightInterpolant !== null) {
+ this._weightInterpolant = null;
+
+ this._mixer._takeBackControlInterpolant(weightInterpolant);
+ }
+
+ return this;
+ } // Time Scale Control
+ // set the time scale stopping any scheduled warping
+ // although .paused = true yields an effective time scale of zero, this
+ // method does *not* change .paused, because it would be confusing
+
+
+ setEffectiveTimeScale(timeScale) {
+ this.timeScale = timeScale;
+ this._effectiveTimeScale = this.paused ? 0 : timeScale;
+ return this.stopWarping();
+ } // return the time scale considering warping and .paused
+
+
+ getEffectiveTimeScale() {
+ return this._effectiveTimeScale;
+ }
+
+ setDuration(duration) {
+ this.timeScale = this._clip.duration / duration;
+ return this.stopWarping();
+ }
+
+ syncWith(action) {
+ this.time = action.time;
+ this.timeScale = action.timeScale;
+ return this.stopWarping();
+ }
+
+ halt(duration) {
+ return this.warp(this._effectiveTimeScale, 0, duration);
+ }
+
+ 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;
+ }
+
+ stopWarping() {
+ const timeScaleInterpolant = this._timeScaleInterpolant;
+
+ if (timeScaleInterpolant !== null) {
+ this._timeScaleInterpolant = null;
+
+ this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
+ }
+
+ return this;
+ } // Object Accessors
+
+
+ getMixer() {
+ return this._mixer;
+ }
+
+ getClip() {
+ return this._clip;
+ }
+
+ getRoot() {
+ return this._localRoot || this._mixer._root;
+ } // Interna
+
+
+ _update(time, deltaTime, timeDirection, accuIndex) {
+ // called by the mixer
+ if (!this.enabled) {
+ // call ._updateWeight() to update ._effectiveWeight
+ this._updateWeight(time);
+
+ return;
+ }
+
+ const startTime = this._startTime;
+
+ if (startTime !== null) {
+ // check for scheduled start of action
+ const timeRunning = (time - startTime) * timeDirection;
+
+ if (timeRunning < 0 || timeDirection === 0) {
+ return; // yet to come / don't decide when delta = 0
+ } // start
+
+
+ this._startTime = null; // unschedule
+
+ deltaTime = timeDirection * timeRunning;
+ } // apply time scale and advance time
+
+
+ deltaTime *= this._updateTimeScale(time);
+
+ const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
+ // an effective weight of 0
+
+
+ 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) {
+ // faded out, disable
+ 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) {
+ // motion has halted, pause
+ this.paused = true;
+ } else {
+ // warp done - apply final time scale
+ 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) {
+ // just started
+ 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 {
+ // repetitive Repeat or PingPong
+ if (loopCount === -1) {
+ // just started
+ if (deltaTime >= 0) {
+ loopCount = 0;
+
+ this._setEndings(true, this.repetitions === 0, pingPong);
+ } else {
+ // when looping in reverse direction, the initial
+ // transition through zero counts as a repetition,
+ // so leave loopCount at -1
+ this._setEndings(this.repetitions === 0, true, pingPong);
+ }
+ }
+
+ if (time >= duration || time < 0) {
+ // wrap around
+ const loopDelta = Math.floor(time / duration); // signed
+
+ time -= duration * loopDelta;
+ loopCount += Math.abs(loopDelta);
+ const pending = this.repetitions - loopCount;
+
+ if (pending <= 0) {
+ // have to stop (switch state, clamp time, fire event)
+ 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 {
+ // keep running
+ if (pending === 1) {
+ // entering the last round
+ 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: loopDelta
+ });
+ }
+ } else {
+ this.time = time;
+ }
+
+ if (pingPong && (loopCount & 1) === 1) {
+ // invert time for the "pong round"
+ return duration - time;
+ }
+ }
+
+ return time;
+ }
+
+ _setEndings(atStart, atEnd, pingPong) {
+ const settings = this._interpolantSettings;
+
+ if (pingPong) {
+ settings.endingStart = ZeroSlopeEnding;
+ settings.endingEnd = ZeroSlopeEnding;
+ } else {
+ // assuming for LoopOnce atStart == atEnd == true
+ 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;
+ }
+
+}
+
+class AnimationMixer extends EventDispatcher {
+ constructor(root) {
+ super();
+ this._root = root;
+
+ this._initMemoryManager();
+
+ this._accuIndex = 0;
+ this.time = 0;
+ this.timeScale = 1.0;
+ }
+
+ _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 === undefined) {
+ bindingsByName = {};
+ bindingsByRoot[rootUuid] = bindingsByName;
+ }
+
+ for (let i = 0; i !== nTracks; ++i) {
+ const track = tracks[i],
+ trackName = track.name;
+ let binding = bindingsByName[trackName];
+
+ if (binding !== undefined) {
+ ++binding.referenceCount;
+ bindings[i] = binding;
+ } else {
+ binding = bindings[i];
+
+ if (binding !== undefined) {
+ // existing binding, make sure the cache knows
+ 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) {
+ // this action has been forgotten by the cache, but the user
+ // appears to be still using it -> rebind
+ 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; // increment reference counts / sort out state
+
+ 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; // decrement reference counts / sort out state
+
+ 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 = []; // 'nActiveActions' followed by inactive ones
+
+ this._nActiveActions = 0;
+ this._actionsByClip = {}; // inside:
+ // {
+ // knownActions: Array< AnimationAction > - used as prototypes
+ // actionByRoot: AnimationAction - lookup
+ // }
+
+ this._bindings = []; // 'nActiveBindings' followed by inactive ones
+
+ this._nActiveBindings = 0;
+ this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
+
+ this._controlInterpolants = []; // same game as above
+
+ 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 === undefined) {
+ 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) {
+ // [ active actions | inactive actions ]
+ // [ active actions >| inactive actions ]
+ // s a
+ // <-swap->
+ // a s
+ 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) {
+ // [ active actions | inactive actions ]
+ // [ active actions |< inactive actions ]
+ // a s
+ // <-swap->
+ // s a
+ 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 === undefined) {
+ 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 === undefined) {
+ interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._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;
+ } // return an action for a clip optionally using a custom root target
+ // object (this method allocates a lot of dynamic memory in case a
+ // previously unknown clip/root combination is specified)
+
+
+ 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 === undefined) {
+ if (clipObject !== null) {
+ blendMode = clipObject.blendMode;
+ } else {
+ blendMode = NormalAnimationBlendMode;
+ }
+ }
+
+ if (actionsForClip !== undefined) {
+ const existingAction = actionsForClip.actionByRoot[rootUuid];
+
+ if (existingAction !== undefined && existingAction.blendMode === blendMode) {
+ return existingAction;
+ } // we know the clip, so we don't have to parse all
+ // the bindings again but can just copy
+
+
+ prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
+
+ if (clipObject === null) clipObject = prototypeAction._clip;
+ } // clip must be known when specified via string
+
+
+ if (clipObject === null) return null; // allocate all resources required to run it
+
+ const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
+
+ this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
+
+
+ this._addInactiveAction(newAction, clipUuid, rootUuid);
+
+ return newAction;
+ } // get an existing action
+
+
+ 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 !== undefined) {
+ return actionsForClip.actionByRoot[rootUuid] || null;
+ }
+
+ return null;
+ } // deactivates all previously scheduled actions
+
+
+ stopAllAction() {
+ const actions = this._actions,
+ nActions = this._nActiveActions;
+
+ for (let i = nActions - 1; i >= 0; --i) {
+ actions[i].stop();
+ }
+
+ return this;
+ } // advance the time and update apply the animation
+
+
+ update(deltaTime) {
+ deltaTime *= this.timeScale;
+ const actions = this._actions,
+ nActions = this._nActiveActions,
+ time = this.time += deltaTime,
+ timeDirection = Math.sign(deltaTime),
+ accuIndex = this._accuIndex ^= 1; // run active actions
+
+ for (let i = 0; i !== nActions; ++i) {
+ const action = actions[i];
+
+ action._update(time, deltaTime, timeDirection, accuIndex);
+ } // update scene graph
+
+
+ const bindings = this._bindings,
+ nBindings = this._nActiveBindings;
+
+ for (let i = 0; i !== nBindings; ++i) {
+ bindings[i].apply(accuIndex);
+ }
+
+ return this;
+ } // Allows you to seek to a specific time in an animation.
+
+
+ setTime(timeInSeconds) {
+ this.time = 0; // Zero out time attribute for AnimationMixer object;
+
+ for (let i = 0; i < this._actions.length; i++) {
+ this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
+ }
+
+ return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
+ } // return this mixer's root target object
+
+
+ getRoot() {
+ return this._root;
+ } // free all resources specific to a particular clip
+
+
+ uncacheClip(clip) {
+ const actions = this._actions,
+ clipUuid = clip.uuid,
+ actionsByClip = this._actionsByClip,
+ actionsForClip = actionsByClip[clipUuid];
+
+ if (actionsForClip !== undefined) {
+ // note: just calling _removeInactiveAction would mess up the
+ // iteration state and also require updating the state we can
+ // just throw away
+ 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];
+ }
+ } // free all resources specific to a particular root target object
+
+
+ uncacheRoot(root) {
+ const rootUuid = root.uuid,
+ actionsByClip = this._actionsByClip;
+
+ for (const clipUuid in actionsByClip) {
+ const actionByRoot = actionsByClip[clipUuid].actionByRoot,
+ action = actionByRoot[rootUuid];
+
+ if (action !== undefined) {
+ this._deactivateAction(action);
+
+ this._removeInactiveAction(action);
+ }
+ }
+
+ const bindingsByRoot = this._bindingsByRootAndName,
+ bindingByName = bindingsByRoot[rootUuid];
+
+ if (bindingByName !== undefined) {
+ for (const trackName in bindingByName) {
+ const binding = bindingByName[trackName];
+ binding.restoreOriginalState();
+
+ this._removeInactiveBinding(binding);
+ }
+ }
+ } // remove a targeted clip from the cache
+
+
+ uncacheAction(clip, optionalRoot) {
+ const action = this.existingAction(clip, optionalRoot);
+
+ if (action !== null) {
+ this._deactivateAction(action);
+
+ this._removeInactiveAction(action);
+ }
+ }
+
+}
+
+AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
+
+class Uniform {
+ constructor(value) {
+ if (typeof value === 'string') {
+ console.warn('THREE.Uniform: Type parameter is no longer needed.');
+ value = arguments[1];
+ }
+
+ this.value = value;
+ }
+
+ clone() {
+ return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
+ }
+
+}
+
+class InstancedInterleavedBuffer extends InterleavedBuffer {
+ constructor(array, stride, meshPerAttribute = 1) {
+ super(array, stride);
+ 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;
+ }
+
+}
+
+InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
+
+class GLBufferAttribute {
+ constructor(buffer, type, itemSize, elementSize, count) {
+ this.buffer = buffer;
+ this.type = type;
+ this.itemSize = itemSize;
+ this.elementSize = elementSize;
+ this.count = count;
+ this.version = 0;
+ }
+
+ set needsUpdate(value) {
+ if (value === true) this.version++;
+ }
+
+ setBuffer(buffer) {
+ this.buffer = buffer;
+ return this;
+ }
+
+ setType(type, elementSize) {
+ this.type = type;
+ this.elementSize = elementSize;
+ return this;
+ }
+
+ setItemSize(itemSize) {
+ this.itemSize = itemSize;
+ return this;
+ }
+
+ setCount(count) {
+ this.count = count;
+ return this;
+ }
+
+}
+
+GLBufferAttribute.prototype.isGLBufferAttribute = true;
+
+class Raycaster {
+ constructor(origin, direction, near = 0, far = Infinity) {
+ this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
+
+ this.near = near;
+ this.far = far;
+ this.camera = null;
+ this.layers = new Layers();
+ this.params = {
+ Mesh: {},
+ Line: {
+ threshold: 1
+ },
+ LOD: {},
+ Points: {
+ threshold: 1
+ },
+ Sprite: {}
+ };
+ }
+
+ set(origin, direction) {
+ // direction is assumed to be normalized (for accurate distance calculations)
+ this.ray.set(origin, direction);
+ }
+
+ setFromCamera(coords, camera) {
+ if (camera && 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 && camera.isOrthographicCamera) {
+ this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
+
+ this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
+ this.camera = camera;
+ } else {
+ console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
+ }
+ }
+
+ intersectObject(object, recursive = true, intersects = []) {
+ intersectObject(object, this, intersects, recursive);
+ intersects.sort(ascSort);
+ return intersects;
+ }
+
+ intersectObjects(objects, recursive = true, intersects = []) {
+ for (let i = 0, l = objects.length; i < l; i++) {
+ intersectObject(objects[i], this, intersects, recursive);
+ }
+
+ intersects.sort(ascSort);
+ return intersects;
+ }
+
+}
+
+function ascSort(a, b) {
+ return a.distance - b.distance;
+}
+
+function intersectObject(object, raycaster, intersects, recursive) {
+ if (object.layers.test(raycaster.layers)) {
+ object.raycast(raycaster, intersects);
+ }
+
+ if (recursive === true) {
+ const children = object.children;
+
+ for (let i = 0, l = children.length; i < l; i++) {
+ intersectObject(children[i], raycaster, intersects, true);
+ }
+ }
+}
+
+/**
+ * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
+ *
+ * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
+ * The azimuthal angle (theta) is measured from the positive z-axis.
+ */
+
+class Spherical {
+ constructor(radius = 1, phi = 0, theta = 0) {
+ this.radius = radius;
+ this.phi = phi; // polar angle
+
+ this.theta = theta; // azimuthal angle
+
+ return this;
+ }
+
+ set(radius, phi, theta) {
+ this.radius = radius;
+ this.phi = phi;
+ this.theta = theta;
+ return this;
+ }
+
+ copy(other) {
+ this.radius = other.radius;
+ this.phi = other.phi;
+ this.theta = other.theta;
+ return this;
+ } // restrict phi to be betwee EPS and PI-EPS
+
+
+ makeSafe() {
+ const EPS = 0.000001;
+ this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
+ return this;
+ }
+
+ setFromVector3(v) {
+ return this.setFromCartesianCoords(v.x, v.y, v.z);
+ }
+
+ 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;
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+}
+
+/**
+ * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
+ */
+class Cylindrical {
+ constructor(radius = 1, theta = 0, y = 0) {
+ this.radius = radius; // distance from the origin to a point in the x-z plane
+
+ this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
+
+ this.y = y; // height above the x-z plane
+
+ return this;
+ }
+
+ set(radius, theta, y) {
+ this.radius = radius;
+ this.theta = theta;
+ this.y = y;
+ return this;
+ }
+
+ copy(other) {
+ this.radius = other.radius;
+ this.theta = other.theta;
+ this.y = other.y;
+ return this;
+ }
+
+ setFromVector3(v) {
+ return this.setFromCartesianCoords(v.x, v.y, v.z);
+ }
+
+ setFromCartesianCoords(x, y, z) {
+ this.radius = Math.sqrt(x * x + z * z);
+ this.theta = Math.atan2(x, z);
+ this.y = y;
+ return this;
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+}
+
+const _vector$4 = /*@__PURE__*/new Vector2();
+
+class Box2 {
+ constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
+ this.min = min;
+ this.max = max;
+ }
+
+ set(min, max) {
+ this.min.copy(min);
+ this.max.copy(max);
+ return this;
+ }
+
+ setFromPoints(points) {
+ this.makeEmpty();
+
+ for (let i = 0, il = points.length; i < il; i++) {
+ this.expandByPoint(points[i]);
+ }
+
+ return this;
+ }
+
+ 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;
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+ copy(box) {
+ this.min.copy(box.min);
+ this.max.copy(box.max);
+ return this;
+ }
+
+ makeEmpty() {
+ this.min.x = this.min.y = +Infinity;
+ this.max.x = this.max.y = -Infinity;
+ return this;
+ }
+
+ isEmpty() {
+ // 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;
+ }
+
+ getCenter(target) {
+ return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
+ }
+
+ getSize(target) {
+ return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
+ }
+
+ expandByPoint(point) {
+ this.min.min(point);
+ this.max.max(point);
+ return this;
+ }
+
+ expandByVector(vector) {
+ this.min.sub(vector);
+ this.max.add(vector);
+ return this;
+ }
+
+ expandByScalar(scalar) {
+ this.min.addScalar(-scalar);
+ this.max.addScalar(scalar);
+ return this;
+ }
+
+ containsPoint(point) {
+ return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
+ }
+
+ 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;
+ }
+
+ getParameter(point, target) {
+ // This can potentially have a divide by zero if the box
+ // has a size dimension of 0.
+ return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y));
+ }
+
+ intersectsBox(box) {
+ // using 4 splitting planes to rule out intersections
+ 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 ? false : true;
+ }
+
+ clampPoint(point, target) {
+ return target.copy(point).clamp(this.min, this.max);
+ }
+
+ distanceToPoint(point) {
+ const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
+
+ return clampedPoint.sub(point).length();
+ }
+
+ intersect(box) {
+ this.min.max(box.min);
+ this.max.min(box.max);
+ return this;
+ }
+
+ union(box) {
+ this.min.min(box.min);
+ this.max.max(box.max);
+ return this;
+ }
+
+ translate(offset) {
+ this.min.add(offset);
+ this.max.add(offset);
+ return this;
+ }
+
+ equals(box) {
+ return box.min.equals(this.min) && box.max.equals(this.max);
+ }
+
+}
+
+Box2.prototype.isBox2 = true;
+
+const _startP = /*@__PURE__*/new Vector3();
+
+const _startEnd = /*@__PURE__*/new Vector3();
+
+class Line3 {
+ constructor(start = new Vector3(), end = new Vector3()) {
+ this.start = start;
+ this.end = end;
+ }
+
+ set(start, end) {
+ this.start.copy(start);
+ this.end.copy(end);
+ return this;
+ }
+
+ copy(line) {
+ this.start.copy(line.start);
+ this.end.copy(line.end);
+ return this;
+ }
+
+ getCenter(target) {
+ return target.addVectors(this.start, this.end).multiplyScalar(0.5);
+ }
+
+ delta(target) {
+ return target.subVectors(this.end, this.start);
+ }
+
+ distanceSq() {
+ return this.start.distanceToSquared(this.end);
+ }
+
+ distance() {
+ return this.start.distanceTo(this.end);
+ }
+
+ at(t, target) {
+ return this.delta(target).multiplyScalar(t).add(this.start);
+ }
+
+ closestPointToPointParameter(point, clampToLine) {
+ _startP.subVectors(point, this.start);
+
+ _startEnd.subVectors(this.end, this.start);
+
+ const startEnd2 = _startEnd.dot(_startEnd);
+
+ const startEnd_startP = _startEnd.dot(_startP);
+
+ let t = startEnd_startP / startEnd2;
+
+ if (clampToLine) {
+ t = clamp(t, 0, 1);
+ }
+
+ return t;
+ }
+
+ closestPointToPoint(point, clampToLine, target) {
+ const t = this.closestPointToPointParameter(point, clampToLine);
+ return this.delta(target).multiplyScalar(t).add(this.start);
+ }
+
+ applyMatrix4(matrix) {
+ this.start.applyMatrix4(matrix);
+ this.end.applyMatrix4(matrix);
+ return this;
+ }
+
+ equals(line) {
+ return line.start.equals(this.start) && line.end.equals(this.end);
+ }
+
+ clone() {
+ return new this.constructor().copy(this);
+ }
+
+}
+
+const _vector$3 = /*@__PURE__*/new Vector3();
+
+class SpotLightHelper extends Object3D {
+ constructor(light, color) {
+ super();
+ this.light = light;
+ this.light.updateMatrixWorld();
+ this.matrix = light.matrixWorld;
+ this.matrixAutoUpdate = false;
+ this.color = color;
+ 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();
+ }
+
+ dispose() {
+ this.cone.geometry.dispose();
+ this.cone.material.dispose();
+ }
+
+ update() {
+ this.light.updateMatrixWorld();
+ const coneLength = this.light.distance ? this.light.distance : 1000;
+ 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 !== undefined) {
+ 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 {
+ constructor(object) {
+ const bones = getBoneList(object);
+ const geometry = new BufferGeometry();
+ const vertices = [];
+ const colors = [];
+ const color1 = new Color(0, 0, 1);
+ const color2 = new Color(0, 1, 0);
+
+ 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(color1.r, color1.g, color1.b);
+ colors.push(color2.r, color2.g, color2.b);
+ }
+ }
+
+ 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.type = 'SkeletonHelper';
+ this.isSkeletonHelper = true;
+ this.root = object;
+ this.bones = bones;
+ this.matrix = object.matrixWorld;
+ this.matrixAutoUpdate = false;
+ }
+
+ 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);
+ }
+
+}
+
+function getBoneList(object) {
+ const boneList = [];
+
+ if (object && object.isBone) {
+ boneList.push(object);
+ }
+
+ for (let i = 0; i < object.children.length; i++) {
+ boneList.push.apply(boneList, getBoneList(object.children[i]));
+ }
+
+ return boneList;
+}
+
+class PointLightHelper extends Mesh {
+ 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.light.updateMatrixWorld();
+ this.color = color;
+ this.type = 'PointLightHelper';
+ this.matrix = this.light.matrixWorld;
+ this.matrixAutoUpdate = false;
+ this.update();
+ /*
+ // TODO: delete this comment?
+ const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
+ const 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 );
+ const d = light.distance;
+ if ( d === 0.0 ) {
+ this.lightDistance.visible = false;
+ } else {
+ this.lightDistance.scale.set( d, d, d );
+ }
+ this.add( this.lightDistance );
+ */
+ }
+
+ dispose() {
+ this.geometry.dispose();
+ this.material.dispose();
+ }
+
+ update() {
+ if (this.color !== undefined) {
+ this.material.color.set(this.color);
+ } else {
+ this.material.color.copy(this.light.color);
+ }
+ /*
+ const d = this.light.distance;
+ if ( d === 0.0 ) {
+ this.lightDistance.visible = false;
+ } else {
+ this.lightDistance.visible = true;
+ this.lightDistance.scale.set( d, d, d );
+ }
+ */
+
+ }
+
+}
+
+const _vector$1 = /*@__PURE__*/new Vector3();
+
+const _color1 = /*@__PURE__*/new Color();
+
+const _color2 = /*@__PURE__*/new Color();
+
+class HemisphereLightHelper extends Object3D {
+ constructor(light, size, color) {
+ super();
+ this.light = light;
+ this.light.updateMatrixWorld();
+ this.matrix = light.matrixWorld;
+ this.matrixAutoUpdate = false;
+ this.color = color;
+ const geometry = new OctahedronGeometry(size);
+ geometry.rotateY(Math.PI * 0.5);
+ this.material = new MeshBasicMaterial({
+ wireframe: true,
+ fog: false,
+ toneMapped: false
+ });
+ if (this.color === undefined) 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();
+ }
+
+ dispose() {
+ this.children[0].geometry.dispose();
+ this.children[0].material.dispose();
+ }
+
+ update() {
+ const mesh = this.children[0];
+
+ if (this.color !== undefined) {
+ 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;
+ }
+
+ mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
+ }
+
+}
+
+class GridHelper extends LineSegments {
+ constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
+ 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';
+ }
+
+}
+
+class PolarGridHelper extends LineSegments {
+ constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
+ color1 = new Color(color1);
+ color2 = new Color(color2);
+ const vertices = [];
+ const colors = []; // create the radials
+
+ for (let i = 0; i <= radials; i++) {
+ const v = i / radials * (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);
+ } // create the circles
+
+
+ for (let i = 0; i <= circles; i++) {
+ const color = i & 1 ? color1 : color2;
+ const r = radius - radius / circles * i;
+
+ for (let j = 0; j < divisions; j++) {
+ // first vertex
+ 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); // second vertex
+
+ 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';
+ }
+
+}
+
+const _v1 = /*@__PURE__*/new Vector3();
+
+const _v2 = /*@__PURE__*/new Vector3();
+
+const _v3 = /*@__PURE__*/new Vector3();
+
+class DirectionalLightHelper extends Object3D {
+ constructor(light, size, color) {
+ super();
+ this.light = light;
+ this.light.updateMatrixWorld();
+ this.matrix = light.matrixWorld;
+ this.matrixAutoUpdate = false;
+ this.color = color;
+ if (size === undefined) 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();
+ }
+
+ dispose() {
+ this.lightPlane.geometry.dispose();
+ this.lightPlane.material.dispose();
+ this.targetLine.geometry.dispose();
+ this.targetLine.material.dispose();
+ }
+
+ update() {
+ _v1.setFromMatrixPosition(this.light.matrixWorld);
+
+ _v2.setFromMatrixPosition(this.light.target.matrixWorld);
+
+ _v3.subVectors(_v2, _v1);
+
+ this.lightPlane.lookAt(_v2);
+
+ if (this.color !== undefined) {
+ 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();
+/**
+ * - shows frustum, line of sight and up of the camera
+ * - suitable for fast updates
+ * - based on frustum visualization in lightgl.js shadowmap example
+ * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
+ */
+
+
+class CameraHelper extends LineSegments {
+ constructor(camera) {
+ const geometry = new BufferGeometry();
+ const material = new LineBasicMaterial({
+ color: 0xffffff,
+ vertexColors: true,
+ toneMapped: false
+ });
+ const vertices = [];
+ const colors = [];
+ const pointMap = {}; // colors
+
+ const colorFrustum = new Color(0xffaa00);
+ const colorCone = new Color(0xff0000);
+ const colorUp = new Color(0x00aaff);
+ const colorTarget = new Color(0xffffff);
+ const colorCross = new Color(0x333333); // near
+
+ addLine('n1', 'n2', colorFrustum);
+ addLine('n2', 'n4', colorFrustum);
+ addLine('n4', 'n3', colorFrustum);
+ addLine('n3', 'n1', colorFrustum); // far
+
+ addLine('f1', 'f2', colorFrustum);
+ addLine('f2', 'f4', colorFrustum);
+ addLine('f4', 'f3', colorFrustum);
+ addLine('f3', 'f1', colorFrustum); // sides
+
+ addLine('n1', 'f1', colorFrustum);
+ addLine('n2', 'f2', colorFrustum);
+ addLine('n3', 'f3', colorFrustum);
+ addLine('n4', 'f4', colorFrustum); // cone
+
+ addLine('p', 'n1', colorCone);
+ addLine('p', 'n2', colorCone);
+ addLine('p', 'n3', colorCone);
+ addLine('p', 'n4', colorCone); // up
+
+ addLine('u1', 'u2', colorUp);
+ addLine('u2', 'u3', colorUp);
+ addLine('u3', 'u1', colorUp); // target
+
+ addLine('c', 't', colorTarget);
+ addLine('p', 'c', colorCross); // cross
+
+ addLine('cn1', 'cn2', colorCross);
+ addLine('cn3', 'cn4', colorCross);
+ addLine('cf1', 'cf2', colorCross);
+ addLine('cf3', 'cf4', colorCross);
+
+ function addLine(a, b, color) {
+ addPoint(a, color);
+ addPoint(b, color);
+ }
+
+ function addPoint(id, color) {
+ vertices.push(0, 0, 0);
+ colors.push(color.r, color.g, color.b);
+
+ if (pointMap[id] === undefined) {
+ 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();
+ }
+
+ update() {
+ const geometry = this.geometry;
+ const pointMap = this.pointMap;
+ const w = 1,
+ h = 1; // we need just camera projection matrix inverse
+ // world matrix must be identity
+
+ _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
+
+
+ setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
+ setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
+
+ setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
+ setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
+ setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
+ setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
+
+ setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
+ setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
+ setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
+ setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
+
+ setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
+ setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
+ setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
+
+ setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
+ setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
+ setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
+ setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
+ setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
+ setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
+ setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
+ setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
+ geometry.getAttribute('position').needsUpdate = true;
+ }
+
+ dispose() {
+ this.geometry.dispose();
+ this.material.dispose();
+ }
+
+}
+
+function setPoint(point, pointMap, geometry, camera, x, y, z) {
+ _vector.set(x, y, z).unproject(camera);
+
+ const points = pointMap[point];
+
+ if (points !== undefined) {
+ 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 {
+ constructor(object, color = 0xffff00) {
+ 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: color,
+ toneMapped: false
+ }));
+ this.object = object;
+ this.type = 'BoxHelper';
+ this.matrixAutoUpdate = false;
+ this.update();
+ }
+
+ update(object) {
+ if (object !== undefined) {
+ console.warn('THREE.BoxHelper: .update() has no longer arguments.');
+ }
+
+ if (this.object !== undefined) {
+ _box.setFromObject(this.object);
+ }
+
+ if (_box.isEmpty()) return;
+ const min = _box.min;
+ const max = _box.max;
+ /*
+ 5____4
+ 1/___0/|
+ | 6__|_7
+ 2/___3/
+ 0: max.x, max.y, max.z
+ 1: min.x, max.y, max.z
+ 2: min.x, min.y, max.z
+ 3: max.x, min.y, max.z
+ 4: max.x, max.y, min.z
+ 5: min.x, max.y, min.z
+ 6: min.x, min.y, min.z
+ 7: max.x, min.y, min.z
+ */
+
+ 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();
+ }
+
+ setFromObject(object) {
+ this.object = object;
+ this.update();
+ return this;
+ }
+
+ copy(source) {
+ LineSegments.prototype.copy.call(this, source);
+ this.object = source.object;
+ return this;
+ }
+
+}
+
+class Box3Helper extends LineSegments {
+ constructor(box, color = 0xffff00) {
+ 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: 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);
+ }
+
+}
+
+class PlaneHelper extends Line {
+ constructor(plane, size = 1, hex = 0xffff00) {
+ const color = hex;
+ 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, 0, 0, 1, 0, 0, 0];
+ const geometry = new BufferGeometry();
+ geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
+ geometry.computeBoundingSphere();
+ super(geometry, new LineBasicMaterial({
+ color: color,
+ toneMapped: false
+ }));
+ this.type = 'PlaneHelper';
+ this.plane = plane;
+ this.size = size;
+ const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
+ const geometry2 = new BufferGeometry();
+ geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
+ geometry2.computeBoundingSphere();
+ this.add(new Mesh(geometry2, new MeshBasicMaterial({
+ color: color,
+ opacity: 0.2,
+ transparent: true,
+ depthWrite: false,
+ toneMapped: false
+ })));
+ }
+
+ updateMatrixWorld(force) {
+ let scale = -this.plane.constant;
+ if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
+
+ this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
+ this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
+
+ this.lookAt(this.plane.normal);
+ super.updateMatrixWorld(force);
+ }
+
+}
+
+const _axis = /*@__PURE__*/new Vector3();
+
+let _lineGeometry, _coneGeometry;
+
+class ArrowHelper extends Object3D {
+ // dir is assumed to be normalized
+ constructor(dir = new Vector3(0, 0, 1), origin = new Vector3(0, 0, 0), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2) {
+ super();
+ this.type = 'ArrowHelper';
+
+ if (_lineGeometry === undefined) {
+ _lineGeometry = new BufferGeometry();
+
+ _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
+
+ _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
+
+ _coneGeometry.translate(0, -0.5, 0);
+ }
+
+ this.position.copy(origin);
+ this.line = new Line(_lineGeometry, new LineBasicMaterial({
+ color: color,
+ toneMapped: false
+ }));
+ this.line.matrixAutoUpdate = false;
+ this.add(this.line);
+ this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
+ color: color,
+ toneMapped: false
+ }));
+ this.cone.matrixAutoUpdate = false;
+ this.add(this.cone);
+ this.setDirection(dir);
+ this.setLength(length, headLength, headWidth);
+ }
+
+ setDirection(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();
+
+ const radians = Math.acos(dir.y);
+ this.quaternion.setFromAxisAngle(_axis, radians);
+ }
+ }
+
+ setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
+ this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
+
+ this.line.updateMatrix();
+ this.cone.scale.set(headWidth, headLength, headWidth);
+ this.cone.position.y = length;
+ this.cone.updateMatrix();
+ }
+
+ 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;
+ }
+
+}
+
+class AxesHelper extends LineSegments {
+ 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';
+ }
+
+ 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;
+ }
+
+ dispose() {
+ this.geometry.dispose();
+ this.material.dispose();
+ }
+
+}
+
+class ShapePath {
+ constructor() {
+ this.type = 'ShapePath';
+ this.color = new Color();
+ this.subPaths = [];
+ this.currentPath = null;
+ }
+
+ moveTo(x, y) {
+ this.currentPath = new Path();
+ this.subPaths.push(this.currentPath);
+ this.currentPath.moveTo(x, y);
+ return this;
+ }
+
+ lineTo(x, y) {
+ this.currentPath.lineTo(x, y);
+ return this;
+ }
+
+ quadraticCurveTo(aCPx, aCPy, aX, aY) {
+ this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
+ return this;
+ }
+
+ bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
+ this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
+ return this;
+ }
+
+ splineThru(pts) {
+ this.currentPath.splineThru(pts);
+ return this;
+ }
+
+ toShapes(isCCW, noHoles) {
+ function toShapesNoHoles(inSubpaths) {
+ const shapes = [];
+
+ for (let i = 0, l = inSubpaths.length; i < l; i++) {
+ const tmpPath = inSubpaths[i];
+ const tmpShape = new Shape();
+ tmpShape.curves = tmpPath.curves;
+ shapes.push(tmpShape);
+ }
+
+ return shapes;
+ }
+
+ function isPointInsidePolygon(inPt, inPolygon) {
+ const 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
+
+ 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) {
+ // 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 {
+ const 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 collinear
+ if (inPt.y !== edgeLowPt.y) continue; // parallel
+ // edge 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;
+ }
+
+ const isClockWise = ShapeUtils.isClockWise;
+ const subPaths = this.subPaths;
+ if (subPaths.length === 0) return [];
+ if (noHoles === true) return toShapesNoHoles(subPaths);
+ 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; // console.log("Holes first", holesFirst);
+
+ const betterShapeHoles = [];
+ const newShapes = [];
+ let newShapeHoles = [];
+ let mainIdx = 0;
+ let tmpPoints;
+ newShapes[mainIdx] = undefined;
+ 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] = []; //console.log('cw', i);
+ } else {
+ newShapeHoles[mainIdx].push({
+ h: tmpPath,
+ p: tmpPoints[0]
+ }); //console.log('ccw', i);
+ }
+ } // only Holes? -> probably all Shapes with wrong orientation
+
+
+ if (!newShapes[0]) return toShapesNoHoles(subPaths);
+
+ if (newShapes.length > 1) {
+ let ambiguous = false;
+ const toChange = [];
+
+ 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.push({
+ froms: sIdx,
+ tos: s2Idx,
+ hole: hIdx
+ });
+
+ if (hole_unassigned) {
+ hole_unassigned = false;
+ betterShapeHoles[s2Idx].push(ho);
+ } else {
+ ambiguous = true;
+ }
+ }
+ }
+
+ if (hole_unassigned) {
+ betterShapeHoles[sIdx].push(ho);
+ }
+ }
+ } // console.log("ambiguous: ", ambiguous);
+
+
+ if (toChange.length > 0) {
+ // console.log("to change: ", toChange);
+ if (!ambiguous) 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);
+ }
+ } //console.log("shape", shapes);
+
+
+ return shapes;
+ }
+
+}
+
+const _floatView = new Float32Array(1);
+
+const _int32View = new Int32Array(_floatView.buffer);
+
+class DataUtils {
+ // Converts float32 to float16 (stored as uint16 value).
+ static toHalfFloat(val) {
+ if (val > 65504) {
+ console.warn('THREE.DataUtils.toHalfFloat(): value exceeds 65504.');
+ val = 65504; // maximum representable value in float16
+ } // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
+
+ /* This method is faster than the OpenEXR implementation (very often
+ * used, eg. in Ogre), with the additional benefit of rounding, inspired
+ * by James Tursa?s half-precision code. */
+
+
+ _floatView[0] = val;
+ const x = _int32View[0];
+ let bits = x >> 16 & 0x8000;
+ /* Get the sign */
+
+ let m = x >> 12 & 0x07ff;
+ /* Keep one extra bit for rounding */
+
+ const e = x >> 23 & 0xff;
+ /* Using int is faster here */
+
+ /* If zero, or denormal, or exponent underflows too much for a denormal
+ * half, return signed zero. */
+
+ if (e < 103) return bits;
+ /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
+
+ if (e > 142) {
+ bits |= 0x7c00;
+ /* If exponent was 0xff and one mantissa bit was set, it means NaN,
+ * not Inf, so make sure we set one mantissa bit too. */
+
+ bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
+ return bits;
+ }
+ /* If exponent underflows but not too much, return a denormal */
+
+
+ if (e < 113) {
+ m |= 0x0800;
+ /* Extra rounding may overflow and set mantissa to 0 and exponent
+ * to 1, which is OK. */
+
+ bits |= (m >> 114 - e) + (m >> 113 - e & 1);
+ return bits;
+ }
+
+ bits |= e - 112 << 10 | m >> 1;
+ /* Extra rounding. An overflow will set mantissa to 0 and increment
+ * the exponent, which is OK. */
+
+ bits += m & 1;
+ return bits;
+ }
+
+}
+
+const LineStrip = 0;
+const LinePieces = 1;
+const NoColors = 0;
+const FaceColors = 1;
+const VertexColors = 2;
+function MeshFaceMaterial(materials) {
+ console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
+ return materials;
+}
+function MultiMaterial(materials = []) {
+ console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
+ materials.isMultiMaterial = true;
+ materials.materials = materials;
+
+ materials.clone = function () {
+ return materials.slice();
+ };
+
+ return materials;
+}
+function PointCloud(geometry, material) {
+ console.warn('THREE.PointCloud has been renamed to THREE.Points.');
+ return new Points(geometry, material);
+}
+function Particle(material) {
+ console.warn('THREE.Particle has been renamed to THREE.Sprite.');
+ return new Sprite(material);
+}
+function ParticleSystem(geometry, material) {
+ console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
+ return new Points(geometry, material);
+}
+function PointCloudMaterial(parameters) {
+ console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
+ return new PointsMaterial(parameters);
+}
+function ParticleBasicMaterial(parameters) {
+ console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
+ return new PointsMaterial(parameters);
+}
+function ParticleSystemMaterial(parameters) {
+ console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
+ return new PointsMaterial(parameters);
+}
+function Vertex(x, y, z) {
+ console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
+ return new Vector3(x, y, z);
+} //
+
+function DynamicBufferAttribute(array, itemSize) {
+ console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
+ return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
+}
+function Int8Attribute(array, itemSize) {
+ console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
+ return new Int8BufferAttribute(array, itemSize);
+}
+function Uint8Attribute(array, itemSize) {
+ console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
+ return new Uint8BufferAttribute(array, itemSize);
+}
+function Uint8ClampedAttribute(array, itemSize) {
+ console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
+ return new Uint8ClampedBufferAttribute(array, itemSize);
+}
+function Int16Attribute(array, itemSize) {
+ console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
+ return new Int16BufferAttribute(array, itemSize);
+}
+function Uint16Attribute(array, itemSize) {
+ console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
+ return new Uint16BufferAttribute(array, itemSize);
+}
+function Int32Attribute(array, itemSize) {
+ console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
+ return new Int32BufferAttribute(array, itemSize);
+}
+function Uint32Attribute(array, itemSize) {
+ console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
+ return new Uint32BufferAttribute(array, itemSize);
+}
+function Float32Attribute(array, itemSize) {
+ console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
+ return new Float32BufferAttribute(array, itemSize);
+}
+function Float64Attribute(array, itemSize) {
+ console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
+ return new Float64BufferAttribute(array, itemSize);
+} //
+
+Curve.create = function (construct, getPoint) {
+ console.log('THREE.Curve.create() has been deprecated');
+ construct.prototype = Object.create(Curve.prototype);
+ construct.prototype.constructor = construct;
+ construct.prototype.getPoint = getPoint;
+ return construct;
+}; //
+
+
+Path.prototype.fromPoints = function (points) {
+ console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
+ return this.setFromPoints(points);
+}; //
+
+
+function AxisHelper(size) {
+ console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
+ return new AxesHelper(size);
+}
+function BoundingBoxHelper(object, color) {
+ console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
+ return new BoxHelper(object, color);
+}
+function EdgesHelper(object, hex) {
+ console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
+ return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
+ color: hex !== undefined ? hex : 0xffffff
+ }));
+}
+
+GridHelper.prototype.setColors = function () {
+ console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
+};
+
+SkeletonHelper.prototype.update = function () {
+ console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
+};
+
+function WireframeHelper(object, hex) {
+ console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
+ return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
+ color: hex !== undefined ? hex : 0xffffff
+ }));
+} //
+
+Loader.prototype.extractUrlBase = function (url) {
+ console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
+ return LoaderUtils.extractUrlBase(url);
+};
+
+Loader.Handlers = {
+ add: function
+ /* regex, loader */
+ () {
+ console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
+ },
+ get: function
+ /* file */
+ () {
+ console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
+ }
+};
+function XHRLoader(manager) {
+ console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
+ return new FileLoader(manager);
+}
+function BinaryTextureLoader(manager) {
+ console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
+ return new DataTextureLoader(manager);
+} //
+
+Box2.prototype.center = function (optionalTarget) {
+ console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
+ return this.getCenter(optionalTarget);
+};
+
+Box2.prototype.empty = function () {
+ console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
+ return this.isEmpty();
+};
+
+Box2.prototype.isIntersectionBox = function (box) {
+ console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
+ return this.intersectsBox(box);
+};
+
+Box2.prototype.size = function (optionalTarget) {
+ console.warn('THREE.Box2: .size() has been renamed to .getSize().');
+ return this.getSize(optionalTarget);
+}; //
+
+
+Box3.prototype.center = function (optionalTarget) {
+ console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
+ return this.getCenter(optionalTarget);
+};
+
+Box3.prototype.empty = function () {
+ console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
+ return this.isEmpty();
+};
+
+Box3.prototype.isIntersectionBox = function (box) {
+ console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
+ return this.intersectsBox(box);
+};
+
+Box3.prototype.isIntersectionSphere = function (sphere) {
+ console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
+ return this.intersectsSphere(sphere);
+};
+
+Box3.prototype.size = function (optionalTarget) {
+ console.warn('THREE.Box3: .size() has been renamed to .getSize().');
+ return this.getSize(optionalTarget);
+}; //
+
+
+Sphere.prototype.empty = function () {
+ console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
+ return this.isEmpty();
+}; //
+
+
+Frustum.prototype.setFromMatrix = function (m) {
+ console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
+ return this.setFromProjectionMatrix(m);
+}; //
+
+
+Line3.prototype.center = function (optionalTarget) {
+ console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
+ return this.getCenter(optionalTarget);
+}; //
+
+
+Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
+ console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
+ return this.toArray(array, offset);
+};
+
+Matrix3.prototype.multiplyVector3 = function (vector) {
+ console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
+ return vector.applyMatrix3(this);
+};
+
+Matrix3.prototype.multiplyVector3Array = function
+ /* a */
+() {
+ console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
+};
+
+Matrix3.prototype.applyToBufferAttribute = function (attribute) {
+ console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
+ return attribute.applyMatrix3(this);
+};
+
+Matrix3.prototype.applyToVector3Array = function
+ /* array, offset, length */
+() {
+ console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
+};
+
+Matrix3.prototype.getInverse = function (matrix) {
+ console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
+ return this.copy(matrix).invert();
+}; //
+
+
+Matrix4.prototype.extractPosition = function (m) {
+ console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
+ return this.copyPosition(m);
+};
+
+Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
+ console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
+ return this.toArray(array, offset);
+};
+
+Matrix4.prototype.getPosition = function () {
+ console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
+ return new Vector3().setFromMatrixColumn(this, 3);
+};
+
+Matrix4.prototype.setRotationFromQuaternion = function (q) {
+ console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
+ return this.makeRotationFromQuaternion(q);
+};
+
+Matrix4.prototype.multiplyToArray = function () {
+ console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
+};
+
+Matrix4.prototype.multiplyVector3 = function (vector) {
+ console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
+ return vector.applyMatrix4(this);
+};
+
+Matrix4.prototype.multiplyVector4 = function (vector) {
+ console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
+ return vector.applyMatrix4(this);
+};
+
+Matrix4.prototype.multiplyVector3Array = function
+ /* a */
+() {
+ console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
+};
+
+Matrix4.prototype.rotateAxis = function (v) {
+ console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
+ v.transformDirection(this);
+};
+
+Matrix4.prototype.crossVector = function (vector) {
+ console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
+ return vector.applyMatrix4(this);
+};
+
+Matrix4.prototype.translate = function () {
+ console.error('THREE.Matrix4: .translate() has been removed.');
+};
+
+Matrix4.prototype.rotateX = function () {
+ console.error('THREE.Matrix4: .rotateX() has been removed.');
+};
+
+Matrix4.prototype.rotateY = function () {
+ console.error('THREE.Matrix4: .rotateY() has been removed.');
+};
+
+Matrix4.prototype.rotateZ = function () {
+ console.error('THREE.Matrix4: .rotateZ() has been removed.');
+};
+
+Matrix4.prototype.rotateByAxis = function () {
+ console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
+};
+
+Matrix4.prototype.applyToBufferAttribute = function (attribute) {
+ console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
+ return attribute.applyMatrix4(this);
+};
+
+Matrix4.prototype.applyToVector3Array = function
+ /* array, offset, length */
+() {
+ console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
+};
+
+Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
+ console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
+ return this.makePerspective(left, right, top, bottom, near, far);
+};
+
+Matrix4.prototype.getInverse = function (matrix) {
+ console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
+ return this.copy(matrix).invert();
+}; //
+
+
+Plane.prototype.isIntersectionLine = function (line) {
+ console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
+ return this.intersectsLine(line);
+}; //
+
+
+Quaternion.prototype.multiplyVector3 = function (vector) {
+ console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
+ return vector.applyQuaternion(this);
+};
+
+Quaternion.prototype.inverse = function () {
+ console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
+ return this.invert();
+}; //
+
+
+Ray.prototype.isIntersectionBox = function (box) {
+ console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
+ return this.intersectsBox(box);
+};
+
+Ray.prototype.isIntersectionPlane = function (plane) {
+ console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
+ return this.intersectsPlane(plane);
+};
+
+Ray.prototype.isIntersectionSphere = function (sphere) {
+ console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
+ return this.intersectsSphere(sphere);
+}; //
+
+
+Triangle.prototype.area = function () {
+ console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
+ return this.getArea();
+};
+
+Triangle.prototype.barycoordFromPoint = function (point, target) {
+ console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
+ return this.getBarycoord(point, target);
+};
+
+Triangle.prototype.midpoint = function (target) {
+ console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
+ return this.getMidpoint(target);
+};
+
+Triangle.prototypenormal = function (target) {
+ console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
+ return this.getNormal(target);
+};
+
+Triangle.prototype.plane = function (target) {
+ console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
+ return this.getPlane(target);
+};
+
+Triangle.barycoordFromPoint = function (point, a, b, c, target) {
+ console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
+ return Triangle.getBarycoord(point, a, b, c, target);
+};
+
+Triangle.normal = function (a, b, c, target) {
+ console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
+ return Triangle.getNormal(a, b, c, target);
+}; //
+
+
+Shape.prototype.extractAllPoints = function (divisions) {
+ console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
+ return this.extractPoints(divisions);
+};
+
+Shape.prototype.extrude = function (options) {
+ console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
+ return new ExtrudeGeometry(this, options);
+};
+
+Shape.prototype.makeGeometry = function (options) {
+ console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
+ return new ShapeGeometry(this, options);
+}; //
+
+
+Vector2.prototype.fromAttribute = function (attribute, index, offset) {
+ console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
+ return this.fromBufferAttribute(attribute, index, offset);
+};
+
+Vector2.prototype.distanceToManhattan = function (v) {
+ console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
+ return this.manhattanDistanceTo(v);
+};
+
+Vector2.prototype.lengthManhattan = function () {
+ console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
+ return this.manhattanLength();
+}; //
+
+
+Vector3.prototype.setEulerFromRotationMatrix = function () {
+ console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
+};
+
+Vector3.prototype.setEulerFromQuaternion = function () {
+ console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
+};
+
+Vector3.prototype.getPositionFromMatrix = function (m) {
+ console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
+ return this.setFromMatrixPosition(m);
+};
+
+Vector3.prototype.getScaleFromMatrix = function (m) {
+ console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
+ return this.setFromMatrixScale(m);
+};
+
+Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
+ console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
+ return this.setFromMatrixColumn(matrix, index);
+};
+
+Vector3.prototype.applyProjection = function (m) {
+ console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
+ return this.applyMatrix4(m);
+};
+
+Vector3.prototype.fromAttribute = function (attribute, index, offset) {
+ console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
+ return this.fromBufferAttribute(attribute, index, offset);
+};
+
+Vector3.prototype.distanceToManhattan = function (v) {
+ console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
+ return this.manhattanDistanceTo(v);
+};
+
+Vector3.prototype.lengthManhattan = function () {
+ console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
+ return this.manhattanLength();
+}; //
+
+
+Vector4.prototype.fromAttribute = function (attribute, index, offset) {
+ console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
+ return this.fromBufferAttribute(attribute, index, offset);
+};
+
+Vector4.prototype.lengthManhattan = function () {
+ console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
+ return this.manhattanLength();
+}; //
+
+
+Object3D.prototype.getChildByName = function (name) {
+ console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
+ return this.getObjectByName(name);
+};
+
+Object3D.prototype.renderDepth = function () {
+ console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
+};
+
+Object3D.prototype.translate = function (distance, axis) {
+ console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
+ return this.translateOnAxis(axis, distance);
+};
+
+Object3D.prototype.getWorldRotation = function () {
+ console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
+};
+
+Object3D.prototype.applyMatrix = function (matrix) {
+ console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
+ return this.applyMatrix4(matrix);
+};
+
+Object.defineProperties(Object3D.prototype, {
+ eulerOrder: {
+ get: function () {
+ console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
+ return this.rotation.order;
+ },
+ set: function (value) {
+ console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
+ this.rotation.order = value;
+ }
+ },
+ useQuaternion: {
+ get: function () {
+ console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
+ },
+ set: function () {
+ console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
+ }
+ }
+});
+
+Mesh.prototype.setDrawMode = function () {
+ console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
+};
+
+Object.defineProperties(Mesh.prototype, {
+ drawMode: {
+ get: function () {
+ console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
+ return TrianglesDrawMode;
+ },
+ set: function () {
+ console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
+ }
+ }
+});
+
+SkinnedMesh.prototype.initBones = function () {
+ console.error('THREE.SkinnedMesh: initBones() has been removed.');
+}; //
+
+
+PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
+ console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
+ if (filmGauge !== undefined) this.filmGauge = filmGauge;
+ this.setFocalLength(focalLength);
+}; //
+
+
+Object.defineProperties(Light.prototype, {
+ onlyShadow: {
+ set: function () {
+ console.warn('THREE.Light: .onlyShadow has been removed.');
+ }
+ },
+ shadowCameraFov: {
+ set: function (value) {
+ console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
+ this.shadow.camera.fov = value;
+ }
+ },
+ shadowCameraLeft: {
+ set: function (value) {
+ console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
+ this.shadow.camera.left = value;
+ }
+ },
+ shadowCameraRight: {
+ set: function (value) {
+ console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
+ this.shadow.camera.right = value;
+ }
+ },
+ shadowCameraTop: {
+ set: function (value) {
+ console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
+ this.shadow.camera.top = value;
+ }
+ },
+ shadowCameraBottom: {
+ set: function (value) {
+ console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
+ this.shadow.camera.bottom = value;
+ }
+ },
+ shadowCameraNear: {
+ set: function (value) {
+ console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
+ this.shadow.camera.near = value;
+ }
+ },
+ shadowCameraFar: {
+ set: function (value) {
+ console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
+ this.shadow.camera.far = value;
+ }
+ },
+ shadowCameraVisible: {
+ set: function () {
+ console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
+ }
+ },
+ shadowBias: {
+ set: function (value) {
+ console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
+ this.shadow.bias = value;
+ }
+ },
+ shadowDarkness: {
+ set: function () {
+ console.warn('THREE.Light: .shadowDarkness has been removed.');
+ }
+ },
+ shadowMapWidth: {
+ set: function (value) {
+ console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
+ this.shadow.mapSize.width = value;
+ }
+ },
+ shadowMapHeight: {
+ set: function (value) {
+ console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
+ this.shadow.mapSize.height = value;
+ }
+ }
+}); //
+
+Object.defineProperties(BufferAttribute.prototype, {
+ length: {
+ get: function () {
+ console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
+ return this.array.length;
+ }
+ },
+ dynamic: {
+ get: function () {
+ console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
+ return this.usage === DynamicDrawUsage;
+ },
+ set: function
+ /* value */
+ () {
+ console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
+ this.setUsage(DynamicDrawUsage);
+ }
+ }
+});
+
+BufferAttribute.prototype.setDynamic = function (value) {
+ console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
+ this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
+ return this;
+};
+
+BufferAttribute.prototype.copyIndicesArray = function
+ /* indices */
+() {
+ console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
+}, BufferAttribute.prototype.setArray = function
+ /* array */
+() {
+ console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
+}; //
+
+BufferGeometry.prototype.addIndex = function (index) {
+ console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
+ this.setIndex(index);
+};
+
+BufferGeometry.prototype.addAttribute = function (name, attribute) {
+ console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
+
+ if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
+ console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
+ return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
+ }
+
+ if (name === 'index') {
+ console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
+ this.setIndex(attribute);
+ return this;
+ }
+
+ return this.setAttribute(name, attribute);
+};
+
+BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
+ if (indexOffset !== undefined) {
+ console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
+ }
+
+ console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
+ this.addGroup(start, count);
+};
+
+BufferGeometry.prototype.clearDrawCalls = function () {
+ console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
+ this.clearGroups();
+};
+
+BufferGeometry.prototype.computeOffsets = function () {
+ console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
+};
+
+BufferGeometry.prototype.removeAttribute = function (name) {
+ console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
+ return this.deleteAttribute(name);
+};
+
+BufferGeometry.prototype.applyMatrix = function (matrix) {
+ console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
+ return this.applyMatrix4(matrix);
+};
+
+Object.defineProperties(BufferGeometry.prototype, {
+ drawcalls: {
+ get: function () {
+ console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
+ return this.groups;
+ }
+ },
+ offsets: {
+ get: function () {
+ console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
+ return this.groups;
+ }
+ }
+});
+
+InterleavedBuffer.prototype.setDynamic = function (value) {
+ console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
+ this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
+ return this;
+};
+
+InterleavedBuffer.prototype.setArray = function
+ /* array */
+() {
+ console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
+}; //
+
+
+ExtrudeGeometry.prototype.getArrays = function () {
+ console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
+};
+
+ExtrudeGeometry.prototype.addShapeList = function () {
+ console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
+};
+
+ExtrudeGeometry.prototype.addShape = function () {
+ console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
+}; //
+
+
+Scene.prototype.dispose = function () {
+ console.error('THREE.Scene: .dispose() has been removed.');
+}; //
+
+
+Uniform.prototype.onUpdate = function () {
+ console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
+ return this;
+}; //
+
+
+Object.defineProperties(Material.prototype, {
+ wrapAround: {
+ get: function () {
+ console.warn('THREE.Material: .wrapAround has been removed.');
+ },
+ set: function () {
+ console.warn('THREE.Material: .wrapAround has been removed.');
+ }
+ },
+ overdraw: {
+ get: function () {
+ console.warn('THREE.Material: .overdraw has been removed.');
+ },
+ set: function () {
+ console.warn('THREE.Material: .overdraw has been removed.');
+ }
+ },
+ wrapRGB: {
+ get: function () {
+ console.warn('THREE.Material: .wrapRGB has been removed.');
+ return new Color();
+ }
+ },
+ shading: {
+ get: function () {
+ console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
+ },
+ set: function (value) {
+ console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
+ this.flatShading = value === FlatShading;
+ }
+ },
+ stencilMask: {
+ get: function () {
+ console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
+ return this.stencilFuncMask;
+ },
+ set: function (value) {
+ console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
+ this.stencilFuncMask = value;
+ }
+ },
+ vertexTangents: {
+ get: function () {
+ console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
+ },
+ set: function () {
+ console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
+ }
+ }
+});
+Object.defineProperties(ShaderMaterial.prototype, {
+ derivatives: {
+ get: function () {
+ console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
+ return this.extensions.derivatives;
+ },
+ set: function (value) {
+ console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
+ this.extensions.derivatives = value;
+ }
+ }
+}); //
+
+WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
+ console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
+ this.setRenderTarget(renderTarget);
+ this.clear(color, depth, stencil);
+};
+
+WebGLRenderer.prototype.animate = function (callback) {
+ console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
+ this.setAnimationLoop(callback);
+};
+
+WebGLRenderer.prototype.getCurrentRenderTarget = function () {
+ console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
+ return this.getRenderTarget();
+};
+
+WebGLRenderer.prototype.getMaxAnisotropy = function () {
+ console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
+ return this.capabilities.getMaxAnisotropy();
+};
+
+WebGLRenderer.prototype.getPrecision = function () {
+ console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
+ return this.capabilities.precision;
+};
+
+WebGLRenderer.prototype.resetGLState = function () {
+ console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
+ return this.state.reset();
+};
+
+WebGLRenderer.prototype.supportsFloatTextures = function () {
+ console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
+ return this.extensions.get('OES_texture_float');
+};
+
+WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
+ console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
+ return this.extensions.get('OES_texture_half_float');
+};
+
+WebGLRenderer.prototype.supportsStandardDerivatives = function () {
+ console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
+ return this.extensions.get('OES_standard_derivatives');
+};
+
+WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
+ console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
+ return this.extensions.get('WEBGL_compressed_texture_s3tc');
+};
+
+WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
+ console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
+ return this.extensions.get('WEBGL_compressed_texture_pvrtc');
+};
+
+WebGLRenderer.prototype.supportsBlendMinMax = function () {
+ console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
+ return this.extensions.get('EXT_blend_minmax');
+};
+
+WebGLRenderer.prototype.supportsVertexTextures = function () {
+ console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
+ return this.capabilities.vertexTextures;
+};
+
+WebGLRenderer.prototype.supportsInstancedArrays = function () {
+ console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
+ return this.extensions.get('ANGLE_instanced_arrays');
+};
+
+WebGLRenderer.prototype.enableScissorTest = function (boolean) {
+ console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
+ this.setScissorTest(boolean);
+};
+
+WebGLRenderer.prototype.initMaterial = function () {
+ console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
+};
+
+WebGLRenderer.prototype.addPrePlugin = function () {
+ console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
+};
+
+WebGLRenderer.prototype.addPostPlugin = function () {
+ console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
+};
+
+WebGLRenderer.prototype.updateShadowMap = function () {
+ console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
+};
+
+WebGLRenderer.prototype.setFaceCulling = function () {
+ console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
+};
+
+WebGLRenderer.prototype.allocTextureUnit = function () {
+ console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
+};
+
+WebGLRenderer.prototype.setTexture = function () {
+ console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
+};
+
+WebGLRenderer.prototype.setTexture2D = function () {
+ console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
+};
+
+WebGLRenderer.prototype.setTextureCube = function () {
+ console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
+};
+
+WebGLRenderer.prototype.getActiveMipMapLevel = function () {
+ console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
+ return this.getActiveMipmapLevel();
+};
+
+Object.defineProperties(WebGLRenderer.prototype, {
+ shadowMapEnabled: {
+ get: function () {
+ return this.shadowMap.enabled;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
+ this.shadowMap.enabled = value;
+ }
+ },
+ shadowMapType: {
+ get: function () {
+ return this.shadowMap.type;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
+ this.shadowMap.type = value;
+ }
+ },
+ shadowMapCullFace: {
+ get: function () {
+ console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
+ return undefined;
+ },
+ set: function
+ /* value */
+ () {
+ console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
+ }
+ },
+ context: {
+ get: function () {
+ console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
+ return this.getContext();
+ }
+ },
+ vr: {
+ get: function () {
+ console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
+ return this.xr;
+ }
+ },
+ gammaInput: {
+ get: function () {
+ console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
+ return false;
+ },
+ set: function () {
+ console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
+ }
+ },
+ gammaOutput: {
+ get: function () {
+ console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
+ return false;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
+ this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
+ }
+ },
+ toneMappingWhitePoint: {
+ get: function () {
+ console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
+ return 1.0;
+ },
+ set: function () {
+ console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
+ }
+ },
+ gammaFactor: {
+ get: function () {
+ console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.');
+ return 2;
+ },
+ set: function () {
+ console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.');
+ }
+ }
+});
+Object.defineProperties(WebGLShadowMap.prototype, {
+ cullFace: {
+ get: function () {
+ console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
+ return undefined;
+ },
+ set: function
+ /* cullFace */
+ () {
+ console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
+ }
+ },
+ renderReverseSided: {
+ get: function () {
+ console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
+ return undefined;
+ },
+ set: function () {
+ console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
+ }
+ },
+ renderSingleSided: {
+ get: function () {
+ console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
+ return undefined;
+ },
+ set: function () {
+ console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
+ }
+ }
+});
+function WebGLRenderTargetCube(width, height, options) {
+ console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
+ return new WebGLCubeRenderTarget(width, options);
+} //
+
+Object.defineProperties(WebGLRenderTarget.prototype, {
+ wrapS: {
+ get: function () {
+ console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
+ return this.texture.wrapS;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
+ this.texture.wrapS = value;
+ }
+ },
+ wrapT: {
+ get: function () {
+ console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
+ return this.texture.wrapT;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
+ this.texture.wrapT = value;
+ }
+ },
+ magFilter: {
+ get: function () {
+ console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
+ return this.texture.magFilter;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
+ this.texture.magFilter = value;
+ }
+ },
+ minFilter: {
+ get: function () {
+ console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
+ return this.texture.minFilter;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
+ this.texture.minFilter = value;
+ }
+ },
+ anisotropy: {
+ get: function () {
+ console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
+ return this.texture.anisotropy;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
+ this.texture.anisotropy = value;
+ }
+ },
+ offset: {
+ get: function () {
+ console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
+ return this.texture.offset;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
+ this.texture.offset = value;
+ }
+ },
+ repeat: {
+ get: function () {
+ console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
+ return this.texture.repeat;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
+ this.texture.repeat = value;
+ }
+ },
+ format: {
+ get: function () {
+ console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
+ return this.texture.format;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
+ this.texture.format = value;
+ }
+ },
+ type: {
+ get: function () {
+ console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
+ return this.texture.type;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
+ this.texture.type = value;
+ }
+ },
+ generateMipmaps: {
+ get: function () {
+ console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
+ return this.texture.generateMipmaps;
+ },
+ set: function (value) {
+ console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
+ this.texture.generateMipmaps = value;
+ }
+ }
+}); //
+
+Audio.prototype.load = function (file) {
+ console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
+ const scope = this;
+ const audioLoader = new AudioLoader();
+ audioLoader.load(file, function (buffer) {
+ scope.setBuffer(buffer);
+ });
+ return this;
+};
+
+AudioAnalyser.prototype.getData = function () {
+ console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
+ return this.getFrequencyData();
+}; //
+
+
+CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
+ console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
+ return this.update(renderer, scene);
+};
+
+CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
+ console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
+ return this.renderTarget.clear(renderer, color, depth, stencil);
+};
+
+ImageUtils.crossOrigin = undefined;
+
+ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
+ console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
+ const loader = new TextureLoader();
+ loader.setCrossOrigin(this.crossOrigin);
+ const texture = loader.load(url, onLoad, undefined, onError);
+ if (mapping) texture.mapping = mapping;
+ return texture;
+};
+
+ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
+ console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
+ const loader = new CubeTextureLoader();
+ loader.setCrossOrigin(this.crossOrigin);
+ const texture = loader.load(urls, onLoad, undefined, onError);
+ if (mapping) texture.mapping = mapping;
+ return texture;
+};
+
+ImageUtils.loadCompressedTexture = function () {
+ console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
+};
+
+ImageUtils.loadCompressedTextureCube = function () {
+ console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
+}; //
+
+
+function CanvasRenderer() {
+ console.error('THREE.CanvasRenderer has been removed');
+} //
+
+function JSONLoader() {
+ console.error('THREE.JSONLoader has been removed.');
+} //
+
+const SceneUtils = {
+ createMultiMaterialObject: function
+ /* geometry, materials */
+ () {
+ console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
+ },
+ detach: function
+ /* child, parent, scene */
+ () {
+ console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
+ },
+ attach: function
+ /* child, scene, parent */
+ () {
+ console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
+ }
+}; //
+
+function LensFlare() {
+ console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
+} //
+
+function ParametricGeometry() {
+ console.error('THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js');
+ return new BufferGeometry();
+}
+function TextGeometry() {
+ console.error('THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js');
+ return new BufferGeometry();
+}
+function FontLoader() {
+ console.error('THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js');
+}
+function Font() {
+ console.error('THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js');
+}
+function ImmediateRenderObject() {
+ console.error('THREE.ImmediateRenderObject has been removed.');
+}
+
+if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
+ __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
+ detail: {
+ revision: REVISION
+ }
+ }));
+}
+
+if (typeof window !== 'undefined') {
+ if (window.__THREE__) {
+ console.warn('WARNING: Multiple instances of Three.js being imported.');
+ } else {
+ window.__THREE__ = REVISION;
+ }
+}
+
+exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
+exports.AddEquation = AddEquation;
+exports.AddOperation = AddOperation;
+exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
+exports.AdditiveBlending = AdditiveBlending;
+exports.AlphaFormat = AlphaFormat;
+exports.AlwaysDepth = AlwaysDepth;
+exports.AlwaysStencilFunc = AlwaysStencilFunc;
+exports.AmbientLight = AmbientLight;
+exports.AmbientLightProbe = AmbientLightProbe;
+exports.AnimationClip = AnimationClip;
+exports.AnimationLoader = AnimationLoader;
+exports.AnimationMixer = AnimationMixer;
+exports.AnimationObjectGroup = AnimationObjectGroup;
+exports.AnimationUtils = AnimationUtils;
+exports.ArcCurve = ArcCurve;
+exports.ArrayCamera = ArrayCamera;
+exports.ArrowHelper = ArrowHelper;
+exports.Audio = Audio;
+exports.AudioAnalyser = AudioAnalyser;
+exports.AudioContext = AudioContext;
+exports.AudioListener = AudioListener;
+exports.AudioLoader = AudioLoader;
+exports.AxesHelper = AxesHelper;
+exports.AxisHelper = AxisHelper;
+exports.BackSide = BackSide;
+exports.BasicDepthPacking = BasicDepthPacking;
+exports.BasicShadowMap = BasicShadowMap;
+exports.BinaryTextureLoader = BinaryTextureLoader;
+exports.Bone = Bone;
+exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
+exports.BoundingBoxHelper = BoundingBoxHelper;
+exports.Box2 = Box2;
+exports.Box3 = Box3;
+exports.Box3Helper = Box3Helper;
+exports.BoxBufferGeometry = BoxGeometry;
+exports.BoxGeometry = BoxGeometry;
+exports.BoxHelper = BoxHelper;
+exports.BufferAttribute = BufferAttribute;
+exports.BufferGeometry = BufferGeometry;
+exports.BufferGeometryLoader = BufferGeometryLoader;
+exports.ByteType = ByteType;
+exports.Cache = Cache;
+exports.Camera = Camera;
+exports.CameraHelper = CameraHelper;
+exports.CanvasRenderer = CanvasRenderer;
+exports.CanvasTexture = CanvasTexture;
+exports.CatmullRomCurve3 = CatmullRomCurve3;
+exports.CineonToneMapping = CineonToneMapping;
+exports.CircleBufferGeometry = CircleGeometry;
+exports.CircleGeometry = CircleGeometry;
+exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
+exports.Clock = Clock;
+exports.Color = Color;
+exports.ColorKeyframeTrack = ColorKeyframeTrack;
+exports.CompressedTexture = CompressedTexture;
+exports.CompressedTextureLoader = CompressedTextureLoader;
+exports.ConeBufferGeometry = ConeGeometry;
+exports.ConeGeometry = ConeGeometry;
+exports.CubeCamera = CubeCamera;
+exports.CubeReflectionMapping = CubeReflectionMapping;
+exports.CubeRefractionMapping = CubeRefractionMapping;
+exports.CubeTexture = CubeTexture;
+exports.CubeTextureLoader = CubeTextureLoader;
+exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
+exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
+exports.CubicBezierCurve = CubicBezierCurve;
+exports.CubicBezierCurve3 = CubicBezierCurve3;
+exports.CubicInterpolant = CubicInterpolant;
+exports.CullFaceBack = CullFaceBack;
+exports.CullFaceFront = CullFaceFront;
+exports.CullFaceFrontBack = CullFaceFrontBack;
+exports.CullFaceNone = CullFaceNone;
+exports.Curve = Curve;
+exports.CurvePath = CurvePath;
+exports.CustomBlending = CustomBlending;
+exports.CustomToneMapping = CustomToneMapping;
+exports.CylinderBufferGeometry = CylinderGeometry;
+exports.CylinderGeometry = CylinderGeometry;
+exports.Cylindrical = Cylindrical;
+exports.DataTexture = DataTexture;
+exports.DataTexture2DArray = DataTexture2DArray;
+exports.DataTexture3D = DataTexture3D;
+exports.DataTextureLoader = DataTextureLoader;
+exports.DataUtils = DataUtils;
+exports.DecrementStencilOp = DecrementStencilOp;
+exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
+exports.DefaultLoadingManager = DefaultLoadingManager;
+exports.DepthFormat = DepthFormat;
+exports.DepthStencilFormat = DepthStencilFormat;
+exports.DepthTexture = DepthTexture;
+exports.DirectionalLight = DirectionalLight;
+exports.DirectionalLightHelper = DirectionalLightHelper;
+exports.DiscreteInterpolant = DiscreteInterpolant;
+exports.DodecahedronBufferGeometry = DodecahedronGeometry;
+exports.DodecahedronGeometry = DodecahedronGeometry;
+exports.DoubleSide = DoubleSide;
+exports.DstAlphaFactor = DstAlphaFactor;
+exports.DstColorFactor = DstColorFactor;
+exports.DynamicBufferAttribute = DynamicBufferAttribute;
+exports.DynamicCopyUsage = DynamicCopyUsage;
+exports.DynamicDrawUsage = DynamicDrawUsage;
+exports.DynamicReadUsage = DynamicReadUsage;
+exports.EdgesGeometry = EdgesGeometry;
+exports.EdgesHelper = EdgesHelper;
+exports.EllipseCurve = EllipseCurve;
+exports.EqualDepth = EqualDepth;
+exports.EqualStencilFunc = EqualStencilFunc;
+exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
+exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
+exports.Euler = Euler;
+exports.EventDispatcher = EventDispatcher;
+exports.ExtrudeBufferGeometry = ExtrudeGeometry;
+exports.ExtrudeGeometry = ExtrudeGeometry;
+exports.FaceColors = FaceColors;
+exports.FileLoader = FileLoader;
+exports.FlatShading = FlatShading;
+exports.Float16BufferAttribute = Float16BufferAttribute;
+exports.Float32Attribute = Float32Attribute;
+exports.Float32BufferAttribute = Float32BufferAttribute;
+exports.Float64Attribute = Float64Attribute;
+exports.Float64BufferAttribute = Float64BufferAttribute;
+exports.FloatType = FloatType;
+exports.Fog = Fog;
+exports.FogExp2 = FogExp2;
+exports.Font = Font;
+exports.FontLoader = FontLoader;
+exports.FramebufferTexture = FramebufferTexture;
+exports.FrontSide = FrontSide;
+exports.Frustum = Frustum;
+exports.GLBufferAttribute = GLBufferAttribute;
+exports.GLSL1 = GLSL1;
+exports.GLSL3 = GLSL3;
+exports.GreaterDepth = GreaterDepth;
+exports.GreaterEqualDepth = GreaterEqualDepth;
+exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
+exports.GreaterStencilFunc = GreaterStencilFunc;
+exports.GridHelper = GridHelper;
+exports.Group = Group;
+exports.HalfFloatType = HalfFloatType;
+exports.HemisphereLight = HemisphereLight;
+exports.HemisphereLightHelper = HemisphereLightHelper;
+exports.HemisphereLightProbe = HemisphereLightProbe;
+exports.IcosahedronBufferGeometry = IcosahedronGeometry;
+exports.IcosahedronGeometry = IcosahedronGeometry;
+exports.ImageBitmapLoader = ImageBitmapLoader;
+exports.ImageLoader = ImageLoader;
+exports.ImageUtils = ImageUtils;
+exports.ImmediateRenderObject = ImmediateRenderObject;
+exports.IncrementStencilOp = IncrementStencilOp;
+exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
+exports.InstancedBufferAttribute = InstancedBufferAttribute;
+exports.InstancedBufferGeometry = InstancedBufferGeometry;
+exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
+exports.InstancedMesh = InstancedMesh;
+exports.Int16Attribute = Int16Attribute;
+exports.Int16BufferAttribute = Int16BufferAttribute;
+exports.Int32Attribute = Int32Attribute;
+exports.Int32BufferAttribute = Int32BufferAttribute;
+exports.Int8Attribute = Int8Attribute;
+exports.Int8BufferAttribute = Int8BufferAttribute;
+exports.IntType = IntType;
+exports.InterleavedBuffer = InterleavedBuffer;
+exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
+exports.Interpolant = Interpolant;
+exports.InterpolateDiscrete = InterpolateDiscrete;
+exports.InterpolateLinear = InterpolateLinear;
+exports.InterpolateSmooth = InterpolateSmooth;
+exports.InvertStencilOp = InvertStencilOp;
+exports.JSONLoader = JSONLoader;
+exports.KeepStencilOp = KeepStencilOp;
+exports.KeyframeTrack = KeyframeTrack;
+exports.LOD = LOD;
+exports.LatheBufferGeometry = LatheGeometry;
+exports.LatheGeometry = LatheGeometry;
+exports.Layers = Layers;
+exports.LensFlare = LensFlare;
+exports.LessDepth = LessDepth;
+exports.LessEqualDepth = LessEqualDepth;
+exports.LessEqualStencilFunc = LessEqualStencilFunc;
+exports.LessStencilFunc = LessStencilFunc;
+exports.Light = Light;
+exports.LightProbe = LightProbe;
+exports.Line = Line;
+exports.Line3 = Line3;
+exports.LineBasicMaterial = LineBasicMaterial;
+exports.LineCurve = LineCurve;
+exports.LineCurve3 = LineCurve3;
+exports.LineDashedMaterial = LineDashedMaterial;
+exports.LineLoop = LineLoop;
+exports.LinePieces = LinePieces;
+exports.LineSegments = LineSegments;
+exports.LineStrip = LineStrip;
+exports.LinearEncoding = LinearEncoding;
+exports.LinearFilter = LinearFilter;
+exports.LinearInterpolant = LinearInterpolant;
+exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
+exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
+exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
+exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
+exports.LinearToneMapping = LinearToneMapping;
+exports.Loader = Loader;
+exports.LoaderUtils = LoaderUtils;
+exports.LoadingManager = LoadingManager;
+exports.LoopOnce = LoopOnce;
+exports.LoopPingPong = LoopPingPong;
+exports.LoopRepeat = LoopRepeat;
+exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
+exports.LuminanceFormat = LuminanceFormat;
+exports.MOUSE = MOUSE;
+exports.Material = Material;
+exports.MaterialLoader = MaterialLoader;
+exports.Math = MathUtils;
+exports.MathUtils = MathUtils;
+exports.Matrix3 = Matrix3;
+exports.Matrix4 = Matrix4;
+exports.MaxEquation = MaxEquation;
+exports.Mesh = Mesh;
+exports.MeshBasicMaterial = MeshBasicMaterial;
+exports.MeshDepthMaterial = MeshDepthMaterial;
+exports.MeshDistanceMaterial = MeshDistanceMaterial;
+exports.MeshFaceMaterial = MeshFaceMaterial;
+exports.MeshLambertMaterial = MeshLambertMaterial;
+exports.MeshMatcapMaterial = MeshMatcapMaterial;
+exports.MeshNormalMaterial = MeshNormalMaterial;
+exports.MeshPhongMaterial = MeshPhongMaterial;
+exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
+exports.MeshStandardMaterial = MeshStandardMaterial;
+exports.MeshToonMaterial = MeshToonMaterial;
+exports.MinEquation = MinEquation;
+exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
+exports.MixOperation = MixOperation;
+exports.MultiMaterial = MultiMaterial;
+exports.MultiplyBlending = MultiplyBlending;
+exports.MultiplyOperation = MultiplyOperation;
+exports.NearestFilter = NearestFilter;
+exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
+exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
+exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
+exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
+exports.NeverDepth = NeverDepth;
+exports.NeverStencilFunc = NeverStencilFunc;
+exports.NoBlending = NoBlending;
+exports.NoColors = NoColors;
+exports.NoToneMapping = NoToneMapping;
+exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
+exports.NormalBlending = NormalBlending;
+exports.NotEqualDepth = NotEqualDepth;
+exports.NotEqualStencilFunc = NotEqualStencilFunc;
+exports.NumberKeyframeTrack = NumberKeyframeTrack;
+exports.Object3D = Object3D;
+exports.ObjectLoader = ObjectLoader;
+exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
+exports.OctahedronBufferGeometry = OctahedronGeometry;
+exports.OctahedronGeometry = OctahedronGeometry;
+exports.OneFactor = OneFactor;
+exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
+exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
+exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
+exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
+exports.OrthographicCamera = OrthographicCamera;
+exports.PCFShadowMap = PCFShadowMap;
+exports.PCFSoftShadowMap = PCFSoftShadowMap;
+exports.PMREMGenerator = PMREMGenerator;
+exports.ParametricGeometry = ParametricGeometry;
+exports.Particle = Particle;
+exports.ParticleBasicMaterial = ParticleBasicMaterial;
+exports.ParticleSystem = ParticleSystem;
+exports.ParticleSystemMaterial = ParticleSystemMaterial;
+exports.Path = Path;
+exports.PerspectiveCamera = PerspectiveCamera;
+exports.Plane = Plane;
+exports.PlaneBufferGeometry = PlaneGeometry;
+exports.PlaneGeometry = PlaneGeometry;
+exports.PlaneHelper = PlaneHelper;
+exports.PointCloud = PointCloud;
+exports.PointCloudMaterial = PointCloudMaterial;
+exports.PointLight = PointLight;
+exports.PointLightHelper = PointLightHelper;
+exports.Points = Points;
+exports.PointsMaterial = PointsMaterial;
+exports.PolarGridHelper = PolarGridHelper;
+exports.PolyhedronBufferGeometry = PolyhedronGeometry;
+exports.PolyhedronGeometry = PolyhedronGeometry;
+exports.PositionalAudio = PositionalAudio;
+exports.PropertyBinding = PropertyBinding;
+exports.PropertyMixer = PropertyMixer;
+exports.QuadraticBezierCurve = QuadraticBezierCurve;
+exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
+exports.Quaternion = Quaternion;
+exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
+exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
+exports.REVISION = REVISION;
+exports.RGBADepthPacking = RGBADepthPacking;
+exports.RGBAFormat = RGBAFormat;
+exports.RGBAIntegerFormat = RGBAIntegerFormat;
+exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
+exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
+exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
+exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
+exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
+exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
+exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
+exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
+exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
+exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
+exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
+exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
+exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
+exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
+exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
+exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
+exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
+exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
+exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
+exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
+exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
+exports.RGB_ETC1_Format = RGB_ETC1_Format;
+exports.RGB_ETC2_Format = RGB_ETC2_Format;
+exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
+exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
+exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
+exports.RGFormat = RGFormat;
+exports.RGIntegerFormat = RGIntegerFormat;
+exports.RawShaderMaterial = RawShaderMaterial;
+exports.Ray = Ray;
+exports.Raycaster = Raycaster;
+exports.RectAreaLight = RectAreaLight;
+exports.RedFormat = RedFormat;
+exports.RedIntegerFormat = RedIntegerFormat;
+exports.ReinhardToneMapping = ReinhardToneMapping;
+exports.RepeatWrapping = RepeatWrapping;
+exports.ReplaceStencilOp = ReplaceStencilOp;
+exports.ReverseSubtractEquation = ReverseSubtractEquation;
+exports.RingBufferGeometry = RingGeometry;
+exports.RingGeometry = RingGeometry;
+exports.Scene = Scene;
+exports.SceneUtils = SceneUtils;
+exports.ShaderChunk = ShaderChunk;
+exports.ShaderLib = ShaderLib;
+exports.ShaderMaterial = ShaderMaterial;
+exports.ShadowMaterial = ShadowMaterial;
+exports.Shape = Shape;
+exports.ShapeBufferGeometry = ShapeGeometry;
+exports.ShapeGeometry = ShapeGeometry;
+exports.ShapePath = ShapePath;
+exports.ShapeUtils = ShapeUtils;
+exports.ShortType = ShortType;
+exports.Skeleton = Skeleton;
+exports.SkeletonHelper = SkeletonHelper;
+exports.SkinnedMesh = SkinnedMesh;
+exports.SmoothShading = SmoothShading;
+exports.Sphere = Sphere;
+exports.SphereBufferGeometry = SphereGeometry;
+exports.SphereGeometry = SphereGeometry;
+exports.Spherical = Spherical;
+exports.SphericalHarmonics3 = SphericalHarmonics3;
+exports.SplineCurve = SplineCurve;
+exports.SpotLight = SpotLight;
+exports.SpotLightHelper = SpotLightHelper;
+exports.Sprite = Sprite;
+exports.SpriteMaterial = SpriteMaterial;
+exports.SrcAlphaFactor = SrcAlphaFactor;
+exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
+exports.SrcColorFactor = SrcColorFactor;
+exports.StaticCopyUsage = StaticCopyUsage;
+exports.StaticDrawUsage = StaticDrawUsage;
+exports.StaticReadUsage = StaticReadUsage;
+exports.StereoCamera = StereoCamera;
+exports.StreamCopyUsage = StreamCopyUsage;
+exports.StreamDrawUsage = StreamDrawUsage;
+exports.StreamReadUsage = StreamReadUsage;
+exports.StringKeyframeTrack = StringKeyframeTrack;
+exports.SubtractEquation = SubtractEquation;
+exports.SubtractiveBlending = SubtractiveBlending;
+exports.TOUCH = TOUCH;
+exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
+exports.TetrahedronBufferGeometry = TetrahedronGeometry;
+exports.TetrahedronGeometry = TetrahedronGeometry;
+exports.TextGeometry = TextGeometry;
+exports.Texture = Texture;
+exports.TextureLoader = TextureLoader;
+exports.TorusBufferGeometry = TorusGeometry;
+exports.TorusGeometry = TorusGeometry;
+exports.TorusKnotBufferGeometry = TorusKnotGeometry;
+exports.TorusKnotGeometry = TorusKnotGeometry;
+exports.Triangle = Triangle;
+exports.TriangleFanDrawMode = TriangleFanDrawMode;
+exports.TriangleStripDrawMode = TriangleStripDrawMode;
+exports.TrianglesDrawMode = TrianglesDrawMode;
+exports.TubeBufferGeometry = TubeGeometry;
+exports.TubeGeometry = TubeGeometry;
+exports.UVMapping = UVMapping;
+exports.Uint16Attribute = Uint16Attribute;
+exports.Uint16BufferAttribute = Uint16BufferAttribute;
+exports.Uint32Attribute = Uint32Attribute;
+exports.Uint32BufferAttribute = Uint32BufferAttribute;
+exports.Uint8Attribute = Uint8Attribute;
+exports.Uint8BufferAttribute = Uint8BufferAttribute;
+exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
+exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
+exports.Uniform = Uniform;
+exports.UniformsLib = UniformsLib;
+exports.UniformsUtils = UniformsUtils;
+exports.UnsignedByteType = UnsignedByteType;
+exports.UnsignedInt248Type = UnsignedInt248Type;
+exports.UnsignedIntType = UnsignedIntType;
+exports.UnsignedShort4444Type = UnsignedShort4444Type;
+exports.UnsignedShort5551Type = UnsignedShort5551Type;
+exports.UnsignedShortType = UnsignedShortType;
+exports.VSMShadowMap = VSMShadowMap;
+exports.Vector2 = Vector2;
+exports.Vector3 = Vector3;
+exports.Vector4 = Vector4;
+exports.VectorKeyframeTrack = VectorKeyframeTrack;
+exports.Vertex = Vertex;
+exports.VertexColors = VertexColors;
+exports.VideoTexture = VideoTexture;
+exports.WebGL1Renderer = WebGL1Renderer;
+exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
+exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
+exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
+exports.WebGLRenderTarget = WebGLRenderTarget;
+exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
+exports.WebGLRenderer = WebGLRenderer;
+exports.WebGLUtils = WebGLUtils;
+exports.WireframeGeometry = WireframeGeometry;
+exports.WireframeHelper = WireframeHelper;
+exports.WrapAroundEnding = WrapAroundEnding;
+exports.XHRLoader = XHRLoader;
+exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
+exports.ZeroFactor = ZeroFactor;
+exports.ZeroSlopeEnding = ZeroSlopeEnding;
+exports.ZeroStencilOp = ZeroStencilOp;
+exports._SRGBAFormat = _SRGBAFormat;
+exports.sRGBEncoding = sRGBEncoding;

build/three.js

@@ -1,6 +1,6 @@
/**
* @license
- * Copyright 2010-2021 Three.js Authors
+ * Copyright 2010-2022 Three.js Authors
* SPDX-License-Identifier: MIT
*/
(function (global, factory) {
@@ -9,7 +9,7 @@
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.THREE = {}));
})(this, (function (exports) { 'use strict';
- const REVISION = '136';
+ const REVISION = '137';
const MOUSE = {
LEFT: 0,
MIDDLE: 1,
@@ -106,10 +106,8 @@
const HalfFloatType = 1016;
const UnsignedShort4444Type = 1017;
const UnsignedShort5551Type = 1018;
- const UnsignedShort565Type = 1019;
const UnsignedInt248Type = 1020;
const AlphaFormat = 1021;
- const RGBFormat = 1022;
const RGBAFormat = 1023;
const LuminanceFormat = 1024;
const LuminanceAlphaFormat = 1025;
@@ -119,7 +117,6 @@
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;
@@ -147,20 +144,6 @@
const RGBA_ASTC_12x10_Format = 37820;
const RGBA_ASTC_12x12_Format = 37821;
const RGBA_BPTC_Format = 36492;
- const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
- const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
- const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
- const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
- const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
- const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
- const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
- const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
- const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
- const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
- const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
- const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
- const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
- const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
const LoopOnce = 2200;
const LoopRepeat = 2201;
const LoopPingPong = 2202;
@@ -208,6 +191,7 @@
const StreamCopyUsage = 35042;
const GLSL1 = '100';
const GLSL3 = '300 es';
+ const _SRGBAFormat = 1035; // fallback for WebGL 1
/**
* https://github.com/mrdoob/eventdispatcher.js/
@@ -1070,15 +1054,13 @@
Matrix3.prototype.isMatrix3 = true;
- function arrayMax(array) {
- if (array.length === 0) return -Infinity;
- let max = array[0];
-
- for (let i = 1, l = array.length; i < l; ++i) {
- if (array[i] > max) max = array[i];
+ function arrayNeedsUint32(array) {
+ // assumes larger values usually on last
+ for (let i = array.length - 1; i >= 0; --i) {
+ if (array[i] > 65535) return true;
}
- return max;
+ return false;
}
const TYPED_ARRAYS = {
@@ -1101,6 +1083,549 @@
return document.createElementNS('http://www.w3.org/1999/xhtml', name);
}
+ const _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,
+ 'rebeccapurple': 0x663399,
+ '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
+ };
+ 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;
+ }
+
+ function SRGBToLinear(c) {
+ return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
+ }
+
+ function LinearToSRGB(c) {
+ return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
+ }
+
+ class Color {
+ constructor(r, g, b) {
+ if (g === undefined && b === undefined) {
+ // r is THREE.Color, hex or string
+ return this.set(r);
+ }
+
+ return this.setRGB(r, g, b);
+ }
+
+ set(value) {
+ if (value && value.isColor) {
+ this.copy(value);
+ } else if (typeof value === 'number') {
+ this.setHex(value);
+ } else if (typeof value === 'string') {
+ this.setStyle(value);
+ }
+
+ return this;
+ }
+
+ setScalar(scalar) {
+ this.r = scalar;
+ this.g = scalar;
+ this.b = scalar;
+ return this;
+ }
+
+ setHex(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(r, g, b) {
+ this.r = r;
+ this.g = g;
+ this.b = b;
+ return this;
+ }
+
+ setHSL(h, s, l) {
+ // h,s,l ranges are in 0.0 - 1.0
+ 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);
+ }
+
+ return this;
+ }
+
+ setStyle(style) {
+ function handleAlpha(string) {
+ if (string === undefined) return;
+
+ if (parseFloat(string) < 1) {
+ console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
+ }
+ }
+
+ let m;
+
+ if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
+ // rgb / hsl
+ 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)) {
+ // rgb(255,0,0) rgba(255,0,0,0.5)
+ 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;
+ handleAlpha(color[4]);
+ return this;
+ }
+
+ if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
+ // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
+ 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;
+ handleAlpha(color[4]);
+ return this;
+ }
+
+ break;
+
+ case 'hsl':
+ case 'hsla':
+ if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
+ // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
+ const h = parseFloat(color[1]) / 360;
+ const s = parseInt(color[2], 10) / 100;
+ const l = parseInt(color[3], 10) / 100;
+ handleAlpha(color[4]);
+ return this.setHSL(h, s, l);
+ }
+
+ break;
+ }
+ } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
+ // hex color
+ const hex = m[1];
+ const size = hex.length;
+
+ if (size === 3) {
+ // #ff0
+ this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
+ this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
+ this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
+ return this;
+ } else if (size === 6) {
+ // #ff0000
+ this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
+ this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
+ this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
+ return this;
+ }
+ }
+
+ if (style && style.length > 0) {
+ return this.setColorName(style);
+ }
+
+ return this;
+ }
+
+ setColorName(style) {
+ // color keywords
+ const hex = _colorKeywords[style.toLowerCase()];
+
+ if (hex !== undefined) {
+ // red
+ this.setHex(hex);
+ } else {
+ // unknown color
+ console.warn('THREE.Color: Unknown color ' + style);
+ }
+
+ return this;
+ }
+
+ clone() {
+ return new this.constructor(this.r, this.g, this.b);
+ }
+
+ copy(color) {
+ this.r = color.r;
+ this.g = color.g;
+ this.b = color.b;
+ return this;
+ }
+
+ copySRGBToLinear(color) {
+ this.r = SRGBToLinear(color.r);
+ this.g = SRGBToLinear(color.g);
+ this.b = SRGBToLinear(color.b);
+ return this;
+ }
+
+ copyLinearToSRGB(color) {
+ this.r = LinearToSRGB(color.r);
+ this.g = LinearToSRGB(color.g);
+ this.b = LinearToSRGB(color.b);
+ return this;
+ }
+
+ convertSRGBToLinear() {
+ this.copySRGBToLinear(this);
+ return this;
+ }
+
+ convertLinearToSRGB() {
+ this.copyLinearToSRGB(this);
+ return this;
+ }
+
+ getHex() {
+ return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
+ }
+
+ getHexString() {
+ return ('000000' + this.getHex().toString(16)).slice(-6);
+ }
+
+ getHSL(target) {
+ // h,s,l ranges are in 0.0 - 1.0
+ const r = this.r,
+ g = this.g,
+ b = this.b;
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ let hue, saturation;
+ const lightness = (min + max) / 2.0;
+
+ 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;
+ }
+
+ getStyle() {
+ return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
+ }
+
+ offsetHSL(h, s, l) {
+ this.getHSL(_hslA);
+ _hslA.h += h;
+ _hslA.s += s;
+ _hslA.l += l;
+ this.setHSL(_hslA.h, _hslA.s, _hslA.l);
+ return this;
+ }
+
+ add(color) {
+ this.r += color.r;
+ this.g += color.g;
+ this.b += color.b;
+ return this;
+ }
+
+ addColors(color1, color2) {
+ this.r = color1.r + color2.r;
+ this.g = color1.g + color2.g;
+ this.b = color1.b + color2.b;
+ return this;
+ }
+
+ addScalar(s) {
+ this.r += s;
+ this.g += s;
+ this.b += s;
+ return this;
+ }
+
+ 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;
+ }
+
+ multiply(color) {
+ this.r *= color.r;
+ this.g *= color.g;
+ this.b *= color.b;
+ return this;
+ }
+
+ multiplyScalar(s) {
+ this.r *= s;
+ this.g *= s;
+ this.b *= s;
+ return this;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ equals(c) {
+ return c.r === this.r && c.g === this.g && c.b === this.b;
+ }
+
+ fromArray(array, offset = 0) {
+ this.r = array[offset];
+ this.g = array[offset + 1];
+ this.b = array[offset + 2];
+ return this;
+ }
+
+ toArray(array = [], offset = 0) {
+ array[offset] = this.r;
+ array[offset + 1] = this.g;
+ array[offset + 2] = this.b;
+ return array;
+ }
+
+ fromBufferAttribute(attribute, index) {
+ this.r = attribute.getX(index);
+ this.g = attribute.getY(index);
+ this.b = attribute.getZ(index);
+
+ if (attribute.normalized === true) {
+ // assuming Uint8Array
+ this.r /= 255;
+ this.g /= 255;
+ this.b /= 255;
+ }
+
+ return this;
+ }
+
+ toJSON() {
+ return this.getHex();
+ }
+
+ }
+
+ Color.NAMES = _colorKeywords;
+ Color.prototype.isColor = true;
+ Color.prototype.r = 1;
+ Color.prototype.g = 1;
+ Color.prototype.b = 1;
+
let _canvas;
class ImageUtils {
@@ -1141,6 +1666,45 @@
}
}
+ 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 {
+ // assuming float
+ data[i] = SRGBToLinear(data[i]);
+ }
+ }
+
+ return {
+ data: data,
+ width: image.width,
+ height: image.height
+ };
+ } else {
+ console.warn('THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.');
+ return image;
+ }
+ }
+
}
let textureId = 0;
@@ -1183,7 +1747,9 @@
this.userData = {};
this.version = 0;
this.onUpdate = null;
- this.isRenderTargetTexture = false;
+ this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
+
+ this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
}
updateMatrix() {
@@ -1946,10 +2512,9 @@
this.height = source.height;
this.depth = source.depth;
this.viewport.copy(source.viewport);
- this.texture = source.texture.clone();
- this.texture.image = { ...this.texture.image
- }; // See #20328.
+ this.texture = source.texture.clone(); // ensure image object is not shared, see #20328
+ this.texture.image = Object.assign({}, source.texture.image);
this.depthBuffer = source.depthBuffer;
this.stencilBuffer = source.stencilBuffer;
this.depthTexture = source.depthTexture;
@@ -2515,7 +3080,7 @@
}
slerpQuaternions(qa, qb, t) {
- this.copy(qa).slerp(qb, t);
+ return this.copy(qa).slerp(qb, t);
}
random() {
@@ -3196,9 +3761,9 @@
return this;
}
- setFromObject(object) {
+ setFromObject(object, precise = false) {
this.makeEmpty();
- return this.expandByObject(object);
+ return this.expandByObject(object, precise);
}
clone() {
@@ -3248,13 +3813,22 @@
return this;
}
- expandByObject(object) {
+ expandByObject(object, precise = false) {
// Computes the world-axis-aligned bounding box of an object (including its children),
// accounting for both the object's, and children's, world transforms
object.updateWorldMatrix(false, false);
const geometry = object.geometry;
if (geometry !== undefined) {
+ if (precise && geometry.attributes != undefined && geometry.attributes.position !== undefined) {
+ const position = geometry.attributes.position;
+
+ for (let i = 0, l = position.count; i < l; i++) {
+ _vector$b.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
+
+ this.expandByPoint(_vector$b);
+ }
+ } else {
if (geometry.boundingBox === null) {
geometry.computeBoundingBox();
}
@@ -3265,11 +3839,12 @@
this.union(_box$3);
}
+ }
const children = object.children;
for (let i = 0, l = children.length; i < l; i++) {
- this.expandByObject(children[i]);
+ this.expandByObject(children[i], precise);
}
return this;
@@ -5963,7 +6538,6 @@
this.side = FrontSide;
this.vertexColors = false;
this.opacity = 1;
- this.format = RGBAFormat;
this.transparent = false;
this.blendSrc = SrcAlphaFactor;
this.blendDst = OneMinusSrcAlphaFactor;
@@ -5987,6 +6561,7 @@
this.clipShadows = false;
this.shadowSide = null;
this.colorWrite = true;
+ this.alphaWrite = true;
this.precision = null; // override the renderer's default precision for this material
this.polygonOffset = false;
@@ -6172,12 +6747,12 @@
if (this.side !== FrontSide) data.side = this.side;
if (this.vertexColors) data.vertexColors = true;
if (this.opacity < 1) data.opacity = this.opacity;
- if (this.format !== RGBAFormat) data.format = this.format;
if (this.transparent === true) data.transparent = this.transparent;
data.depthFunc = this.depthFunc;
data.depthTest = this.depthTest;
data.depthWrite = this.depthWrite;
data.colorWrite = this.colorWrite;
+ data.alphaWrite = this.alphaWrite;
data.stencilWrite = this.stencilWrite;
data.stencilWriteMask = this.stencilWriteMask;
data.stencilFunc = this.stencilFunc;
@@ -6241,7 +6816,6 @@
this.side = source.side;
this.vertexColors = source.vertexColors;
this.opacity = source.opacity;
- this.format = source.format;
this.transparent = source.transparent;
this.blendSrc = source.blendSrc;
this.blendDst = source.blendDst;
@@ -6277,6 +6851,7 @@
this.clipShadows = source.clipShadows;
this.shadowSide = source.shadowSide;
this.colorWrite = source.colorWrite;
+ this.alphaWrite = source.alphaWrite;
this.precision = source.precision;
this.polygonOffset = source.polygonOffset;
this.polygonOffsetFactor = source.polygonOffsetFactor;
@@ -6305,549 +6880,6 @@
Material.prototype.isMaterial = true;
- const _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,
- 'rebeccapurple': 0x663399,
- '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
- };
- 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;
- }
-
- function SRGBToLinear(c) {
- return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
- }
-
- function LinearToSRGB(c) {
- return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
- }
-
- class Color {
- constructor(r, g, b) {
- if (g === undefined && b === undefined) {
- // r is THREE.Color, hex or string
- return this.set(r);
- }
-
- return this.setRGB(r, g, b);
- }
-
- set(value) {
- if (value && value.isColor) {
- this.copy(value);
- } else if (typeof value === 'number') {
- this.setHex(value);
- } else if (typeof value === 'string') {
- this.setStyle(value);
- }
-
- return this;
- }
-
- setScalar(scalar) {
- this.r = scalar;
- this.g = scalar;
- this.b = scalar;
- return this;
- }
-
- setHex(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(r, g, b) {
- this.r = r;
- this.g = g;
- this.b = b;
- return this;
- }
-
- setHSL(h, s, l) {
- // h,s,l ranges are in 0.0 - 1.0
- 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);
- }
-
- return this;
- }
-
- setStyle(style) {
- function handleAlpha(string) {
- if (string === undefined) return;
-
- if (parseFloat(string) < 1) {
- console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
- }
- }
-
- let m;
-
- if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
- // rgb / hsl
- 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)) {
- // rgb(255,0,0) rgba(255,0,0,0.5)
- 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;
- handleAlpha(color[4]);
- return this;
- }
-
- if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
- // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
- 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;
- handleAlpha(color[4]);
- return this;
- }
-
- break;
-
- case 'hsl':
- case 'hsla':
- if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
- // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
- const h = parseFloat(color[1]) / 360;
- const s = parseInt(color[2], 10) / 100;
- const l = parseInt(color[3], 10) / 100;
- handleAlpha(color[4]);
- return this.setHSL(h, s, l);
- }
-
- break;
- }
- } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
- // hex color
- const hex = m[1];
- const size = hex.length;
-
- if (size === 3) {
- // #ff0
- this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
- this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
- this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
- return this;
- } else if (size === 6) {
- // #ff0000
- this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
- this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
- this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
- return this;
- }
- }
-
- if (style && style.length > 0) {
- return this.setColorName(style);
- }
-
- return this;
- }
-
- setColorName(style) {
- // color keywords
- const hex = _colorKeywords[style.toLowerCase()];
-
- if (hex !== undefined) {
- // red
- this.setHex(hex);
- } else {
- // unknown color
- console.warn('THREE.Color: Unknown color ' + style);
- }
-
- return this;
- }
-
- clone() {
- return new this.constructor(this.r, this.g, this.b);
- }
-
- copy(color) {
- this.r = color.r;
- this.g = color.g;
- this.b = color.b;
- return this;
- }
-
- copySRGBToLinear(color) {
- this.r = SRGBToLinear(color.r);
- this.g = SRGBToLinear(color.g);
- this.b = SRGBToLinear(color.b);
- return this;
- }
-
- copyLinearToSRGB(color) {
- this.r = LinearToSRGB(color.r);
- this.g = LinearToSRGB(color.g);
- this.b = LinearToSRGB(color.b);
- return this;
- }
-
- convertSRGBToLinear() {
- this.copySRGBToLinear(this);
- return this;
- }
-
- convertLinearToSRGB() {
- this.copyLinearToSRGB(this);
- return this;
- }
-
- getHex() {
- return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
- }
-
- getHexString() {
- return ('000000' + this.getHex().toString(16)).slice(-6);
- }
-
- getHSL(target) {
- // h,s,l ranges are in 0.0 - 1.0
- const r = this.r,
- g = this.g,
- b = this.b;
- const max = Math.max(r, g, b);
- const min = Math.min(r, g, b);
- let hue, saturation;
- const lightness = (min + max) / 2.0;
-
- 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;
- }
-
- getStyle() {
- return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
- }
-
- offsetHSL(h, s, l) {
- this.getHSL(_hslA);
- _hslA.h += h;
- _hslA.s += s;
- _hslA.l += l;
- this.setHSL(_hslA.h, _hslA.s, _hslA.l);
- return this;
- }
-
- add(color) {
- this.r += color.r;
- this.g += color.g;
- this.b += color.b;
- return this;
- }
-
- addColors(color1, color2) {
- this.r = color1.r + color2.r;
- this.g = color1.g + color2.g;
- this.b = color1.b + color2.b;
- return this;
- }
-
- addScalar(s) {
- this.r += s;
- this.g += s;
- this.b += s;
- return this;
- }
-
- 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;
- }
-
- multiply(color) {
- this.r *= color.r;
- this.g *= color.g;
- this.b *= color.b;
- return this;
- }
-
- multiplyScalar(s) {
- this.r *= s;
- this.g *= s;
- this.b *= s;
- return this;
- }
-
- 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;
- }
-
- 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;
- }
-
- 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;
- }
-
- equals(c) {
- return c.r === this.r && c.g === this.g && c.b === this.b;
- }
-
- fromArray(array, offset = 0) {
- this.r = array[offset];
- this.g = array[offset + 1];
- this.b = array[offset + 2];
- return this;
- }
-
- toArray(array = [], offset = 0) {
- array[offset] = this.r;
- array[offset + 1] = this.g;
- array[offset + 2] = this.b;
- return array;
- }
-
- fromBufferAttribute(attribute, index) {
- this.r = attribute.getX(index);
- this.g = attribute.getY(index);
- this.b = attribute.getZ(index);
-
- if (attribute.normalized === true) {
- // assuming Uint8Array
- this.r /= 255;
- this.g /= 255;
- this.b /= 255;
- }
-
- return this;
- }
-
- toJSON() {
- return this.getHex();
- }
-
- }
-
- Color.NAMES = _colorKeywords;
- Color.prototype.isColor = true;
- Color.prototype.r = 1;
- Color.prototype.g = 1;
- Color.prototype.b = 1;
-
/**
* parameters = {
* color: <hex>,
@@ -7336,7 +7368,7 @@
setIndex(index) {
if (Array.isArray(index)) {
- this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
+ this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
} else {
this.index = index;
}
@@ -9011,6 +9043,7 @@
renderer.render(scene, cameraNZ);
renderer.setRenderTarget(currentRenderTarget);
renderer.xr.enabled = currentXrEnabled;
+ renderTarget.texture.needsPMREMUpdate = true;
}
}
@@ -9054,7 +9087,6 @@
this.texture.isRenderTargetTexture = true;
this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
- this.texture._needsFlipEnvMap = false;
}
fromEquirectangularTexture(renderer, texture) {
@@ -9672,15 +9704,15 @@
var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
- var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
+ var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
- var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
+ var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
- var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
+ var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
@@ -9700,7 +9732,7 @@
var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
- var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
+ var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
@@ -9718,13 +9750,13 @@
var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
- var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\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\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= specularColorMapTexelToLinear( texture2D( specularColorMap, vUv ) ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= sheenColorMapTexelToLinear( texture2D( sheenColorMap, vUv ) ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
+ var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\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\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\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\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
- var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
+ var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
@@ -9736,11 +9768,11 @@
var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
- var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
+ var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
- var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
+ var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
@@ -9748,11 +9780,11 @@
var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
- var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
+ var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
- var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
+ var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
@@ -9814,7 +9846,7 @@
var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif";
- var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
+ var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
@@ -9831,7 +9863,7 @@
var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
const vertex$g = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
- const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
+ const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
const vertex$f = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
const fragment$f = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
@@ -9843,19 +9875,19 @@
const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
- const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
+ const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
- const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
+ const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
const vertex$9 = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
const fragment$9 = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
- const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
+ const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
@@ -10503,7 +10535,7 @@
value: null
},
sheenRoughness: {
- value: 0
+ value: 1
},
sheenRoughnessMap: {
value: null
@@ -10533,7 +10565,7 @@
value: new Color(0x000000)
},
specularIntensity: {
- value: 0
+ value: 1
},
specularIntensityMap: {
value: null
@@ -10549,9 +10581,9 @@
fragmentShader: ShaderChunk.meshphysical_frag
};
- function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
+ function WebGLBackground(renderer, cubemaps, state, objects, alpha, premultipliedAlpha) {
const clearColor = new Color(0x000000);
- let clearAlpha = 0;
+ let clearAlpha = alpha === true ? 0 : 1;
let planeMesh;
let boxMesh;
let currentBackground = null;
@@ -11339,11 +11371,9 @@
const image = texture.image;
if (image && image.height > 0) {
- const currentRenderTarget = renderer.getRenderTarget();
const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
renderTarget.fromEquirectangularTexture(renderer, texture);
cubemaps.set(texture, renderTarget);
- renderer.setRenderTarget(currentRenderTarget);
texture.addEventListener('dispose', onTextureDispose);
return mapTextureMapping(renderTarget.texture, texture.mapping);
} else {
@@ -11499,10 +11529,6 @@
// samples and exit early, but not recompile the shader.
const MAX_SAMPLES = 20;
- const ENCODINGS = {
- [LinearEncoding]: 0,
- [sRGBEncoding]: 1
- };
const _flatCamera = /*@__PURE__*/new OrthographicCamera();
@@ -11579,8 +11605,8 @@
*/
- fromEquirectangular(equirectangular) {
- return this._fromTexture(equirectangular);
+ fromEquirectangular(equirectangular, renderTarget = null) {
+ return this._fromTexture(equirectangular, renderTarget);
}
/**
* Generates a PMREM from an cubemap texture, which can be either LDR
@@ -11589,8 +11615,8 @@
*/
- fromCubemap(cubemap) {
- return this._fromTexture(cubemap);
+ 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
@@ -11628,6 +11654,7 @@
dispose() {
this._blurMaterial.dispose();
+ if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose();
if (this._cubemapShader !== null) this._cubemapShader.dispose();
if (this._equirectShader !== null) this._equirectShader.dispose();
@@ -11638,8 +11665,6 @@
_cleanup(outputTarget) {
- this._pingPongRenderTarget.dispose();
-
this._renderer.setRenderTarget(_oldTarget);
outputTarget.scissorTest = false;
@@ -11647,10 +11672,10 @@
_setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
}
- _fromTexture(texture) {
+ _fromTexture(texture, renderTarget) {
_oldTarget = this._renderer.getRenderTarget();
- const cubeUVRenderTarget = this._allocateTargets(texture);
+ const cubeUVRenderTarget = renderTarget || this._allocateTargets(texture);
this._textureToCubeUV(texture, cubeUVRenderTarget);
@@ -11676,7 +11701,11 @@
const cubeUVRenderTarget = _createRenderTarget(params);
cubeUVRenderTarget.depthBuffer = texture ? false : true;
+
+ if (this._pingPongRenderTarget === null) {
this._pingPongRenderTarget = _createRenderTarget(params);
+ }
+
return cubeUVRenderTarget;
}
@@ -11722,10 +11751,10 @@
for (let i = 0; i < 6; i++) {
const col = i % 3;
- if (col == 0) {
+ if (col === 0) {
cubeCamera.up.set(0, upSign[i], 0);
cubeCamera.lookAt(forwardSign[i], 0, 0);
- } else if (col == 1) {
+ } else if (col === 1) {
cubeCamera.up.set(0, 0, upSign[i]);
cubeCamera.lookAt(0, forwardSign[i], 0);
} else {
@@ -11751,24 +11780,18 @@
scene.background = background;
}
- _setEncoding(uniform, texture) {
- if (this._renderer.capabilities.isWebGL2 === true && texture.format === RGBAFormat && texture.type === UnsignedByteType && texture.encoding === sRGBEncoding) {
- uniform.value = ENCODINGS[LinearEncoding];
- } else {
- uniform.value = ENCODINGS[texture.encoding];
- }
- }
-
_textureToCubeUV(texture, cubeUVRenderTarget) {
const renderer = this._renderer;
const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping;
if (isCubeTexture) {
- if (this._cubemapShader == null) {
+ if (this._cubemapShader === null) {
this._cubemapShader = _getCubemapShader();
}
+
+ this._cubemapShader.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1;
} else {
- if (this._equirectShader == null) {
+ if (this._equirectShader === null) {
this._equirectShader = _getEquirectShader();
}
}
@@ -11782,8 +11805,6 @@
uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
}
- this._setEncoding(uniforms['inputEncoding'], texture);
-
_setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
renderer.setRenderTarget(cubeUVRenderTarget);
@@ -11850,7 +11871,7 @@
const weight = Math.exp(-x * x / 2);
weights.push(weight);
- if (i == 0) {
+ if (i === 0) {
sum += weight;
} else if (i < samples) {
sum += 2 * weight;
@@ -11899,7 +11920,7 @@
if (i > LOD_MAX - LOD_MIN) {
sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
- } else if (i == 0) {
+ } else if (i === 0) {
sigma = 0;
}
@@ -12009,8 +12030,6 @@
uniform float mipInt;
uniform vec3 poleAxis;
- ${_getEncodings()}
-
#define ENVMAP_TYPE_CUBE_UV
#include <cube_uv_reflection_fragment>
@@ -12074,9 +12093,6 @@
},
'texelSize': {
value: texelSize
- },
- 'inputEncoding': {
- value: ENCODINGS[LinearEncoding]
}
},
vertexShader: _getCommonVertexShader(),
@@ -12092,8 +12108,6 @@
uniform sampler2D envMap;
uniform vec2 texelSize;
- ${_getEncodings()}
-
#include <common>
void main() {
@@ -12105,13 +12119,13 @@
vec2 f = fract( uv / texelSize - 0.5 );
uv -= f * texelSize;
- vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
+ vec3 tl = texture2D ( envMap, uv ).rgb;
uv.x += texelSize.x;
- vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
+ vec3 tr = texture2D ( envMap, uv ).rgb;
uv.y += texelSize.y;
- vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
+ vec3 br = texture2D ( envMap, uv ).rgb;
uv.x -= texelSize.x;
- vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
+ vec3 bl = texture2D ( envMap, uv ).rgb;
vec3 tm = mix( tl, tr, f.x );
vec3 bm = mix( bl, br, f.x );
@@ -12133,8 +12147,8 @@
'envMap': {
value: null
},
- 'inputEncoding': {
- value: ENCODINGS[LinearEncoding]
+ 'flipEnvMap': {
+ value: -1
}
},
vertexShader: _getCommonVertexShader(),
@@ -12145,15 +12159,15 @@
precision mediump float;
precision mediump int;
+ uniform float flipEnvMap;
+
varying vec3 vOutputDirection;
uniform samplerCube envMap;
- ${_getEncodings()}
-
void main() {
- gl_FragColor = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) );
+ gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
}
`,
@@ -12228,61 +12242,34 @@
);
}
- function _getEncodings() {
- return (
- /* glsl */
- `
-
- uniform int inputEncoding;
-
- #include <encodings_pars_fragment>
-
- vec4 inputTexelToLinear( vec4 value ) {
-
- if ( inputEncoding == 0 ) {
-
- return value;
-
- } else {
-
- return sRGBToLinear( value );
-
- }
-
- }
-
- vec4 envMapTexelToLinear( vec4 color ) {
-
- return inputTexelToLinear( color );
-
- }
- `
- );
- }
-
function WebGLCubeUVMaps(renderer) {
let cubeUVmaps = new WeakMap();
let pmremGenerator = null;
function get(texture) {
- if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
+ if (texture && texture.isTexture) {
const mapping = texture.mapping;
const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
- const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
+ const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; // equirect/cube map to cubeUV conversion
if (isEquirectMap || isCubeMap) {
- // equirect/cube map to cubeUV conversion
+ if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) {
+ texture.needsPMREMUpdate = false;
+ let renderTarget = cubeUVmaps.get(texture);
+ if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
+ renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget);
+ cubeUVmaps.set(texture, renderTarget);
+ return renderTarget.texture;
+ } else {
if (cubeUVmaps.has(texture)) {
return cubeUVmaps.get(texture).texture;
} else {
const image = texture.image;
if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
- const currentRenderTarget = renderer.getRenderTarget();
if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
cubeUVmaps.set(texture, renderTarget);
- renderer.setRenderTarget(currentRenderTarget);
texture.addEventListener('dispose', onTextureDispose);
return renderTarget.texture;
} else {
@@ -12292,6 +12279,7 @@
}
}
}
+ }
return texture;
}
@@ -12491,7 +12479,7 @@
}
}
- const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
+ const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
//
@@ -12748,6 +12736,14 @@
size: new Vector2(width, height)
};
morphTextures.set(geometry, entry);
+
+ function disposeTexture() {
+ texture.dispose();
+ morphTextures.delete(geometry);
+ geometry.removeEventListener('dispose', disposeTexture);
+ }
+
+ geometry.addEventListener('dispose', disposeTexture);
} //
@@ -13770,11 +13766,6 @@
return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers(gl.getShaderSource(shader));
}
- function getTexelDecodingFunction(functionName, encoding) {
- const components = getEncodingComponents(encoding);
- return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
- }
-
function getTexelEncodingFunction(functionName, encoding) {
const components = getEncodingComponents(encoding);
return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
@@ -14020,9 +14011,9 @@
}
} else {
prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define MAX_BONES ' + parameters.maxBones, 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.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.morphTargets && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE' : '', parameters.morphTargets && parameters.isWebGL2 ? '#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.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', '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', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', ' 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', '\n'].filter(filterEmptyLine).join('\n');
- prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', 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 : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', 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.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', '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.format === RGBFormat ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
- parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.specularColorMap ? getTexelDecodingFunction('specularColorMapTexelToLinear', parameters.specularColorMapEncoding) : '', parameters.sheenColorMap ? getTexelDecodingFunction('sheenColorMapTexelToLinear', parameters.sheenColorMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
+ prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', 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 : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', 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.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', '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.alphaWrite ? '' : '#define OPAQUE', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
+ getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
}
vertexShader = resolveIncludes(vertexShader);
@@ -14282,25 +14273,6 @@
}
}
- function getTextureEncodingFromMap(map) {
- let encoding;
-
- if (map && map.isTexture) {
- encoding = map.encoding;
- } else if (map && map.isWebGLRenderTarget) {
- console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
- encoding = map.texture.encoding;
- } else {
- encoding = LinearEncoding;
- }
-
- if (isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding) {
- encoding = LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
- }
-
- return encoding;
- }
-
function getParameters(material, lights, shadows, scene, object) {
const fog = scene.fog;
const environment = material.isMeshStandardMaterial ? scene.environment : null;
@@ -14353,24 +14325,20 @@
instancing: object.isInstancedMesh === true,
instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
supportsVertexTextures: vertexTextures,
- outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
+ outputEncoding: currentRenderTarget === null ? renderer.outputEncoding : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding,
map: !!material.map,
- mapEncoding: getTextureEncodingFromMap(material.map),
matcap: !!material.matcap,
- matcapEncoding: getTextureEncodingFromMap(material.matcap),
envMap: !!envMap,
envMapMode: envMap && envMap.mapping,
- envMapEncoding: getTextureEncodingFromMap(envMap),
envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
lightMap: !!material.lightMap,
- lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
aoMap: !!material.aoMap,
emissiveMap: !!material.emissiveMap,
- emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
bumpMap: !!material.bumpMap,
normalMap: !!material.normalMap,
objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
+ decodeVideoTexture: !!material.map && material.map.isVideoTexture === true && material.map.encoding === sRGBEncoding,
clearcoat: useClearcoat,
clearcoatMap: useClearcoat && !!material.clearcoatMap,
clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
@@ -14381,13 +14349,12 @@
specularMap: !!material.specularMap,
specularIntensityMap: !!material.specularIntensityMap,
specularColorMap: !!material.specularColorMap,
- specularColorMapEncoding: getTextureEncodingFromMap(material.specularColorMap),
alphaMap: !!material.alphaMap,
alphaTest: useAlphaTest,
+ alphaWrite: material.alphaWrite || material.transparent,
gradientMap: !!material.gradientMap,
sheen: material.sheen > 0,
sheenColorMap: !!material.sheenColorMap,
- sheenColorMapEncoding: getTextureEncodingFromMap(material.sheenColorMap),
sheenRoughnessMap: !!material.sheenRoughnessMap,
transmission: material.transmission > 0,
transmissionMap: !!material.transmissionMap,
@@ -14420,7 +14387,6 @@
numSpotLightShadows: lights.spotShadowMap.length,
numClippingPlanes: clipping.numPlanes,
numClipIntersection: clipping.numIntersection,
- format: material.format,
dithering: material.dithering,
shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
shadowMapType: renderer.shadowMap.type,
@@ -14473,12 +14439,7 @@
function getProgramCacheKeyParameters(array, parameters) {
array.push(parameters.precision);
array.push(parameters.outputEncoding);
- array.push(parameters.mapEncoding);
- array.push(parameters.matcapEncoding);
array.push(parameters.envMapMode);
- array.push(parameters.envMapEncoding);
- array.push(parameters.lightMapEncoding);
- array.push(parameters.emissiveMapEncoding);
array.push(parameters.combine);
array.push(parameters.vertexUvs);
array.push(parameters.fogExp2);
@@ -14497,9 +14458,7 @@
array.push(parameters.toneMapping);
array.push(parameters.numClippingPlanes);
array.push(parameters.numClipIntersection);
- array.push(parameters.format);
- array.push(parameters.specularColorMapEncoding);
- array.push(parameters.sheenColorMapEncoding);
+ array.push(parameters.alphaWrite);
}
function getProgramCacheKeyBooleans(array, parameters) {
@@ -14563,6 +14522,7 @@
if (parameters.sheen) _programLayers.enable(19);
if (parameters.sheenColorMap) _programLayers.enable(20);
if (parameters.sheenRoughnessMap) _programLayers.enable(21);
+ if (parameters.decodeVideoTexture) _programLayers.enable(22);
array.push(_programLayers.mask);
}
@@ -15876,6 +15836,8 @@
const stencilBuffer = new StencilBuffer();
let enabledCapabilities = {};
let currentBoundFramebuffers = {};
+ let currentDrawbuffers = new WeakMap();
+ let defaultDrawbuffers = [];
let currentProgram = null;
let currentBlendingEnabled = false;
let currentBlending = null;
@@ -15976,6 +15938,51 @@
return false;
}
+ function drawBuffers(renderTarget, framebuffer) {
+ let drawBuffers = defaultDrawbuffers;
+ let needsUpdate = false;
+
+ if (renderTarget) {
+ drawBuffers = currentDrawbuffers.get(framebuffer);
+
+ if (drawBuffers === undefined) {
+ drawBuffers = [];
+ currentDrawbuffers.set(framebuffer, drawBuffers);
+ }
+
+ if (renderTarget.isWebGLMultipleRenderTargets) {
+ const textures = renderTarget.texture;
+
+ if (drawBuffers.length !== textures.length || drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
+ for (let i = 0, il = textures.length; i < il; i++) {
+ drawBuffers[i] = gl.COLOR_ATTACHMENT0 + i;
+ }
+
+ drawBuffers.length = textures.length;
+ needsUpdate = true;
+ }
+ } else {
+ if (drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
+ drawBuffers[0] = gl.COLOR_ATTACHMENT0;
+ needsUpdate = true;
+ }
+ }
+ } else {
+ if (drawBuffers[0] !== gl.BACK) {
+ drawBuffers[0] = gl.BACK;
+ needsUpdate = true;
+ }
+ }
+
+ if (needsUpdate) {
+ if (capabilities.isWebGL2) {
+ gl.drawBuffers(drawBuffers);
+ } else {
+ extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(drawBuffers);
+ }
+ }
+ }
+
function useProgram(program) {
if (currentProgram !== program) {
gl.useProgram(program);
@@ -16052,7 +16059,7 @@
break;
case SubtractiveBlending:
- gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
+ gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
break;
case MultiplyBlending:
@@ -16074,7 +16081,7 @@
break;
case SubtractiveBlending:
- gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
+ gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
break;
case MultiplyBlending:
@@ -16369,6 +16376,8 @@
currentTextureSlot = null;
currentBoundTextures = {};
currentBoundFramebuffers = {};
+ currentDrawbuffers = new WeakMap();
+ defaultDrawbuffers = [];
currentProgram = null;
currentBlendingEnabled = false;
currentBlending = null;
@@ -16400,6 +16409,7 @@
enable: enable,
disable: disable,
bindFramebuffer: bindFramebuffer,
+ drawBuffers: drawBuffers,
useProgram: useProgram,
setBlending: setBlending,
setMaterial: setMaterial,
@@ -16505,7 +16515,7 @@
_gl.generateMipmap(target);
}
- function getInternalFormat(internalFormatName, glFormat, glType, encoding) {
+ function getInternalFormat(internalFormatName, glFormat, glType, encoding, isVideoTexture = false) {
if (isWebGL2 === false) return glFormat;
if (internalFormatName !== null) {
@@ -16521,19 +16531,21 @@
if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
}
- if (glFormat === _gl.RGB) {
- if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
- if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
- if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
+ 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 (glFormat === _gl.RGBA) {
if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
- if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
+ if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding && isVideoTexture === false ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
+ 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.RGBA16F || internalFormat === _gl.RGBA32F) {
+ 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');
}
@@ -16806,11 +16818,12 @@
_gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
- const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
+ let image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
+ image = verifyColorSpace(texture, image);
const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
- glFormat = utils.convert(texture.format);
+ glFormat = utils.convert(texture.format, texture.encoding);
let glType = utils.convert(texture.type),
- glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
+ glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture);
setTextureParameters(textureType, texture, supportsMips);
let mipmap;
const mipmaps = texture.mipmaps;
@@ -16909,7 +16922,7 @@
for (let i = 0, il = mipmaps.length; i < il; i++) {
mipmap = mipmaps[i];
- if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
+ if (texture.format !== RGBAFormat) {
if (glFormat !== null) {
if (useTexStorage) {
state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
@@ -17019,11 +17032,13 @@
} else {
cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
}
+
+ cubeImage[i] = verifyColorSpace(texture, cubeImage[i]);
}
const image = cubeImage[0],
supportsMips = isPowerOfTwo$1(image) || isWebGL2,
- glFormat = utils.convert(texture.format),
+ glFormat = utils.convert(texture.format, texture.encoding),
glType = utils.convert(texture.type),
glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
@@ -17043,7 +17058,7 @@
for (let j = 0; j < mipmaps.length; j++) {
const mipmap = mipmaps[j];
- if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
+ if (texture.format !== RGBAFormat) {
if (glFormat !== null) {
if (useTexStorage) {
state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
@@ -17123,7 +17138,7 @@
function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
- const glFormat = utils.convert(texture.format);
+ const glFormat = utils.convert(texture.format, texture.encoding);
const glType = utils.convert(texture.type);
const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
const renderTargetProperties = properties.get(renderTarget);
@@ -17192,7 +17207,7 @@
} else {
// Use the first texture for MRT so far
const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
- const glFormat = utils.convert(texture.format);
+ const glFormat = utils.convert(texture.format, texture.encoding);
const glType = utils.convert(texture.type);
const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
const samples = getRenderTargetSamples(renderTarget);
@@ -17308,13 +17323,7 @@
const isCube = renderTarget.isWebGLCubeRenderTarget === true;
const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
- const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
-
- if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
- texture.format = RGBAFormat;
- console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
- } // Setup framebuffer
-
+ const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Setup framebuffer
if (isCube) {
renderTargetProperties.__webglFramebuffer = [];
@@ -17347,7 +17356,7 @@
_gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
- const glFormat = utils.convert(texture.format);
+ const glFormat = utils.convert(texture.format, texture.encoding);
const glType = utils.convert(texture.type);
const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
const samples = getRenderTargetSamples(renderTarget);
@@ -17503,6 +17512,40 @@
texture.update();
}
+ }
+
+ function verifyColorSpace(texture, image) {
+ const encoding = texture.encoding;
+ const format = texture.format;
+ const type = texture.type;
+ if (texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat) return image;
+
+ if (encoding !== LinearEncoding) {
+ // sRGB
+ if (encoding === sRGBEncoding) {
+ if (isWebGL2 === false) {
+ // in WebGL 1, try to use EXT_sRGB extension and unsized formats
+ if (extensions.has('EXT_sRGB') === true && format === RGBAFormat) {
+ texture.format = _SRGBAFormat; // it's not possible to generate mips in WebGL 1 with this extension
+
+ texture.minFilter = LinearFilter;
+ texture.generateMipmaps = false;
+ } else {
+ // slow fallback (CPU decode)
+ image = ImageUtils.sRGBToLinear(image);
+ }
+ } else {
+ // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
+ if (format !== RGBAFormat || type !== UnsignedByteType) {
+ console.warn('THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.');
+ }
+ }
+ } else {
+ console.error('THREE.WebGLTextures: Unsupported texture encoding:', encoding);
+ }
+ }
+
+ return image;
} // backwards compatibility
@@ -17555,12 +17598,11 @@
function WebGLUtils(gl, extensions, capabilities) {
const isWebGL2 = capabilities.isWebGL2;
- function convert(p) {
+ function convert(p, encoding = null) {
let extension;
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 === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
if (p === ByteType) return gl.BYTE;
if (p === ShortType) return gl.SHORT;
if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
@@ -17580,21 +17622,42 @@
}
if (p === AlphaFormat) return gl.ALPHA;
- if (p === RGBFormat) return gl.RGB;
if (p === RGBAFormat) return gl.RGBA;
if (p === LuminanceFormat) return gl.LUMINANCE;
if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
if (p === DepthFormat) return gl.DEPTH_COMPONENT;
if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
- if (p === RedFormat) return gl.RED; // WebGL2 formats.
+ if (p === RedFormat) return gl.RED; // WebGL 1 sRGB fallback
+
+ if (p === _SRGBAFormat) {
+ extension = extensions.get('EXT_sRGB');
+
+ if (extension !== null) {
+ return extension.SRGB_ALPHA_EXT;
+ } else {
+ return null;
+ }
+ } // WebGL2 formats.
+
if (p === RedIntegerFormat) return gl.RED_INTEGER;
if (p === RGFormat) return gl.RG;
if (p === RGIntegerFormat) return gl.RG_INTEGER;
- if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
- if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
+ if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER; // S3TC
if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
+ if (encoding === sRGBEncoding) {
+ 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) {
@@ -17606,6 +17669,8 @@
return null;
}
}
+ } // PVRTC
+
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');
@@ -17618,7 +17683,8 @@
} else {
return null;
}
- }
+ } // ETC1
+
if (p === RGB_ETC1_Format) {
extension = extensions.get('WEBGL_compressed_texture_etc1');
@@ -17628,38 +17694,55 @@
} else {
return null;
}
- }
+ } // ETC2
+
if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
extension = extensions.get('WEBGL_compressed_texture_etc');
if (extension !== null) {
- if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
- if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
- }
+ if (p === RGB_ETC2_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
+ if (p === RGBA_ETC2_EAC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
+ } else {
+ return null;
}
+ } // ASTC
+
- 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 || p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format) {
+ 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) {
- // TODO Complete?
- return p;
+ if (p === RGBA_ASTC_4x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
+ if (p === RGBA_ASTC_5x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
+ if (p === RGBA_ASTC_5x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
+ if (p === RGBA_ASTC_6x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
+ if (p === RGBA_ASTC_6x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
+ if (p === RGBA_ASTC_8x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
+ if (p === RGBA_ASTC_8x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
+ if (p === RGBA_ASTC_8x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
+ if (p === RGBA_ASTC_10x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
+ if (p === RGBA_ASTC_10x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
+ if (p === RGBA_ASTC_10x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
+ if (p === RGBA_ASTC_10x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
+ if (p === RGBA_ASTC_12x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
+ if (p === RGBA_ASTC_12x12_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
} else {
return null;
}
- }
+ } // BPTC
+
if (p === RGBA_BPTC_Format) {
extension = extensions.get('EXT_texture_compression_bptc');
if (extension !== null) {
- // TODO Complete?
- return p;
+ if (p === RGBA_BPTC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
} else {
return null;
}
- }
+ } //
+
if (p === UnsignedInt248Type) {
if (isWebGL2) return gl.UNSIGNED_INT_24_8;
@@ -18130,7 +18213,7 @@
}
const projectionlayerInit = {
- colorFormat: attributes.alpha || isMultisample ? gl.RGBA8 : gl.RGB8,
+ colorFormat: renderer.outputEncoding === sRGBEncoding ? gl.SRGB8_ALPHA8 : gl.RGBA8,
depthFormat: glDepthFormat,
scaleFactor: framebufferScaleFactor
};
@@ -18152,7 +18235,7 @@
});
} else {
newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
- format: attributes.alpha ? RGBAFormat : RGBFormat,
+ format: RGBAFormat,
type: UnsignedByteType,
depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
stencilBuffer: attributes.stencil,
@@ -18160,8 +18243,10 @@
encoding: renderer.outputEncoding
});
}
- } // Set foveation to maximum.
+ }
+ newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
+ // Set foveation to maximum.
this.setFoveation(1.0);
referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
@@ -19032,9 +19117,7 @@
const _scissor = new Vector4(0, 0, _width, _height);
- let _scissorTest = false; //
-
- const _currentDrawBuffers = []; // frustum
+ let _scissorTest = false; // frustum
const _frustum = new Frustum(); // clipping
@@ -19077,7 +19160,7 @@
try {
const contextAttributes = {
- alpha: _alpha,
+ alpha: true,
depth: _depth,
stencil: _stencil,
antialias: _antialias,
@@ -19138,7 +19221,6 @@
extensions.init(capabilities);
utils = new WebGLUtils(_gl, extensions, capabilities);
state = new WebGLState(_gl, extensions, capabilities);
- _currentDrawBuffers[0] = _gl.BACK;
info = new WebGLInfo(_gl);
properties = new WebGLProperties();
textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
@@ -19154,7 +19236,7 @@
materials = new WebGLMaterials(properties);
renderLists = new WebGLRenderLists();
renderStates = new WebGLRenderStates(extensions, capabilities);
- background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
+ background = new WebGLBackground(_this, cubemaps, state, objects, _alpha, _premultipliedAlpha);
shadowMap = new WebGLShadowMap(_this, objects, capabilities);
bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
@@ -19357,7 +19439,9 @@
_isContextLost = true;
}
- function onContextRestore() {
+ function
+ /* event */
+ onContextRestore() {
console.log('THREE.WebGLRenderer: Context Restored.');
_isContextLost = false;
const infoAutoReset = info.autoReset;
@@ -19896,7 +19980,7 @@
textures.resetTextureUnits();
const fog = scene.fog;
const environment = material.isMeshStandardMaterial ? scene.environment : null;
- const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
+ const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding;
const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent;
@@ -20200,42 +20284,7 @@
const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) {
- let needsUpdate = false;
-
- if (renderTarget) {
- if (renderTarget.isWebGLMultipleRenderTargets) {
- const textures = renderTarget.texture;
-
- if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
- for (let i = 0, il = textures.length; i < il; i++) {
- _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
- }
-
- _currentDrawBuffers.length = textures.length;
- needsUpdate = true;
- }
- } else {
- if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
- _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
- _currentDrawBuffers.length = 1;
- needsUpdate = true;
- }
- }
- } else {
- if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
- _currentDrawBuffers[0] = _gl.BACK;
- _currentDrawBuffers.length = 1;
- needsUpdate = true;
- }
- }
-
- if (needsUpdate) {
- if (capabilities.isWebGL2) {
- _gl.drawBuffers(_currentDrawBuffers);
- } else {
- extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
- }
- }
+ state.drawBuffers(renderTarget, framebuffer);
}
state.viewport(_currentViewport);
@@ -22037,7 +22086,6 @@
class VideoTexture extends Texture {
constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
- this.format = format !== undefined ? format : RGBFormat;
this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
this.generateMipmaps = false;
@@ -25355,7 +25403,7 @@
const d = base + 1; // faces
indices.push(a, b, d);
- indices.push(b, c, d);
+ indices.push(c, d, b);
}
} // build geometry
@@ -28379,7 +28427,10 @@
headers: new Headers(this.requestHeader),
credentials: this.withCredentials ? 'include' : 'same-origin' // An abort controller could be added within a future PR
- }); // start the fetch
+ }); // record states ( avoid data race )
+
+ const mimeType = this.mimeType;
+ const responseType = this.responseType; // start the fetch
fetch(req).then(response => {
if (response.status === 200 || response.status === 0) {
@@ -28437,7 +28488,7 @@
throw Error(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`);
}
}).then(response => {
- switch (this.responseType) {
+ switch (responseType) {
case 'arraybuffer':
return response.arrayBuffer();
@@ -28447,14 +28498,24 @@
case 'document':
return response.text().then(text => {
const parser = new DOMParser();
- return parser.parseFromString(text, this.mimeType);
+ return parser.parseFromString(text, mimeType);
});
case 'json':
return response.json();
default:
+ if (mimeType === undefined) {
return response.text();
+ } else {
+ // sniff encoding
+ const re = /charset="?([^;"\s]*)"?/i;
+ const exec = re.exec(mimeType);
+ const label = exec && exec[1] ? exec[1].toLowerCase() : undefined;
+ const decoder = new TextDecoder(label);
+ return response.arrayBuffer().then(ab => decoder.decode(ab));
+ }
+
}
}).then(data => {
// Add to cache only on HTTP success, so that we do not cache
@@ -29504,12 +29565,12 @@
if (json.side !== undefined) material.side = json.side;
if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
if (json.opacity !== undefined) material.opacity = json.opacity;
- if (json.format !== undefined) material.format = json.format;
if (json.transparent !== undefined) material.transparent = json.transparent;
if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
if (json.depthTest !== undefined) material.depthTest = json.depthTest;
if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
+ if (json.alphaWrite !== undefined) material.alphaWrite = json.alphaWrite;
if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
@@ -32845,6 +32906,7 @@
let binding = bindingsByName[trackName];
if (binding !== undefined) {
+ ++binding.referenceCount;
bindings[i] = binding;
} else {
binding = bindings[i];
@@ -35076,10 +35138,14 @@
};
Loader.Handlers = {
- add: function () {
+ add: function
+ /* regex, loader */
+ () {
console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
},
- get: function () {
+ get: function
+ /* file */
+ () {
console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
}
};
@@ -35167,7 +35233,9 @@
return vector.applyMatrix3(this);
};
- Matrix3.prototype.multiplyVector3Array = function () {
+ Matrix3.prototype.multiplyVector3Array = function
+ /* a */
+ () {
console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
};
@@ -35176,7 +35244,9 @@
return attribute.applyMatrix3(this);
};
- Matrix3.prototype.applyToVector3Array = function () {
+ Matrix3.prototype.applyToVector3Array = function
+ /* array, offset, length */
+ () {
console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
};
@@ -35220,7 +35290,9 @@
return vector.applyMatrix4(this);
};
- Matrix4.prototype.multiplyVector3Array = function () {
+ Matrix4.prototype.multiplyVector3Array = function
+ /* a */
+ () {
console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
};
@@ -35259,7 +35331,9 @@
return attribute.applyMatrix4(this);
};
- Matrix4.prototype.applyToVector3Array = function () {
+ Matrix4.prototype.applyToVector3Array = function
+ /* array, offset, length */
+ () {
console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
};
@@ -35592,7 +35666,9 @@
console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
return this.usage === DynamicDrawUsage;
},
- set: function () {
+ set: function
+ /* value */
+ () {
console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
this.setUsage(DynamicDrawUsage);
}
@@ -35605,9 +35681,13 @@
return this;
};
- BufferAttribute.prototype.copyIndicesArray = function () {
+ BufferAttribute.prototype.copyIndicesArray = function
+ /* indices */
+ () {
console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
- }, BufferAttribute.prototype.setArray = function () {
+ }, BufferAttribute.prototype.setArray = function
+ /* array */
+ () {
console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
}; //
@@ -35682,7 +35762,9 @@
return this;
};
- InterleavedBuffer.prototype.setArray = function () {
+ InterleavedBuffer.prototype.setArray = function
+ /* array */
+ () {
console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
}; //
@@ -35916,7 +35998,9 @@
console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
return undefined;
},
- set: function () {
+ set: function
+ /* value */
+ () {
console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
}
},
@@ -35976,7 +36060,9 @@
console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
return undefined;
},
- set: function () {
+ set: function
+ /* cullFace */
+ () {
console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
}
},
@@ -36171,13 +36257,19 @@
} //
const SceneUtils = {
- createMultiMaterialObject: function () {
+ createMultiMaterialObject: function
+ /* geometry, materials */
+ () {
console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
},
- detach: function () {
+ detach: function
+ /* child, parent, scene */
+ () {
console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
},
- attach: function () {
+ attach: function
+ /* child, scene, parent */
+ () {
console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
}
}; //
@@ -36537,8 +36629,6 @@
exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
- exports.RGBFormat = RGBFormat;
- exports.RGBIntegerFormat = RGBIntegerFormat;
exports.RGB_ETC1_Format = RGB_ETC1_Format;
exports.RGB_ETC2_Format = RGB_ETC2_Format;
exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
@@ -36558,20 +36648,6 @@
exports.ReverseSubtractEquation = ReverseSubtractEquation;
exports.RingBufferGeometry = RingGeometry;
exports.RingGeometry = RingGeometry;
- exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
- exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
- exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
- exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
- exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
- exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
- exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
- exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
- exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
- exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
- exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
- exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
- exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
- exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
exports.Scene = Scene;
exports.SceneUtils = SceneUtils;
exports.ShaderChunk = ShaderChunk;
@@ -36645,7 +36721,6 @@
exports.UnsignedIntType = UnsignedIntType;
exports.UnsignedShort4444Type = UnsignedShort4444Type;
exports.UnsignedShort5551Type = UnsignedShort5551Type;
- exports.UnsignedShort565Type = UnsignedShort565Type;
exports.UnsignedShortType = UnsignedShortType;
exports.VSMShadowMap = VSMShadowMap;
exports.Vector2 = Vector2;
@@ -36671,6 +36746,7 @@
exports.ZeroFactor = ZeroFactor;
exports.ZeroSlopeEnding = ZeroSlopeEnding;
exports.ZeroStencilOp = ZeroStencilOp;
+ exports._SRGBAFormat = _SRGBAFormat;
exports.sRGBEncoding = sRGBEncoding;
Object.defineProperty(exports, '__esModule', { value: true });

build/three.min.js

@@ -1,6 +1,6 @@
/**
* @license
- * Copyright 2010-2021 Three.js Authors
+ * Copyright 2010-2022 Three.js Authors
* SPDX-License-Identifier: MIT
*/
-!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).THREE={})}(this,(function(t){"use strict";const e="136",n=100,i=300,r=301,s=302,a=303,o=304,l=306,c=307,h=1e3,u=1001,d=1002,p=1003,m=1004,f=1005,g=1006,v=1007,y=1008,x=1009,_=1012,b=1014,M=1015,w=1016,S=1020,T=1022,E=1023,A=1026,L=1027,R=33776,C=33777,P=33778,D=33779,I=35840,N=35841,z=35842,B=35843,F=37492,O=37496,U=2300,H=2301,G=2302,k=2400,V=2401,W=2402,j=2500,q=2501,X=3e3,J=3001,Y=7680,Z=35044,Q=35048,K="300 es";class ${addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[t]&&(n[t]=[]),-1===n[t].indexOf(e)&&n[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[t]&&-1!==n[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const n=this._listeners[t];if(void 0!==n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const n=e.slice(0);for(let e=0,i=n.length;e<i;e++)n[e].call(this,t);t.target=null}}}const tt=[];for(let t=0;t<256;t++)tt[t]=(t<16?"0":"")+t.toString(16);let et=1234567;const nt=Math.PI/180,it=180/Math.PI;function rt(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(tt[255&t]+tt[t>>8&255]+tt[t>>16&255]+tt[t>>24&255]+"-"+tt[255&e]+tt[e>>8&255]+"-"+tt[e>>16&15|64]+tt[e>>24&255]+"-"+tt[63&n|128]+tt[n>>8&255]+"-"+tt[n>>16&255]+tt[n>>24&255]+tt[255&i]+tt[i>>8&255]+tt[i>>16&255]+tt[i>>24&255]).toUpperCase()}function st(t,e,n){return Math.max(e,Math.min(n,t))}function at(t,e){return(t%e+e)%e}function ot(t,e,n){return(1-n)*t+n*e}function lt(t){return 0==(t&t-1)&&0!==t}function ct(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function ht(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}var ut=Object.freeze({__proto__:null,DEG2RAD:nt,RAD2DEG:it,generateUUID:rt,clamp:st,euclideanModulo:at,mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},inverseLerp:function(t,e,n){return t!==e?(n-t)/(e-t):0},lerp:ot,damp:function(t,e,n,i){return ot(t,e,1-Math.exp(-n*i))},pingpong:function(t,e=1){return e-Math.abs(at(t,2*e)-e)},smoothstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*(3-2*t)},smootherstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},seededRandom:function(t){return void 0!==t&&(et=t%2147483647),et=16807*et%2147483647,(et-1)/2147483646},degToRad:function(t){return t*nt},radToDeg:function(t){return t*it},isPowerOfTwo:lt,ceilPowerOfTwo:ct,floorPowerOfTwo:ht,setQuaternionFromProperEuler:function(t,e,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),c=s((e+i)/2),h=a((e+i)/2),u=s((e-i)/2),d=a((e-i)/2),p=s((i-e)/2),m=a((i-e)/2);switch(r){case"XYX":t.set(o*h,l*u,l*d,o*c);break;case"YZY":t.set(l*d,o*h,l*u,o*c);break;case"ZXZ":t.set(l*u,l*d,o*h,o*c);break;case"XZX":t.set(o*h,l*m,l*p,o*c);break;case"YXY":t.set(l*p,o*h,l*m,o*c);break;case"ZYZ":t.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}});class dt{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,e){return void 0!==e?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(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,e){return void 0!==e?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(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=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}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=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(){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}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,n){return void 0!==n&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute()."),this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const n=Math.cos(e),i=Math.sin(e),r=this.x-t.x,s=this.y-t.y;return this.x=r*n-s*i+t.x,this.y=r*i+s*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}dt.prototype.isVector2=!0;class pt{constructor(){this.elements=[1,0,0,0,1,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}set(t,e,n,i,r,s,a,o,l){const c=this.elements;return c[0]=t,c[1]=i,c[2]=a,c[3]=e,c[4]=r,c[5]=o,c[6]=n,c[7]=s,c[8]=l,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,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],c=n[4],h=n[7],u=n[2],d=n[5],p=n[8],m=i[0],f=i[3],g=i[6],v=i[1],y=i[4],x=i[7],_=i[2],b=i[5],M=i[8];return r[0]=s*m+a*v+o*_,r[3]=s*f+a*y+o*b,r[6]=s*g+a*x+o*M,r[1]=l*m+c*v+h*_,r[4]=l*f+c*y+h*b,r[7]=l*g+c*x+h*M,r[2]=u*m+d*v+p*_,r[5]=u*f+d*y+p*b,r[8]=u*g+d*x+p*M,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],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8];return e*s*c-e*a*l-n*r*c+n*a*o+i*r*l-i*s*o}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=c*s-a*l,u=a*o-c*r,d=l*r-s*o,p=e*h+n*u+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=h*m,t[1]=(i*l-c*n)*m,t[2]=(a*n-i*s)*m,t[3]=u*m,t[4]=(c*e-i*o)*m,t[5]=(i*r-a*e)*m,t[6]=d*m,t[7]=(n*o-l*e)*m,t[8]=(s*e-n*r)*m,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,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+t,-i*l,i*o,-i*(-l*s+o*a)+a+e,0,0,1),this}scale(t,e){const n=this.elements;return n[0]*=t,n[3]*=t,n[6]*=t,n[1]*=e,n[4]*=e,n[7]*=e,this}rotate(t){const e=Math.cos(t),n=Math.sin(t),i=this.elements,r=i[0],s=i[3],a=i[6],o=i[1],l=i[4],c=i[7];return i[0]=e*r+n*o,i[3]=e*s+n*l,i[6]=e*a+n*c,i[1]=-n*r+e*o,i[4]=-n*s+e*l,i[7]=-n*a+e*c,this}translate(t,e){const n=this.elements;return n[0]+=t*n[2],n[3]+=t*n[5],n[6]+=t*n[8],n[1]+=e*n[2],n[4]+=e*n[5],n[7]+=e*n[8],this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<9;t++)if(e[t]!==n[t])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)}}function mt(t){if(0===t.length)return-1/0;let e=t[0];for(let n=1,i=t.length;n<i;++n)t[n]>e&&(e=t[n]);return e}pt.prototype.isMatrix3=!0;const ft={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function gt(t,e){return new ft[t](e)}function vt(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}let yt;class xt{static getDataURL(t){if(/^data:/i.test(t.src))return t.src;if("undefined"==typeof HTMLCanvasElement)return t.src;let e;if(t instanceof HTMLCanvasElement)e=t;else{void 0===yt&&(yt=vt("canvas")),yt.width=t.width,yt.height=t.height;const n=yt.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),e=yt}return e.width>2048||e.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",t),e.toDataURL("image/jpeg",.6)):e.toDataURL("image/png")}}let _t=0;class bt extends ${constructor(t=bt.DEFAULT_IMAGE,e=bt.DEFAULT_MAPPING,n=1001,i=1001,r=1006,s=1008,a=1023,o=1009,l=1,c=3e3){super(),Object.defineProperty(this,"id",{value:_t++}),this.uuid=rt(),this.name="",this.image=t,this.mipmaps=[],this.mapping=e,this.wrapS=n,this.wrapT=i,this.magFilter=r,this.minFilter=s,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new dt(0,0),this.repeat=new dt(1,1),this.center=new dt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new pt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.encoding=c,this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return(new this.constructor).copy(this)}copy(t){return this.name=t.name,this.image=t.image,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,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.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.encoding=t.encoding,this.userData=JSON.parse(JSON.stringify(t.userData)),this}toJSON(t){const e=void 0===t||"string"==typeof t;if(!e&&void 0!==t.textures[this.uuid])return t.textures[this.uuid];const n={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,type:this.type,encoding:this.encoding,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};if(void 0!==this.image){const i=this.image;if(void 0===i.uuid&&(i.uuid=rt()),!e&&void 0===t.images[i.uuid]){let e;if(Array.isArray(i)){e=[];for(let t=0,n=i.length;t<n;t++)i[t].isDataTexture?e.push(Mt(i[t].image)):e.push(Mt(i[t]))}else e=Mt(i);t.images[i.uuid]={uuid:i.uuid,url:e}}n.image=i.uuid}return"{}"!==JSON.stringify(this.userData)&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==i)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case h:t.x=t.x-Math.floor(t.x);break;case u:t.x=t.x<0?0:1;break;case d:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case h:t.y=t.y-Math.floor(t.y);break;case u:t.y=t.y<0?0:1;break;case d:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&this.version++}}function Mt(t){return"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap?xt.getDataURL(t):t.data?{data:Array.prototype.slice.call(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}bt.DEFAULT_IMAGE=void 0,bt.DEFAULT_MAPPING=i,bt.prototype.isTexture=!0;class wt{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=void 0!==t.w?t.w:1,this}add(t,e){return void 0!==e?(console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(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,e){return void 0!==e?(console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(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,r=this.w,s=t.elements;return this.x=s[0]*e+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*e+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*e+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*e+s[7]*n+s[11]*i+s[15]*r,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,r;const s=.01,a=.1,o=t.elements,l=o[0],c=o[4],h=o[8],u=o[1],d=o[5],p=o[9],m=o[2],f=o[6],g=o[10];if(Math.abs(c-u)<s&&Math.abs(h-m)<s&&Math.abs(p-f)<s){if(Math.abs(c+u)<a&&Math.abs(h+m)<a&&Math.abs(p+f)<a&&Math.abs(l+d+g-3)<a)return this.set(1,0,0,0),this;e=Math.PI;const t=(l+1)/2,o=(d+1)/2,v=(g+1)/2,y=(c+u)/4,x=(h+m)/4,_=(p+f)/4;return t>o&&t>v?t<s?(n=0,i=.707106781,r=.707106781):(n=Math.sqrt(t),i=y/n,r=x/n):o>v?o<s?(n=.707106781,i=0,r=.707106781):(i=Math.sqrt(o),n=y/i,r=_/i):v<s?(n=.707106781,i=.707106781,r=0):(r=Math.sqrt(v),n=x/r,i=_/r),this.set(n,i,r,e),this}let v=Math.sqrt((f-p)*(f-p)+(h-m)*(h-m)+(u-c)*(u-c));return Math.abs(v)<.001&&(v=1),this.x=(f-p)/v,this.y=(h-m)/v,this.z=(u-c)/v,this.w=Math.acos((l+d+g-1)/2),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=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}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=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(){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,n){return void 0!==n&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute()."),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}}wt.prototype.isVector4=!0;class St extends ${constructor(t,e,n={}){super(),this.width=t,this.height=e,this.depth=1,this.scissor=new wt(0,0,t,e),this.scissorTest=!1,this.viewport=new wt(0,0,t,e),this.texture=new bt(void 0,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.encoding),this.texture.isRenderTargetTexture=!0,this.texture.image={width:t,height:e,depth:1},this.texture.generateMipmaps=void 0!==n.generateMipmaps&&n.generateMipmaps,this.texture.internalFormat=void 0!==n.internalFormat?n.internalFormat:null,this.texture.minFilter=void 0!==n.minFilter?n.minFilter:g,this.depthBuffer=void 0===n.depthBuffer||n.depthBuffer,this.stencilBuffer=void 0!==n.stencilBuffer&&n.stencilBuffer,this.depthTexture=void 0!==n.depthTexture?n.depthTexture:null}setTexture(t){t.image={width:this.width,height:this.height,depth:this.depth},this.texture=t}setSize(t,e,n=1){this.width===t&&this.height===e&&this.depth===n||(this.width=t,this.height=e,this.depth=n,this.texture.image.width=t,this.texture.image.height=e,this.texture.image.depth=n,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){return this.width=t.width,this.height=t.height,this.depth=t.depth,this.viewport.copy(t.viewport),this.texture=t.texture.clone(),this.texture.image={...this.texture.image},this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,this.depthTexture=t.depthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}St.prototype.isWebGLRenderTarget=!0;class Tt extends St{constructor(t,e,n){super(t,e);const i=this.texture;this.texture=[];for(let t=0;t<n;t++)this.texture[t]=i.clone()}setSize(t,e,n=1){if(this.width!==t||this.height!==e||this.depth!==n){this.width=t,this.height=e,this.depth=n;for(let i=0,r=this.texture.length;i<r;i++)this.texture[i].image.width=t,this.texture[i].image.height=e,this.texture[i].image.depth=n;this.dispose()}return this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e),this}copy(t){this.dispose(),this.width=t.width,this.height=t.height,this.depth=t.depth,this.viewport.set(0,0,this.width,this.height),this.scissor.set(0,0,this.width,this.height),this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,this.depthTexture=t.depthTexture,this.texture.length=0;for(let e=0,n=t.texture.length;e<n;e++)this.texture[e]=t.texture[e].clone();return this}}Tt.prototype.isWebGLMultipleRenderTargets=!0;class Et extends St{constructor(t,e,n={}){super(t,e,n),this.samples=4,this.ignoreDepthForMultisampleCopy=void 0===n.ignoreDepth||n.ignoreDepth,this.useRenderToTexture=void 0!==n.useRenderToTexture&&n.useRenderToTexture,this.useRenderbuffer=!1===this.useRenderToTexture}copy(t){return super.copy.call(this,t),this.samples=t.samples,this.useRenderToTexture=t.useRenderToTexture,this.useRenderbuffer=t.useRenderbuffer,this}}Et.prototype.isWebGLMultisampleRenderTarget=!0;class At{constructor(t=0,e=0,n=0,i=1){this._x=t,this._y=e,this._z=n,this._w=i}static slerp(t,e,n,i){return console.warn("THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead."),n.slerpQuaternions(t,e,i)}static slerpFlat(t,e,n,i,r,s,a){let o=n[i+0],l=n[i+1],c=n[i+2],h=n[i+3];const u=r[s+0],d=r[s+1],p=r[s+2],m=r[s+3];if(0===a)return t[e+0]=o,t[e+1]=l,t[e+2]=c,void(t[e+3]=h);if(1===a)return t[e+0]=u,t[e+1]=d,t[e+2]=p,void(t[e+3]=m);if(h!==m||o!==u||l!==d||c!==p){let t=1-a;const e=o*u+l*d+c*p+h*m,n=e>=0?1:-1,i=1-e*e;if(i>Number.EPSILON){const r=Math.sqrt(i),s=Math.atan2(r,e*n);t=Math.sin(t*s)/r,a=Math.sin(a*s)/r}const r=a*n;if(o=o*t+u*r,l=l*t+d*r,c=c*t+p*r,h=h*t+m*r,t===1-a){const t=1/Math.sqrt(o*o+l*l+c*c+h*h);o*=t,l*=t,c*=t,h*=t}}t[e]=o,t[e+1]=l,t[e+2]=c,t[e+3]=h}static multiplyQuaternionsFlat(t,e,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],c=n[i+3],h=r[s],u=r[s+1],d=r[s+2],p=r[s+3];return t[e]=a*p+c*h+o*d-l*u,t[e+1]=o*p+c*u+l*h-a*d,t[e+2]=l*p+c*d+a*u-o*h,t[e+3]=c*p-a*h-o*u-l*d,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){if(!t||!t.isEuler)throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");const n=t._x,i=t._y,r=t._z,s=t._order,a=Math.cos,o=Math.sin,l=a(n/2),c=a(i/2),h=a(r/2),u=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"YXZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"ZXY":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"ZYX":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"YZX":this._x=u*c*h+l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h-u*d*p;break;case"XZY":this._x=u*c*h-l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h+u*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!1!==e&&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],r=e[8],s=e[1],a=e[5],o=e[9],l=e[2],c=e[6],h=e[10],u=n+a+h;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(c-o)*t,this._y=(r-l)*t,this._z=(s-i)*t}else if(n>a&&n>h){const t=2*Math.sqrt(1+n-a-h);this._w=(c-o)/t,this._x=.25*t,this._y=(i+s)/t,this._z=(r+l)/t}else if(a>h){const t=2*Math.sqrt(1+a-n-h);this._w=(r-l)/t,this._x=(i+s)/t,this._y=.25*t,this._z=(o+c)/t}else{const t=2*Math.sqrt(1+h-n-a);this._w=(s-i)/t,this._x=(r+l)/t,this._y=(o+c)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return n<Number.EPSILON?(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(st(this.dot(t),-1,1)))}rotateTowards(t,e){const n=this.angleTo(t);if(0===n)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 0===t?(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,e){return void 0!==e?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const n=t._x,i=t._y,r=t._z,s=t._w,a=e._x,o=e._y,l=e._z,c=e._w;return this._x=n*c+s*a+i*l-r*o,this._y=i*c+s*o+r*a-n*l,this._z=r*c+s*l+n*o-i*a,this._w=s*c-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const n=this._x,i=this._y,r=this._z,s=this._w;let a=s*t._w+n*t._x+i*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=s,this._x=n,this._y=i,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const t=1-e;return this._w=t*s+e*this._w,this._x=t*n+e*this._x,this._y=t*i+e*this._y,this._z=t*r+e*this._z,this.normalize(),this._onChangeCallback(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),h=Math.sin((1-e)*c)/l,u=Math.sin(e*c)/l;return this._w=s*h+this._w*u,this._x=n*h+this._x*u,this._y=i*h+this._y*u,this._z=r*h+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,n){this.copy(t).slerp(e,n)}random(){const t=Math.random(),e=Math.sqrt(1-t),n=Math.sqrt(t),i=2*Math.PI*Math.random(),r=2*Math.PI*Math.random();return this.set(e*Math.cos(i),n*Math.sin(r),n*Math.cos(r),e*Math.sin(i))}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}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}}At.prototype.isQuaternion=!0;class Lt{constructor(t=0,e=0,n=0){this.x=t,this.y=e,this.z=n}set(t,e,n){return void 0===n&&(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,e){return void 0!==e?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(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,e){return void 0!==e?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(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,e){return void 0!==e?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(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 t&&t.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),this.applyQuaternion(Ct.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Ct.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*i,this.y=r[1]*e+r[4]*n+r[7]*i,this.z=r[2]*e+r[5]*n+r[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=t.elements,s=1/(r[3]*e+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*e+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*e+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(t){const e=this.x,n=this.y,i=this.z,r=t.x,s=t.y,a=t.z,o=t.w,l=o*e+s*i-a*n,c=o*n+a*e-r*i,h=o*i+r*n-s*e,u=-r*e-s*n-a*i;return this.x=l*o+u*-r+c*-a-h*-s,this.y=c*o+u*-s+h*-r-l*-a,this.z=h*o+u*-a+l*-s-c*-r,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,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*i,this.y=r[1]*e+r[5]*n+r[9]*i,this.z=r[2]*e+r[6]*n+r[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=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}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=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(){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,e){return void 0!==e?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e)):this.crossVectors(this,t)}crossVectors(t,e){const n=t.x,i=t.y,r=t.z,s=e.x,a=e.y,o=e.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Rt.copy(this).projectOnVector(t),this.sub(Rt)}reflect(t){return this.sub(Rt.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(st(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,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}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,n){return void 0!==n&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute()."),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=2*(Math.random()-.5),e=Math.random()*Math.PI*2,n=Math.sqrt(1-t**2);return this.x=n*Math.cos(e),this.y=n*Math.sin(e),this.z=t,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}Lt.prototype.isVector3=!0;const Rt=new Lt,Ct=new At;class Pt{constructor(t=new Lt(1/0,1/0,1/0),e=new Lt(-1/0,-1/0,-1/0)){this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){let e=1/0,n=1/0,i=1/0,r=-1/0,s=-1/0,a=-1/0;for(let o=0,l=t.length;o<l;o+=3){const l=t[o],c=t[o+1],h=t[o+2];l<e&&(e=l),c<n&&(n=c),h<i&&(i=h),l>r&&(r=l),c>s&&(s=c),h>a&&(a=h)}return this.min.set(e,n,i),this.max.set(r,s,a),this}setFromBufferAttribute(t){let e=1/0,n=1/0,i=1/0,r=-1/0,s=-1/0,a=-1/0;for(let o=0,l=t.count;o<l;o++){const l=t.getX(o),c=t.getY(o),h=t.getZ(o);l<e&&(e=l),c<n&&(n=c),h<i&&(i=h),l>r&&(r=l),c>s&&(s=c),h>a&&(a=h)}return this.min.set(e,n,i),this.max.set(r,s,a),this}setFromPoints(t){this.makeEmpty();for(let e=0,n=t.length;e<n;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const n=It.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(n),this.max.copy(t).add(n),this}setFromObject(t){return this.makeEmpty(),this.expandByObject(t)}clone(){return(new this.constructor).copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(t){return this.isEmpty()?t.set(0,0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}expandByObject(t){t.updateWorldMatrix(!1,!1);const e=t.geometry;void 0!==e&&(null===e.boundingBox&&e.computeBoundingBox(),Nt.copy(e.boundingBox),Nt.applyMatrix4(t.matrixWorld),this.union(Nt));const n=t.children;for(let t=0,e=n.length;t<e;t++)this.expandByObject(n[t]);return this}containsPoint(t){return!(t.x<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,It),It.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(Gt),kt.subVectors(this.max,Gt),zt.subVectors(t.a,Gt),Bt.subVectors(t.b,Gt),Ft.subVectors(t.c,Gt),Ot.subVectors(Bt,zt),Ut.subVectors(Ft,Bt),Ht.subVectors(zt,Ft);let e=[0,-Ot.z,Ot.y,0,-Ut.z,Ut.y,0,-Ht.z,Ht.y,Ot.z,0,-Ot.x,Ut.z,0,-Ut.x,Ht.z,0,-Ht.x,-Ot.y,Ot.x,0,-Ut.y,Ut.x,0,-Ht.y,Ht.x,0];return!!jt(e,zt,Bt,Ft,kt)&&(e=[1,0,0,0,1,0,0,0,1],!!jt(e,zt,Bt,Ft,kt)&&(Vt.crossVectors(Ot,Ut),e=[Vt.x,Vt.y,Vt.z],jt(e,zt,Bt,Ft,kt)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return It.copy(t).clamp(this.min,this.max).sub(t).length()}getBoundingSphere(t){return this.getCenter(t.center),t.radius=.5*this.getSize(It).length(),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()||(Dt[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Dt[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Dt[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Dt[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Dt[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Dt[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Dt[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Dt[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Dt)),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)}}Pt.prototype.isBox3=!0;const Dt=[new Lt,new Lt,new Lt,new Lt,new Lt,new Lt,new Lt,new Lt],It=new Lt,Nt=new Pt,zt=new Lt,Bt=new Lt,Ft=new Lt,Ot=new Lt,Ut=new Lt,Ht=new Lt,Gt=new Lt,kt=new Lt,Vt=new Lt,Wt=new Lt;function jt(t,e,n,i,r){for(let s=0,a=t.length-3;s<=a;s+=3){Wt.fromArray(t,s);const a=r.x*Math.abs(Wt.x)+r.y*Math.abs(Wt.y)+r.z*Math.abs(Wt.z),o=e.dot(Wt),l=n.dot(Wt),c=i.dot(Wt);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const qt=new Pt,Xt=new Lt,Jt=new Lt,Yt=new Lt;class Zt{constructor(t=new Lt,e=-1){this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const n=this.center;void 0!==e?n.copy(e):qt.setFromPoints(t).getCenter(n);let i=0;for(let e=0,r=t.length;e<r;e++)i=Math.max(i,n.distanceToSquared(t[e]));return this.radius=Math.sqrt(i),this}copy(t){return this.center.copy(t.center),this.radius=t.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(t){return t.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(t){return t.distanceTo(this.center)-this.radius}intersectsSphere(t){const e=this.radius+t.radius;return t.center.distanceToSquared(this.center)<=e*e}intersectsBox(t){return t.intersectsSphere(this)}intersectsPlane(t){return Math.abs(t.distanceToPoint(this.center))<=this.radius}clampPoint(t,e){const n=this.center.distanceToSquared(t);return e.copy(t),n>this.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){Yt.subVectors(t,this.center);const e=Yt.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),n=.5*(t-this.radius);this.center.add(Yt.multiplyScalar(n/t)),this.radius+=n}return this}union(t){return!0===this.center.equals(t.center)?Jt.set(0,0,1).multiplyScalar(t.radius):Jt.subVectors(t.center,this.center).normalize().multiplyScalar(t.radius),this.expandByPoint(Xt.copy(t.center).add(Jt)),this.expandByPoint(Xt.copy(t.center).sub(Jt)),this}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Qt=new Lt,Kt=new Lt,$t=new Lt,te=new Lt,ee=new Lt,ne=new Lt,ie=new Lt;class re{constructor(t=new Lt,e=new Lt(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.direction).multiplyScalar(t).add(this.origin)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,Qt)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.direction).multiplyScalar(n).add(this.origin)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=Qt.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(Qt.copy(this.direction).multiplyScalar(e).add(this.origin),Qt.distanceToSquared(t))}distanceSqToSegment(t,e,n,i){Kt.copy(t).add(e).multiplyScalar(.5),$t.copy(e).sub(t).normalize(),te.copy(this.origin).sub(Kt);const r=.5*t.distanceTo(e),s=-this.direction.dot($t),a=te.dot(this.direction),o=-te.dot($t),l=te.lengthSq(),c=Math.abs(1-s*s);let h,u,d,p;if(c>0)if(h=s*o-a,u=s*a-o,p=r*c,h>=0)if(u>=-p)if(u<=p){const t=1/c;h*=t,u*=t,d=h*(h+s*u+2*a)+u*(s*h+u+2*o)+l}else u=r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u=-r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u<=-p?(h=Math.max(0,-(-s*r+a)),u=h>0?-r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l):u<=p?(h=0,u=Math.min(Math.max(-r,-o),r),d=u*(u+2*o)+l):(h=Math.max(0,-(s*r+a)),u=h>0?r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l);else u=s>0?-r:r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;return n&&n.copy(this.direction).multiplyScalar(h).add(this.origin),i&&i.copy($t).multiplyScalar(u).add(Kt),d}intersectSphere(t,e){Qt.subVectors(t.center,this.origin);const n=Qt.dot(this.direction),i=Qt.dot(Qt)-n*n,r=t.radius*t.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return a<0&&o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?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 null===n?null:this.at(n,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);if(0===e)return!0;return t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,i,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,u=this.origin;return l>=0?(n=(t.min.x-u.x)*l,i=(t.max.x-u.x)*l):(n=(t.max.x-u.x)*l,i=(t.min.x-u.x)*l),c>=0?(r=(t.min.y-u.y)*c,s=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,s=(t.min.y-u.y)*c),n>s||r>i?null:((r>n||n!=n)&&(n=r),(s<i||i!=i)&&(i=s),h>=0?(a=(t.min.z-u.z)*h,o=(t.max.z-u.z)*h):(a=(t.max.z-u.z)*h,o=(t.min.z-u.z)*h),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o<i||i!=i)&&(i=o),i<0?null:this.at(n>=0?n:i,e)))}intersectsBox(t){return null!==this.intersectBox(t,Qt)}intersectTriangle(t,e,n,i,r){ee.subVectors(e,t),ne.subVectors(n,t),ie.crossVectors(ee,ne);let s,a=this.direction.dot(ie);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}te.subVectors(this.origin,t);const o=s*this.direction.dot(ne.crossVectors(te,ne));if(o<0)return null;const l=s*this.direction.dot(ee.cross(te));if(l<0)return null;if(o+l>a)return null;const c=-s*te.dot(ie);return c<0?null:this.at(c/a,r)}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 se{constructor(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){const g=this.elements;return g[0]=t,g[4]=e,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=h,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=f,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new se).fromArray(this.elements)}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],e[9]=n[9],e[10]=n[10],e[11]=n[11],e[12]=n[12],e[13]=n[13],e[14]=n[14],e[15]=n[15],this}copyPosition(t){const e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,n=t.elements,i=1/ae.setFromMatrixColumn(t,0).length(),r=1/ae.setFromMatrixColumn(t,1).length(),s=1/ae.setFromMatrixColumn(t,2).length();return e[0]=n[0]*i,e[1]=n[1]*i,e[2]=n[2]*i,e[3]=0,e[4]=n[4]*r,e[5]=n[5]*r,e[6]=n[6]*r,e[7]=0,e[8]=n[8]*s,e[9]=n[9]*s,e[10]=n[10]*s,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){t&&t.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");const e=this.elements,n=t.x,i=t.y,r=t.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),c=Math.cos(r),h=Math.sin(r);if("XYZ"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=-o*h,e[8]=l,e[1]=n+i*l,e[5]=t-r*l,e[9]=-a*o,e[2]=r-t*l,e[6]=i+n*l,e[10]=s*o}else if("YXZ"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t+r*a,e[4]=i*a-n,e[8]=s*l,e[1]=s*h,e[5]=s*c,e[9]=-a,e[2]=n*a-i,e[6]=r+t*a,e[10]=s*o}else if("ZXY"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t-r*a,e[4]=-s*h,e[8]=i+n*a,e[1]=n+i*a,e[5]=s*c,e[9]=r-t*a,e[2]=-s*l,e[6]=a,e[10]=s*o}else if("ZYX"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=i*l-n,e[8]=t*l+r,e[1]=o*h,e[5]=r*l+t,e[9]=n*l-i,e[2]=-l,e[6]=a*o,e[10]=s*o}else if("YZX"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=r-t*h,e[8]=i*h+n,e[1]=h,e[5]=s*c,e[9]=-a*c,e[2]=-l*c,e[6]=n*h+i,e[10]=t-r*h}else if("XZY"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=-h,e[8]=l*c,e[1]=t*h+r,e[5]=s*c,e[9]=n*h-i,e[2]=i*h-n,e[6]=a*c,e[10]=r*h+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(le,t,ce)}lookAt(t,e,n){const i=this.elements;return de.subVectors(t,e),0===de.lengthSq()&&(de.z=1),de.normalize(),he.crossVectors(n,de),0===he.lengthSq()&&(1===Math.abs(n.z)?de.x+=1e-4:de.z+=1e-4,de.normalize(),he.crossVectors(n,de)),he.normalize(),ue.crossVectors(de,he),i[0]=he.x,i[4]=ue.x,i[8]=de.x,i[1]=he.y,i[5]=ue.y,i[9]=de.y,i[2]=he.z,i[6]=ue.z,i[10]=de.z,this}multiply(t,e){return void 0!==e?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],c=n[1],h=n[5],u=n[9],d=n[13],p=n[2],m=n[6],f=n[10],g=n[14],v=n[3],y=n[7],x=n[11],_=n[15],b=i[0],M=i[4],w=i[8],S=i[12],T=i[1],E=i[5],A=i[9],L=i[13],R=i[2],C=i[6],P=i[10],D=i[14],I=i[3],N=i[7],z=i[11],B=i[15];return r[0]=s*b+a*T+o*R+l*I,r[4]=s*M+a*E+o*C+l*N,r[8]=s*w+a*A+o*P+l*z,r[12]=s*S+a*L+o*D+l*B,r[1]=c*b+h*T+u*R+d*I,r[5]=c*M+h*E+u*C+d*N,r[9]=c*w+h*A+u*P+d*z,r[13]=c*S+h*L+u*D+d*B,r[2]=p*b+m*T+f*R+g*I,r[6]=p*M+m*E+f*C+g*N,r[10]=p*w+m*A+f*P+g*z,r[14]=p*S+m*L+f*D+g*B,r[3]=v*b+y*T+x*R+_*I,r[7]=v*M+y*E+x*C+_*N,r[11]=v*w+y*A+x*P+_*z,r[15]=v*S+y*L+x*D+_*B,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[4],i=t[8],r=t[12],s=t[1],a=t[5],o=t[9],l=t[13],c=t[2],h=t[6],u=t[10],d=t[14];return t[3]*(+r*o*h-i*l*h-r*a*u+n*l*u+i*a*d-n*o*d)+t[7]*(+e*o*d-e*l*u+r*s*u-i*s*d+i*l*c-r*o*c)+t[11]*(+e*l*h-e*a*d-r*s*h+n*s*d+r*a*c-n*l*c)+t[15]*(-i*a*c-e*o*h+e*a*u+i*s*h-n*s*u+n*o*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,n){const i=this.elements;return t.isVector3?(i[12]=t.x,i[13]=t.y,i[14]=t.z):(i[12]=t,i[13]=e,i[14]=n),this}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=t[9],u=t[10],d=t[11],p=t[12],m=t[13],f=t[14],g=t[15],v=h*f*l-m*u*l+m*o*d-a*f*d-h*o*g+a*u*g,y=p*u*l-c*f*l-p*o*d+s*f*d+c*o*g-s*u*g,x=c*m*l-p*h*l+p*a*d-s*m*d-c*a*g+s*h*g,_=p*h*o-c*m*o-p*a*u+s*m*u+c*a*f-s*h*f,b=e*v+n*y+i*x+r*_;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/b;return t[0]=v*M,t[1]=(m*u*r-h*f*r-m*i*d+n*f*d+h*i*g-n*u*g)*M,t[2]=(a*f*r-m*o*r+m*i*l-n*f*l-a*i*g+n*o*g)*M,t[3]=(h*o*r-a*u*r-h*i*l+n*u*l+a*i*d-n*o*d)*M,t[4]=y*M,t[5]=(c*f*r-p*u*r+p*i*d-e*f*d-c*i*g+e*u*g)*M,t[6]=(p*o*r-s*f*r-p*i*l+e*f*l+s*i*g-e*o*g)*M,t[7]=(s*u*r-c*o*r+c*i*l-e*u*l-s*i*d+e*o*d)*M,t[8]=x*M,t[9]=(p*h*r-c*m*r-p*n*d+e*m*d+c*n*g-e*h*g)*M,t[10]=(s*m*r-p*a*r+p*n*l-e*m*l-s*n*g+e*a*g)*M,t[11]=(c*a*r-s*h*r-c*n*l+e*h*l+s*n*d-e*a*d)*M,t[12]=_*M,t[13]=(c*m*i-p*h*i+p*n*u-e*m*u-c*n*f+e*h*f)*M,t[14]=(p*a*i-s*m*i-p*n*o+e*m*o+s*n*f-e*a*f)*M,t[15]=(s*h*i-c*a*i+c*n*o-e*h*o-s*n*u+e*a*u)*M,this}scale(t){const e=this.elements,n=t.x,i=t.y,r=t.z;return e[0]*=n,e[4]*=i,e[8]*=r,e[1]*=n,e[5]*=i,e[9]*=r,e[2]*=n,e[6]*=i,e[10]*=r,e[3]*=n,e[7]*=i,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],n=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],i=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,n,i))}makeTranslation(t,e,n){return this.set(1,0,0,t,0,1,0,e,0,0,1,n,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),n=Math.sin(t);return this.set(1,0,0,0,0,e,-n,0,0,n,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,0,n,0,0,1,0,0,-n,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,0,n,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const n=Math.cos(e),i=Math.sin(e),r=1-n,s=t.x,a=t.y,o=t.z,l=r*s,c=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,c*a+n,c*o-i*s,0,l*o-i*a,c*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(t,e,n){return this.set(t,0,0,0,0,e,0,0,0,0,n,0,0,0,0,1),this}makeShear(t,e,n,i,r,s){return this.set(1,n,r,0,t,1,s,0,e,i,1,0,0,0,0,1),this}compose(t,e,n){const i=this.elements,r=e._x,s=e._y,a=e._z,o=e._w,l=r+r,c=s+s,h=a+a,u=r*l,d=r*c,p=r*h,m=s*c,f=s*h,g=a*h,v=o*l,y=o*c,x=o*h,_=n.x,b=n.y,M=n.z;return i[0]=(1-(m+g))*_,i[1]=(d+x)*_,i[2]=(p-y)*_,i[3]=0,i[4]=(d-x)*b,i[5]=(1-(u+g))*b,i[6]=(f+v)*b,i[7]=0,i[8]=(p+y)*M,i[9]=(f-v)*M,i[10]=(1-(u+m))*M,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}decompose(t,e,n){const i=this.elements;let r=ae.set(i[0],i[1],i[2]).length();const s=ae.set(i[4],i[5],i[6]).length(),a=ae.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),t.x=i[12],t.y=i[13],t.z=i[14],oe.copy(this);const o=1/r,l=1/s,c=1/a;return oe.elements[0]*=o,oe.elements[1]*=o,oe.elements[2]*=o,oe.elements[4]*=l,oe.elements[5]*=l,oe.elements[6]*=l,oe.elements[8]*=c,oe.elements[9]*=c,oe.elements[10]*=c,e.setFromRotationMatrix(oe),n.x=r,n.y=s,n.z=a,this}makePerspective(t,e,n,i,r,s){void 0===s&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");const a=this.elements,o=2*r/(e-t),l=2*r/(n-i),c=(e+t)/(e-t),h=(n+i)/(n-i),u=-(s+r)/(s-r),d=-2*s*r/(s-r);return a[0]=o,a[4]=0,a[8]=c,a[12]=0,a[1]=0,a[5]=l,a[9]=h,a[13]=0,a[2]=0,a[6]=0,a[10]=u,a[14]=d,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(t,e,n,i,r,s){const a=this.elements,o=1/(e-t),l=1/(n-i),c=1/(s-r),h=(e+t)*o,u=(n+i)*l,d=(s+r)*c;return a[0]=2*o,a[4]=0,a[8]=0,a[12]=-h,a[1]=0,a[5]=2*l,a[9]=0,a[13]=-u,a[2]=0,a[6]=0,a[10]=-2*c,a[14]=-d,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<16;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<16;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[e+9]=n[9],t[e+10]=n[10],t[e+11]=n[11],t[e+12]=n[12],t[e+13]=n[13],t[e+14]=n[14],t[e+15]=n[15],t}}se.prototype.isMatrix4=!0;const ae=new Lt,oe=new se,le=new Lt(0,0,0),ce=new Lt(1,1,1),he=new Lt,ue=new Lt,de=new Lt,pe=new se,me=new At;class fe{constructor(t=0,e=0,n=0,i=fe.DefaultOrder){this._x=t,this._y=e,this._z=n,this._order=i}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 order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,n,i=this._order){return this._x=t,this._y=e,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,n=!0){const i=t.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],h=i[2],u=i[6],d=i[10];switch(e){case"XYZ":this._y=Math.asin(st(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-st(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,r),this._z=0);break;case"ZXY":this._x=Math.asin(st(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-st(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(st(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-st(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===n&&this._onChangeCallback(),this}setFromQuaternion(t,e,n){return pe.makeRotationFromQuaternion(t),this.setFromRotationMatrix(pe,e,n)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return me.setFromEuler(this),this.setFromQuaternion(me,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[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._order,t}toVector3(t){return t?t.set(this._x,this._y,this._z):new Lt(this._x,this._y,this._z)}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}}fe.prototype.isEuler=!0,fe.DefaultOrder="XYZ",fe.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"];class ge{constructor(){this.mask=1}set(t){this.mask=(1<<t|0)>>>0}enable(t){this.mask|=1<<t|0}enableAll(){this.mask=-1}toggle(t){this.mask^=1<<t|0}disable(t){this.mask&=~(1<<t|0)}disableAll(){this.mask=0}test(t){return 0!=(this.mask&t.mask)}isEnabled(t){return 0!=(this.mask&(1<<t|0))}}let ve=0;const ye=new Lt,xe=new At,_e=new se,be=new Lt,Me=new Lt,we=new Lt,Se=new At,Te=new Lt(1,0,0),Ee=new Lt(0,1,0),Ae=new Lt(0,0,1),Le={type:"added"},Re={type:"removed"};class Ce extends ${constructor(){super(),Object.defineProperty(this,"id",{value:ve++}),this.uuid=rt(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Ce.DefaultUp.clone();const t=new Lt,e=new fe,n=new At,i=new Lt(1,1,1);e._onChange((function(){n.setFromEuler(e,!1)})),n._onChange((function(){e.setFromQuaternion(n,void 0,!1)})),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new se},normalMatrix:{value:new pt}}),this.matrix=new se,this.matrixWorld=new se,this.matrixAutoUpdate=Ce.DefaultMatrixAutoUpdate,this.matrixWorldNeedsUpdate=!1,this.layers=new ge,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeRender(){}onAfterRender(){}applyMatrix4(t){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(t),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(t){return this.quaternion.premultiply(t),this}setRotationFromAxisAngle(t,e){this.quaternion.setFromAxisAngle(t,e)}setRotationFromEuler(t){this.quaternion.setFromEuler(t,!0)}setRotationFromMatrix(t){this.quaternion.setFromRotationMatrix(t)}setRotationFromQuaternion(t){this.quaternion.copy(t)}rotateOnAxis(t,e){return xe.setFromAxisAngle(t,e),this.quaternion.multiply(xe),this}rotateOnWorldAxis(t,e){return xe.setFromAxisAngle(t,e),this.quaternion.premultiply(xe),this}rotateX(t){return this.rotateOnAxis(Te,t)}rotateY(t){return this.rotateOnAxis(Ee,t)}rotateZ(t){return this.rotateOnAxis(Ae,t)}translateOnAxis(t,e){return ye.copy(t).applyQuaternion(this.quaternion),this.position.add(ye.multiplyScalar(e)),this}translateX(t){return this.translateOnAxis(Te,t)}translateY(t){return this.translateOnAxis(Ee,t)}translateZ(t){return this.translateOnAxis(Ae,t)}localToWorld(t){return t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return t.applyMatrix4(_e.copy(this.matrixWorld).invert())}lookAt(t,e,n){t.isVector3?be.copy(t):be.set(t,e,n);const i=this.parent;this.updateWorldMatrix(!0,!1),Me.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?_e.lookAt(Me,be,this.up):_e.lookAt(be,Me,this.up),this.quaternion.setFromRotationMatrix(_e),i&&(_e.extractRotation(i.matrixWorld),xe.setFromRotationMatrix(_e),this.quaternion.premultiply(xe.invert()))}add(t){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return t===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",t),this):(t&&t.isObject3D?(null!==t.parent&&t.parent.remove(t),t.parent=this,this.children.push(t),t.dispatchEvent(Le)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",t),this)}remove(t){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.remove(arguments[t]);return this}const e=this.children.indexOf(t);return-1!==e&&(t.parent=null,this.children.splice(e,1),t.dispatchEvent(Re)),this}removeFromParent(){const t=this.parent;return null!==t&&t.remove(this),this}clear(){for(let t=0;t<this.children.length;t++){const e=this.children[t];e.parent=null,e.dispatchEvent(Re)}return this.children.length=0,this}attach(t){return this.updateWorldMatrix(!0,!1),_e.copy(this.matrixWorld).invert(),null!==t.parent&&(t.parent.updateWorldMatrix(!0,!1),_e.multiply(t.parent.matrixWorld)),t.applyMatrix4(_e),this.add(t),t.updateWorldMatrix(!1,!0),this}getObjectById(t){return this.getObjectByProperty("id",t)}getObjectByName(t){return this.getObjectByProperty("name",t)}getObjectByProperty(t,e){if(this[t]===e)return this;for(let n=0,i=this.children.length;n<i;n++){const i=this.children[n].getObjectByProperty(t,e);if(void 0!==i)return i}}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Me,t,we),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Me,Se,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(e[8],e[9],e[10]).normalize()}raycast(){}traverse(t){t(this);const e=this.children;for(let n=0,i=e.length;n<i;n++)e[n].traverse(t)}traverseVisible(t){if(!1===this.visible)return;t(this);const e=this.children;for(let n=0,i=e.length;n<i;n++)e[n].traverseVisible(t)}traverseAncestors(t){const e=this.parent;null!==e&&(t(e),e.traverseAncestors(t))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||t)&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,t=!0);const e=this.children;for(let n=0,i=e.length;n<i;n++)e[n].updateMatrixWorld(t)}updateWorldMatrix(t,e){const n=this.parent;if(!0===t&&null!==n&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),!0===e){const t=this.children;for(let e=0,n=t.length;e<n;e++)t[e].updateWorldMatrix(!1,!0)}}toJSON(t){const e=void 0===t||"string"==typeof t,n={};e&&(t={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{}},n.metadata={version:4.5,type:"Object",generator:"Object3D.toJSON"});const i={};function r(e,n){return void 0===e[n.uuid]&&(e[n.uuid]=n.toJSON(t)),n.uuid}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),!0===this.castShadow&&(i.castShadow=!0),!0===this.receiveShadow&&(i.receiveShadow=!0),!1===this.visible&&(i.visible=!1),!1===this.frustumCulled&&(i.frustumCulled=!1),0!==this.renderOrder&&(i.renderOrder=this.renderOrder),"{}"!==JSON.stringify(this.userData)&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),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&&(i.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(t.geometries,this.geometry);const e=this.geometry.parameters;if(void 0!==e&&void 0!==e.shapes){const n=e.shapes;if(Array.isArray(n))for(let e=0,i=n.length;e<i;e++){const i=n[e];r(t.shapes,i)}else r(t.shapes,n)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(r(t.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const e=[];for(let n=0,i=this.material.length;n<i;n++)e.push(r(t.materials,this.material[n]));i.material=e}else i.material=r(t.materials,this.material);if(this.children.length>0){i.children=[];for(let e=0;e<this.children.length;e++)i.children.push(this.children[e].toJSON(t).object)}if(this.animations.length>0){i.animations=[];for(let e=0;e<this.animations.length;e++){const n=this.animations[e];i.animations.push(r(t.animations,n))}}if(e){const e=s(t.geometries),i=s(t.materials),r=s(t.textures),a=s(t.images),o=s(t.shapes),l=s(t.skeletons),c=s(t.animations);e.length>0&&(n.geometries=e),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),c.length>0&&(n.animations=c)}return n.object=i,n;function s(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}}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.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,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.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;e<t.children.length;e++){const n=t.children[e];this.add(n.clone())}return this}}Ce.DefaultUp=new Lt(0,1,0),Ce.DefaultMatrixAutoUpdate=!0,Ce.prototype.isObject3D=!0;const Pe=new Lt,De=new Lt,Ie=new Lt,Ne=new Lt,ze=new Lt,Be=new Lt,Fe=new Lt,Oe=new Lt,Ue=new Lt,He=new Lt;class Ge{constructor(t=new Lt,e=new Lt,n=new Lt){this.a=t,this.b=e,this.c=n}static getNormal(t,e,n,i){i.subVectors(n,e),Pe.subVectors(t,e),i.cross(Pe);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(t,e,n,i,r){Pe.subVectors(i,e),De.subVectors(n,e),Ie.subVectors(t,e);const s=Pe.dot(Pe),a=Pe.dot(De),o=Pe.dot(Ie),l=De.dot(De),c=De.dot(Ie),h=s*l-a*a;if(0===h)return r.set(-2,-1,-1);const u=1/h,d=(l*o-a*c)*u,p=(s*c-a*o)*u;return r.set(1-d-p,p,d)}static containsPoint(t,e,n,i){return this.getBarycoord(t,e,n,i,Ne),Ne.x>=0&&Ne.y>=0&&Ne.x+Ne.y<=1}static getUV(t,e,n,i,r,s,a,o){return this.getBarycoord(t,e,n,i,Ne),o.set(0,0),o.addScaledVector(r,Ne.x),o.addScaledVector(s,Ne.y),o.addScaledVector(a,Ne.z),o}static isFrontFacing(t,e,n,i){return Pe.subVectors(n,e),De.subVectors(t,e),Pe.cross(De).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 Pe.subVectors(this.c,this.b),De.subVectors(this.a,this.b),.5*Pe.cross(De).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return Ge.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return Ge.getBarycoord(t,this.a,this.b,this.c,e)}getUV(t,e,n,i,r){return Ge.getUV(t,this.a,this.b,this.c,e,n,i,r)}containsPoint(t){return Ge.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return Ge.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const n=this.a,i=this.b,r=this.c;let s,a;ze.subVectors(i,n),Be.subVectors(r,n),Oe.subVectors(t,n);const o=ze.dot(Oe),l=Be.dot(Oe);if(o<=0&&l<=0)return e.copy(n);Ue.subVectors(t,i);const c=ze.dot(Ue),h=Be.dot(Ue);if(c>=0&&h<=c)return e.copy(i);const u=o*h-c*l;if(u<=0&&o>=0&&c<=0)return s=o/(o-c),e.copy(n).addScaledVector(ze,s);He.subVectors(t,r);const d=ze.dot(He),p=Be.dot(He);if(p>=0&&d<=p)return e.copy(r);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(n).addScaledVector(Be,a);const f=c*p-d*h;if(f<=0&&h-c>=0&&d-p>=0)return Fe.subVectors(r,i),a=(h-c)/(h-c+(d-p)),e.copy(i).addScaledVector(Fe,a);const g=1/(f+m+u);return s=m*g,a=u*g,e.copy(n).addScaledVector(ze,s).addScaledVector(Be,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}let ke=0;class Ve extends ${constructor(){super(),Object.defineProperty(this,"id",{value:ke++}),this.uuid=rt(),this.name="",this.type="Material",this.fog=!0,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.format=E,this.transparent=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=n,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Y,this.stencilZFail=Y,this.stencilZPass=Y,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(void 0!==t)for(const e in t){const n=t[e];if(void 0===n){console.warn("THREE.Material: '"+e+"' parameter is undefined.");continue}if("shading"===e){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===n;continue}const i=this[e];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[e]=n:console.warn("THREE."+this.type+": '"+e+"' is not a property of this material.")}}toJSON(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const n={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};function i(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(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.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,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).uuid),void 0!==this.attenuationDistance&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.format!==E&&(n.format=this.format),!0===this.transparent&&(n.transparent=this.transparent),n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.stencilWrite=this.stencilWrite,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaToCoverage&&(n.alphaToCoverage=this.alphaToCoverage),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=this.premultipliedAlpha),!0===this.wireframe&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=this.flatShading),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),"{}"!==JSON.stringify(this.userData)&&(n.userData=this.userData),e){const e=i(t.textures),r=i(t.images);e.length>0&&(n.textures=e),r.length>0&&(n.images=r)}return n}clone(){return(new this.constructor).copy(this)}copy(t){this.name=t.name,this.fog=t.fog,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.format=t.format,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.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(null!==e){const t=e.length;n=new Array(t);for(let i=0;i!==t;++i)n[i]=e[i].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.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,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){!0===t&&this.version++}}Ve.prototype.isMaterial=!0;const We={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},je={h:0,s:0,l:0},qe={h:0,s:0,l:0};function Xe(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+6*(e-t)*(2/3-n):t}function Je(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function Ye(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}class Ze{constructor(t,e,n){return void 0===e&&void 0===n?this.set(t):this.setRGB(t,e,n)}set(t){return t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t),this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,this}setRGB(t,e,n){return this.r=t,this.g=e,this.b=n,this}setHSL(t,e,n){if(t=at(t,1),e=st(e,0,1),n=st(n,0,1),0===e)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+e):n+e-n*e,r=2*n-i;this.r=Xe(r,i,t+1/3),this.g=Xe(r,i,t),this.b=Xe(r,i,t-1/3)}return this}setStyle(t){function e(e){void 0!==e&&parseFloat(e)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let n;if(n=/^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(t)){let t;const i=n[1],r=n[2];switch(i){case"rgb":case"rgba":if(t=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return this.r=Math.min(255,parseInt(t[1],10))/255,this.g=Math.min(255,parseInt(t[2],10))/255,this.b=Math.min(255,parseInt(t[3],10))/255,e(t[4]),this;if(t=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return this.r=Math.min(100,parseInt(t[1],10))/100,this.g=Math.min(100,parseInt(t[2],10))/100,this.b=Math.min(100,parseInt(t[3],10))/100,e(t[4]),this;break;case"hsl":case"hsla":if(t=/^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r)){const n=parseFloat(t[1])/360,i=parseInt(t[2],10)/100,r=parseInt(t[3],10)/100;return e(t[4]),this.setHSL(n,i,r)}}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(t)){const t=n[1],e=t.length;if(3===e)return this.r=parseInt(t.charAt(0)+t.charAt(0),16)/255,this.g=parseInt(t.charAt(1)+t.charAt(1),16)/255,this.b=parseInt(t.charAt(2)+t.charAt(2),16)/255,this;if(6===e)return this.r=parseInt(t.charAt(0)+t.charAt(1),16)/255,this.g=parseInt(t.charAt(2)+t.charAt(3),16)/255,this.b=parseInt(t.charAt(4)+t.charAt(5),16)/255,this}return t&&t.length>0?this.setColorName(t):this}setColorName(t){const e=We[t.toLowerCase()];return void 0!==e?this.setHex(e):console.warn("THREE.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=Je(t.r),this.g=Je(t.g),this.b=Je(t.b),this}copyLinearToSRGB(t){return this.r=Ye(t.r),this.g=Ye(t.g),this.b=Ye(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}getHSL(t){const e=this.r,n=this.g,i=this.b,r=Math.max(e,n,i),s=Math.min(e,n,i);let a,o;const l=(s+r)/2;if(s===r)a=0,o=0;else{const t=r-s;switch(o=l<=.5?t/(r+s):t/(2-r-s),r){case e:a=(n-i)/t+(n<i?6:0);break;case n:a=(i-e)/t+2;break;case i:a=(e-n)/t+4}a/=6}return t.h=a,t.s=o,t.l=l,t}getStyle(){return"rgb("+(255*this.r|0)+","+(255*this.g|0)+","+(255*this.b|0)+")"}offsetHSL(t,e,n){return this.getHSL(je),je.h+=t,je.s+=e,je.l+=n,this.setHSL(je.h,je.s,je.l),this}add(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this}addColors(t,e){return this.r=t.r+e.r,this.g=t.g+e.g,this.b=t.b+e.b,this}addScalar(t){return this.r+=t,this.g+=t,this.b+=t,this}sub(t){return this.r=Math.max(0,this.r-t.r),this.g=Math.max(0,this.g-t.g),this.b=Math.max(0,this.b-t.b),this}multiply(t){return this.r*=t.r,this.g*=t.g,this.b*=t.b,this}multiplyScalar(t){return this.r*=t,this.g*=t,this.b*=t,this}lerp(t,e){return this.r+=(t.r-this.r)*e,this.g+=(t.g-this.g)*e,this.b+=(t.b-this.b)*e,this}lerpColors(t,e,n){return this.r=t.r+(e.r-t.r)*n,this.g=t.g+(e.g-t.g)*n,this.b=t.b+(e.b-t.b)*n,this}lerpHSL(t,e){this.getHSL(je),t.getHSL(qe);const n=ot(je.h,qe.h,e),i=ot(je.s,qe.s,e),r=ot(je.l,qe.l,e);return this.setHSL(n,i,r),this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}fromArray(t,e=0){return this.r=t[e],this.g=t[e+1],this.b=t[e+2],this}toArray(t=[],e=0){return t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,t}fromBufferAttribute(t,e){return this.r=t.getX(e),this.g=t.getY(e),this.b=t.getZ(e),!0===t.normalized&&(this.r/=255,this.g/=255,this.b/=255),this}toJSON(){return this.getHex()}}Ze.NAMES=We,Ze.prototype.isColor=!0,Ze.prototype.r=1,Ze.prototype.g=1,Ze.prototype.b=1;class Qe extends Ve{constructor(t){super(),this.type="MeshBasicMaterial",this.color=new Ze(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.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",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.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}}Qe.prototype.isMeshBasicMaterial=!0;const Ke=new Lt,$e=new dt;class tn{constructor(t,e,n){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=!0===n,this.usage=Z,this.updateRange={offset:0,count:-1},this.version=0}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}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}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let i=0,r=this.itemSize;i<r;i++)this.array[t+i]=e.array[n+i];return this}copyArray(t){return this.array.set(t),this}copyColorsArray(t){const e=this.array;let n=0;for(let i=0,r=t.length;i<r;i++){let r=t[i];void 0===r&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",i),r=new Ze),e[n++]=r.r,e[n++]=r.g,e[n++]=r.b}return this}copyVector2sArray(t){const e=this.array;let n=0;for(let i=0,r=t.length;i<r;i++){let r=t[i];void 0===r&&(console.warn("THREE.BufferAttribute.copyVector2sArray(): vector is undefined",i),r=new dt),e[n++]=r.x,e[n++]=r.y}return this}copyVector3sArray(t){const e=this.array;let n=0;for(let i=0,r=t.length;i<r;i++){let r=t[i];void 0===r&&(console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",i),r=new Lt),e[n++]=r.x,e[n++]=r.y,e[n++]=r.z}return this}copyVector4sArray(t){const e=this.array;let n=0;for(let i=0,r=t.length;i<r;i++){let r=t[i];void 0===r&&(console.warn("THREE.BufferAttribute.copyVector4sArray(): vector is undefined",i),r=new wt),e[n++]=r.x,e[n++]=r.y,e[n++]=r.z,e[n++]=r.w}return this}applyMatrix3(t){if(2===this.itemSize)for(let e=0,n=this.count;e<n;e++)$e.fromBufferAttribute(this,e),$e.applyMatrix3(t),this.setXY(e,$e.x,$e.y);else if(3===this.itemSize)for(let e=0,n=this.count;e<n;e++)Ke.fromBufferAttribute(this,e),Ke.applyMatrix3(t),this.setXYZ(e,Ke.x,Ke.y,Ke.z);return this}applyMatrix4(t){for(let e=0,n=this.count;e<n;e++)Ke.x=this.getX(e),Ke.y=this.getY(e),Ke.z=this.getZ(e),Ke.applyMatrix4(t),this.setXYZ(e,Ke.x,Ke.y,Ke.z);return this}applyNormalMatrix(t){for(let e=0,n=this.count;e<n;e++)Ke.x=this.getX(e),Ke.y=this.getY(e),Ke.z=this.getZ(e),Ke.applyNormalMatrix(t),this.setXYZ(e,Ke.x,Ke.y,Ke.z);return this}transformDirection(t){for(let e=0,n=this.count;e<n;e++)Ke.x=this.getX(e),Ke.y=this.getY(e),Ke.z=this.getZ(e),Ke.transformDirection(t),this.setXYZ(e,Ke.x,Ke.y,Ke.z);return this}set(t,e=0){return this.array.set(t,e),this}getX(t){return this.array[t*this.itemSize]}setX(t,e){return this.array[t*this.itemSize]=e,this}getY(t){return this.array[t*this.itemSize+1]}setY(t,e){return this.array[t*this.itemSize+1]=e,this}getZ(t){return this.array[t*this.itemSize+2]}setZ(t,e){return this.array[t*this.itemSize+2]=e,this}getW(t){return this.array[t*this.itemSize+3]}setW(t,e){return this.array[t*this.itemSize+3]=e,this}setXY(t,e,n){return t*=this.itemSize,this.array[t+0]=e,this.array[t+1]=n,this}setXYZ(t,e,n,i){return t*=this.itemSize,this.array[t+0]=e,this.array[t+1]=n,this.array[t+2]=i,this}setXYZW(t,e,n,i,r){return t*=this.itemSize,this.array[t+0]=e,this.array[t+1]=n,this.array[t+2]=i,this.array[t+3]=r,this}onUpload(t){return this.onUploadCallback=t,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const t={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.prototype.slice.call(this.array),normalized:this.normalized};return""!==this.name&&(t.name=this.name),this.usage!==Z&&(t.usage=this.usage),0===this.updateRange.offset&&-1===this.updateRange.count||(t.updateRange=this.updateRange),t}}tn.prototype.isBufferAttribute=!0;class en extends tn{constructor(t,e,n){super(new Int8Array(t),e,n)}}class nn extends tn{constructor(t,e,n){super(new Uint8Array(t),e,n)}}class rn extends tn{constructor(t,e,n){super(new Uint8ClampedArray(t),e,n)}}class sn extends tn{constructor(t,e,n){super(new Int16Array(t),e,n)}}class an extends tn{constructor(t,e,n){super(new Uint16Array(t),e,n)}}class on extends tn{constructor(t,e,n){super(new Int32Array(t),e,n)}}class ln extends tn{constructor(t,e,n){super(new Uint32Array(t),e,n)}}class cn extends tn{constructor(t,e,n){super(new Uint16Array(t),e,n)}}cn.prototype.isFloat16BufferAttribute=!0;class hn extends tn{constructor(t,e,n){super(new Float32Array(t),e,n)}}class un extends tn{constructor(t,e,n){super(new Float64Array(t),e,n)}}let dn=0;const pn=new se,mn=new Ce,fn=new Lt,gn=new Pt,vn=new Pt,yn=new Lt;class xn extends ${constructor(){super(),Object.defineProperty(this,"id",{value:dn++}),this.uuid=rt(),this.name="",this.type="BufferGeometry",this.index=null,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(mt(t)>65535?ln:an)(t,1):this.index=t,this}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 void 0!==this.attributes[t]}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;void 0!==e&&(e.applyMatrix4(t),e.needsUpdate=!0);const n=this.attributes.normal;if(void 0!==n){const e=(new pt).getNormalMatrix(t);n.applyNormalMatrix(e),n.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(t),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(t){return pn.makeRotationFromQuaternion(t),this.applyMatrix4(pn),this}rotateX(t){return pn.makeRotationX(t),this.applyMatrix4(pn),this}rotateY(t){return pn.makeRotationY(t),this.applyMatrix4(pn),this}rotateZ(t){return pn.makeRotationZ(t),this.applyMatrix4(pn),this}translate(t,e,n){return pn.makeTranslation(t,e,n),this.applyMatrix4(pn),this}scale(t,e,n){return pn.makeScale(t,e,n),this.applyMatrix4(pn),this}lookAt(t){return mn.lookAt(t),mn.updateMatrix(),this.applyMatrix4(mn.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(fn).negate(),this.translate(fn.x,fn.y,fn.z),this}setFromPoints(t){const e=[];for(let n=0,i=t.length;n<i;n++){const i=t[n];e.push(i.x,i.y,i.z||0)}return this.setAttribute("position",new hn(e,3)),this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Pt);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)return console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".',this),void this.boundingBox.set(new Lt(-1/0,-1/0,-1/0),new Lt(1/0,1/0,1/0));if(void 0!==t){if(this.boundingBox.setFromBufferAttribute(t),e)for(let t=0,n=e.length;t<n;t++){const n=e[t];gn.setFromBufferAttribute(n),this.morphTargetsRelative?(yn.addVectors(this.boundingBox.min,gn.min),this.boundingBox.expandByPoint(yn),yn.addVectors(this.boundingBox.max,gn.max),this.boundingBox.expandByPoint(yn)):(this.boundingBox.expandByPoint(gn.min),this.boundingBox.expandByPoint(gn.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new Zt);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)return console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".',this),void this.boundingSphere.set(new Lt,1/0);if(t){const n=this.boundingSphere.center;if(gn.setFromBufferAttribute(t),e)for(let t=0,n=e.length;t<n;t++){const n=e[t];vn.setFromBufferAttribute(n),this.morphTargetsRelative?(yn.addVectors(gn.min,vn.min),gn.expandByPoint(yn),yn.addVectors(gn.max,vn.max),gn.expandByPoint(yn)):(gn.expandByPoint(vn.min),gn.expandByPoint(vn.max))}gn.getCenter(n);let i=0;for(let e=0,r=t.count;e<r;e++)yn.fromBufferAttribute(t,e),i=Math.max(i,n.distanceToSquared(yn));if(e)for(let r=0,s=e.length;r<s;r++){const s=e[r],a=this.morphTargetsRelative;for(let e=0,r=s.count;e<r;e++)yn.fromBufferAttribute(s,e),a&&(fn.fromBufferAttribute(t,e),yn.add(fn)),i=Math.max(i,n.distanceToSquared(yn))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const t=this.index,e=this.attributes;if(null===t||void 0===e.position||void 0===e.normal||void 0===e.uv)return void console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const n=t.array,i=e.position.array,r=e.normal.array,s=e.uv.array,a=i.length/3;void 0===e.tangent&&this.setAttribute("tangent",new tn(new Float32Array(4*a),4));const o=e.tangent.array,l=[],c=[];for(let t=0;t<a;t++)l[t]=new Lt,c[t]=new Lt;const h=new Lt,u=new Lt,d=new Lt,p=new dt,m=new dt,f=new dt,g=new Lt,v=new Lt;function y(t,e,n){h.fromArray(i,3*t),u.fromArray(i,3*e),d.fromArray(i,3*n),p.fromArray(s,2*t),m.fromArray(s,2*e),f.fromArray(s,2*n),u.sub(h),d.sub(h),m.sub(p),f.sub(p);const r=1/(m.x*f.y-f.x*m.y);isFinite(r)&&(g.copy(u).multiplyScalar(f.y).addScaledVector(d,-m.y).multiplyScalar(r),v.copy(d).multiplyScalar(m.x).addScaledVector(u,-f.x).multiplyScalar(r),l[t].add(g),l[e].add(g),l[n].add(g),c[t].add(v),c[e].add(v),c[n].add(v))}let x=this.groups;0===x.length&&(x=[{start:0,count:n.length}]);for(let t=0,e=x.length;t<e;++t){const e=x[t],i=e.start;for(let t=i,r=i+e.count;t<r;t+=3)y(n[t+0],n[t+1],n[t+2])}const _=new Lt,b=new Lt,M=new Lt,w=new Lt;function S(t){M.fromArray(r,3*t),w.copy(M);const e=l[t];_.copy(e),_.sub(M.multiplyScalar(M.dot(e))).normalize(),b.crossVectors(w,e);const n=b.dot(c[t])<0?-1:1;o[4*t]=_.x,o[4*t+1]=_.y,o[4*t+2]=_.z,o[4*t+3]=n}for(let t=0,e=x.length;t<e;++t){const e=x[t],i=e.start;for(let t=i,r=i+e.count;t<r;t+=3)S(n[t+0]),S(n[t+1]),S(n[t+2])}}computeVertexNormals(){const t=this.index,e=this.getAttribute("position");if(void 0!==e){let n=this.getAttribute("normal");if(void 0===n)n=new tn(new Float32Array(3*e.count),3),this.setAttribute("normal",n);else for(let t=0,e=n.count;t<e;t++)n.setXYZ(t,0,0,0);const i=new Lt,r=new Lt,s=new Lt,a=new Lt,o=new Lt,l=new Lt,c=new Lt,h=new Lt;if(t)for(let u=0,d=t.count;u<d;u+=3){const d=t.getX(u+0),p=t.getX(u+1),m=t.getX(u+2);i.fromBufferAttribute(e,d),r.fromBufferAttribute(e,p),s.fromBufferAttribute(e,m),c.subVectors(s,r),h.subVectors(i,r),c.cross(h),a.fromBufferAttribute(n,d),o.fromBufferAttribute(n,p),l.fromBufferAttribute(n,m),a.add(c),o.add(c),l.add(c),n.setXYZ(d,a.x,a.y,a.z),n.setXYZ(p,o.x,o.y,o.z),n.setXYZ(m,l.x,l.y,l.z)}else for(let t=0,a=e.count;t<a;t+=3)i.fromBufferAttribute(e,t+0),r.fromBufferAttribute(e,t+1),s.fromBufferAttribute(e,t+2),c.subVectors(s,r),h.subVectors(i,r),c.cross(h),n.setXYZ(t+0,c.x,c.y,c.z),n.setXYZ(t+1,c.x,c.y,c.z),n.setXYZ(t+2,c.x,c.y,c.z);this.normalizeNormals(),n.needsUpdate=!0}}merge(t,e){if(!t||!t.isBufferGeometry)return void console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",t);void 0===e&&(e=0,console.warn("THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge."));const n=this.attributes;for(const i in n){if(void 0===t.attributes[i])continue;const r=n[i].array,s=t.attributes[i],a=s.array,o=s.itemSize*e,l=Math.min(a.length,r.length-o);for(let t=0,e=o;t<l;t++,e++)r[e]=a[t]}return this}normalizeNormals(){const t=this.attributes.normal;for(let e=0,n=t.count;e<n;e++)yn.fromBufferAttribute(t,e),yn.normalize(),t.setXYZ(e,yn.x,yn.y,yn.z)}toNonIndexed(){function t(t,e){const n=t.array,i=t.itemSize,r=t.normalized,s=new n.constructor(e.length*i);let a=0,o=0;for(let r=0,l=e.length;r<l;r++){a=t.isInterleavedBufferAttribute?e[r]*t.data.stride+t.offset:e[r]*i;for(let t=0;t<i;t++)s[o++]=n[a++]}return new tn(s,i,r)}if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const e=new xn,n=this.index.array,i=this.attributes;for(const r in i){const s=t(i[r],n);e.setAttribute(r,s)}const r=this.morphAttributes;for(const i in r){const s=[],a=r[i];for(let e=0,i=a.length;e<i;e++){const i=t(a[e],n);s.push(i)}e.morphAttributes[i]=s}e.morphTargetsRelative=this.morphTargetsRelative;const s=this.groups;for(let t=0,n=s.length;t<n;t++){const n=s[t];e.addGroup(n.start,n.count,n.materialIndex)}return e}toJSON(){const t={metadata:{version:4.5,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(t.uuid=this.uuid,t.type=this.type,""!==this.name&&(t.name=this.name),Object.keys(this.userData).length>0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const n in e)void 0!==e[n]&&(t[n]=e[n]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const n=this.attributes;for(const e in n){const i=n[e];t.data.attributes[e]=i.toJSON(t.data)}const i={};let r=!1;for(const e in this.morphAttributes){const n=this.morphAttributes[e],s=[];for(let e=0,i=n.length;e<i;e++){const i=n[e];s.push(i.toJSON(t.data))}s.length>0&&(i[e]=s,r=!0)}r&&(t.data.morphAttributes=i,t.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(t.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),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;null!==n&&this.setIndex(n.clone(e));const i=t.attributes;for(const t in i){const n=i[t];this.setAttribute(t,n.clone(e))}const r=t.morphAttributes;for(const t in r){const n=[],i=r[t];for(let t=0,r=i.length;t<r;t++)n.push(i[t].clone(e));this.morphAttributes[t]=n}this.morphTargetsRelative=t.morphTargetsRelative;const s=t.groups;for(let t=0,e=s.length;t<e;t++){const e=s[t];this.addGroup(e.start,e.count,e.materialIndex)}const a=t.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=t.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=t.drawRange.start,this.drawRange.count=t.drawRange.count,this.userData=t.userData,void 0!==t.parameters&&(this.parameters=Object.assign({},t.parameters)),this}dispose(){this.dispatchEvent({type:"dispose"})}}xn.prototype.isBufferGeometry=!0;const _n=new se,bn=new re,Mn=new Zt,wn=new Lt,Sn=new Lt,Tn=new Lt,En=new Lt,An=new Lt,Ln=new Lt,Rn=new Lt,Cn=new Lt,Pn=new Lt,Dn=new dt,In=new dt,Nn=new dt,zn=new Lt,Bn=new Lt;class Fn extends Ce{constructor(t=new xn,e=new Qe){super(),this.type="Mesh",this.geometry=t,this.material=e,this.updateMorphTargets()}copy(t){return super.copy(t),void 0!==t.morphTargetInfluences&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),void 0!==t.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=t.material,this.geometry=t.geometry,this}updateMorphTargets(){const t=this.geometry;if(t.isBufferGeometry){const e=t.morphAttributes,n=Object.keys(e);if(n.length>0){const t=e[n[0]];if(void 0!==t){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,n=t.length;e<n;e++){const n=t[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[n]=e}}}}else{const e=t.morphTargets;void 0!==e&&e.length>0&&console.error("THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}}raycast(t,e){const n=this.geometry,i=this.material,r=this.matrixWorld;if(void 0===i)return;if(null===n.boundingSphere&&n.computeBoundingSphere(),Mn.copy(n.boundingSphere),Mn.applyMatrix4(r),!1===t.ray.intersectsSphere(Mn))return;if(_n.copy(r).invert(),bn.copy(t.ray).applyMatrix4(_n),null!==n.boundingBox&&!1===bn.intersectsBox(n.boundingBox))return;let s;if(n.isBufferGeometry){const r=n.index,a=n.attributes.position,o=n.morphAttributes.position,l=n.morphTargetsRelative,c=n.attributes.uv,h=n.attributes.uv2,u=n.groups,d=n.drawRange;if(null!==r)if(Array.isArray(i))for(let n=0,p=u.length;n<p;n++){const p=u[n],m=i[p.materialIndex];for(let n=Math.max(p.start,d.start),i=Math.min(r.count,Math.min(p.start+p.count,d.start+d.count));n<i;n+=3){const i=r.getX(n),u=r.getX(n+1),d=r.getX(n+2);s=On(this,m,t,bn,a,o,l,c,h,i,u,d),s&&(s.faceIndex=Math.floor(n/3),s.face.materialIndex=p.materialIndex,e.push(s))}}else{for(let n=Math.max(0,d.start),u=Math.min(r.count,d.start+d.count);n<u;n+=3){const u=r.getX(n),d=r.getX(n+1),p=r.getX(n+2);s=On(this,i,t,bn,a,o,l,c,h,u,d,p),s&&(s.faceIndex=Math.floor(n/3),e.push(s))}}else if(void 0!==a)if(Array.isArray(i))for(let n=0,r=u.length;n<r;n++){const r=u[n],p=i[r.materialIndex];for(let n=Math.max(r.start,d.start),i=Math.min(a.count,Math.min(r.start+r.count,d.start+d.count));n<i;n+=3){s=On(this,p,t,bn,a,o,l,c,h,n,n+1,n+2),s&&(s.faceIndex=Math.floor(n/3),s.face.materialIndex=r.materialIndex,e.push(s))}}else{for(let n=Math.max(0,d.start),r=Math.min(a.count,d.start+d.count);n<r;n+=3){s=On(this,i,t,bn,a,o,l,c,h,n,n+1,n+2),s&&(s.faceIndex=Math.floor(n/3),e.push(s))}}}else n.isGeometry&&console.error("THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}}function On(t,e,n,i,r,s,a,o,l,c,h,u){wn.fromBufferAttribute(r,c),Sn.fromBufferAttribute(r,h),Tn.fromBufferAttribute(r,u);const d=t.morphTargetInfluences;if(s&&d){Rn.set(0,0,0),Cn.set(0,0,0),Pn.set(0,0,0);for(let t=0,e=s.length;t<e;t++){const e=d[t],n=s[t];0!==e&&(En.fromBufferAttribute(n,c),An.fromBufferAttribute(n,h),Ln.fromBufferAttribute(n,u),a?(Rn.addScaledVector(En,e),Cn.addScaledVector(An,e),Pn.addScaledVector(Ln,e)):(Rn.addScaledVector(En.sub(wn),e),Cn.addScaledVector(An.sub(Sn),e),Pn.addScaledVector(Ln.sub(Tn),e)))}wn.add(Rn),Sn.add(Cn),Tn.add(Pn)}t.isSkinnedMesh&&(t.boneTransform(c,wn),t.boneTransform(h,Sn),t.boneTransform(u,Tn));const p=function(t,e,n,i,r,s,a,o){let l;if(l=1===e.side?i.intersectTriangle(a,s,r,!0,o):i.intersectTriangle(r,s,a,2!==e.side,o),null===l)return null;Bn.copy(o),Bn.applyMatrix4(t.matrixWorld);const c=n.ray.origin.distanceTo(Bn);return c<n.near||c>n.far?null:{distance:c,point:Bn.clone(),object:t}}(t,e,n,i,wn,Sn,Tn,zn);if(p){o&&(Dn.fromBufferAttribute(o,c),In.fromBufferAttribute(o,h),Nn.fromBufferAttribute(o,u),p.uv=Ge.getUV(zn,wn,Sn,Tn,Dn,In,Nn,new dt)),l&&(Dn.fromBufferAttribute(l,c),In.fromBufferAttribute(l,h),Nn.fromBufferAttribute(l,u),p.uv2=Ge.getUV(zn,wn,Sn,Tn,Dn,In,Nn,new dt));const t={a:c,b:h,c:u,normal:new Lt,materialIndex:0};Ge.getNormal(wn,Sn,Tn,t.normal),p.face=t}return p}Fn.prototype.isMesh=!0;class Un extends xn{constructor(t=1,e=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],h=[];let u=0,d=0;function p(t,e,n,i,r,s,p,m,f,g,v){const y=s/f,x=p/g,_=s/2,b=p/2,M=m/2,w=f+1,S=g+1;let T=0,E=0;const A=new Lt;for(let s=0;s<S;s++){const a=s*x-b;for(let o=0;o<w;o++){const u=o*y-_;A[t]=u*i,A[e]=a*r,A[n]=M,l.push(A.x,A.y,A.z),A[t]=0,A[e]=0,A[n]=m>0?1:-1,c.push(A.x,A.y,A.z),h.push(o/f),h.push(1-s/g),T+=1}}for(let t=0;t<g;t++)for(let e=0;e<f;e++){const n=u+e+w*t,i=u+e+w*(t+1),r=u+(e+1)+w*(t+1),s=u+(e+1)+w*t;o.push(n,i,s),o.push(i,r,s),E+=6}a.addGroup(d,E,v),d+=E,u+=T}p("z","y","x",-1,-1,n,e,t,s,r,0),p("z","y","x",1,-1,n,e,-t,s,r,1),p("x","z","y",1,1,t,n,e,i,s,2),p("x","z","y",1,-1,t,n,-e,i,s,3),p("x","y","z",1,-1,t,e,n,i,r,4),p("x","y","z",-1,-1,t,e,-n,i,r,5),this.setIndex(o),this.setAttribute("position",new hn(l,3)),this.setAttribute("normal",new hn(c,3)),this.setAttribute("uv",new hn(h,2))}static fromJSON(t){return new Un(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}}function Hn(t){const e={};for(const n in t){e[n]={};for(const i in t[n]){const r=t[n][i];r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)?e[n][i]=r.clone():Array.isArray(r)?e[n][i]=r.slice():e[n][i]=r}}return e}function Gn(t){const e={};for(let n=0;n<t.length;n++){const i=Hn(t[n]);for(const t in i)e[t]=i[t]}return e}const kn={clone:Hn,merge:Gn};class Vn extends Ve{constructor(t){super(),this.type="ShaderMaterial",this.defines={},this.uniforms={},this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.extensions={derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv2:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,void 0!==t&&(void 0!==t.attributes&&console.error("THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead."),this.setValues(t))}copy(t){return super.copy(t),this.fragmentShader=t.fragmentShader,this.vertexShader=t.vertexShader,this.uniforms=Hn(t.uniforms),this.defines=Object.assign({},t.defines),this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.lights=t.lights,this.clipping=t.clipping,this.extensions=Object.assign({},t.extensions),this.glslVersion=t.glslVersion,this}toJSON(t){const e=super.toJSON(t);e.glslVersion=this.glslVersion,e.uniforms={};for(const n in this.uniforms){const i=this.uniforms[n].value;i&&i.isTexture?e.uniforms[n]={type:"t",value:i.toJSON(t).uuid}:i&&i.isColor?e.uniforms[n]={type:"c",value:i.getHex()}:i&&i.isVector2?e.uniforms[n]={type:"v2",value:i.toArray()}:i&&i.isVector3?e.uniforms[n]={type:"v3",value:i.toArray()}:i&&i.isVector4?e.uniforms[n]={type:"v4",value:i.toArray()}:i&&i.isMatrix3?e.uniforms[n]={type:"m3",value:i.toArray()}:i&&i.isMatrix4?e.uniforms[n]={type:"m4",value:i.toArray()}:e.uniforms[n]={value:i}}Object.keys(this.defines).length>0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader;const n={};for(const t in this.extensions)!0===this.extensions[t]&&(n[t]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}}Vn.prototype.isShaderMaterial=!0;class Wn extends Ce{constructor(){super(),this.type="Camera",this.matrixWorldInverse=new se,this.projectionMatrix=new se,this.projectionMatrixInverse=new se}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(-e[8],-e[9],-e[10]).normalize()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}Wn.prototype.isCamera=!0;class jn extends Wn{constructor(t=50,e=1,n=.1,i=2e3){super(),this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*it*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*nt*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*it*Math.atan(Math.tan(.5*nt*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(t,e,n,i,r,s){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(.5*nt*this.fov)/this.zoom,n=2*e,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const t=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/t,e-=s.offsetY*n/a,i*=s.width/t,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,e,e-n,t,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}jn.prototype.isPerspectiveCamera=!0;const qn=90;class Xn extends Ce{constructor(t,e,n){if(super(),this.type="CubeCamera",!0!==n.isWebGLCubeRenderTarget)return void console.error("THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.");this.renderTarget=n;const i=new jn(qn,1,t,e);i.layers=this.layers,i.up.set(0,-1,0),i.lookAt(new Lt(1,0,0)),this.add(i);const r=new jn(qn,1,t,e);r.layers=this.layers,r.up.set(0,-1,0),r.lookAt(new Lt(-1,0,0)),this.add(r);const s=new jn(qn,1,t,e);s.layers=this.layers,s.up.set(0,0,1),s.lookAt(new Lt(0,1,0)),this.add(s);const a=new jn(qn,1,t,e);a.layers=this.layers,a.up.set(0,0,-1),a.lookAt(new Lt(0,-1,0)),this.add(a);const o=new jn(qn,1,t,e);o.layers=this.layers,o.up.set(0,-1,0),o.lookAt(new Lt(0,0,1)),this.add(o);const l=new jn(qn,1,t,e);l.layers=this.layers,l.up.set(0,-1,0),l.lookAt(new Lt(0,0,-1)),this.add(l)}update(t,e){null===this.parent&&this.updateMatrixWorld();const n=this.renderTarget,[i,r,s,a,o,l]=this.children,c=t.xr.enabled,h=t.getRenderTarget();t.xr.enabled=!1;const u=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,t.setRenderTarget(n,0),t.render(e,i),t.setRenderTarget(n,1),t.render(e,r),t.setRenderTarget(n,2),t.render(e,s),t.setRenderTarget(n,3),t.render(e,a),t.setRenderTarget(n,4),t.render(e,o),n.texture.generateMipmaps=u,t.setRenderTarget(n,5),t.render(e,l),t.setRenderTarget(h),t.xr.enabled=c}}class Jn extends bt{constructor(t,e,n,i,s,a,o,l,c,h){super(t=void 0!==t?t:[],e=void 0!==e?e:r,n,i,s,a,o,l,c,h),this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}Jn.prototype.isCubeTexture=!0;class Yn extends St{constructor(t,e,n){Number.isInteger(e)&&(console.warn("THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )"),e=n),super(t,t,e),e=e||{},this.texture=new Jn(void 0,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.encoding),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==e.generateMipmaps&&e.generateMipmaps,this.texture.minFilter=void 0!==e.minFilter?e.minFilter:g,this.texture._needsFlipEnvMap=!1}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.format=E,this.texture.encoding=e.encoding,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Un(5,5,5),r=new Vn({name:"CubemapFromEquirect",uniforms:Hn(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=e;const s=new Fn(i,r),a=e.minFilter;e.minFilter===y&&(e.minFilter=g);return new Xn(1,10,this).update(t,s),e.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(t,e,n,i){const r=t.getRenderTarget();for(let r=0;r<6;r++)t.setRenderTarget(this,r),t.clear(e,n,i);t.setRenderTarget(r)}}Yn.prototype.isWebGLCubeRenderTarget=!0;const Zn=new Lt,Qn=new Lt,Kn=new pt;class $n{constructor(t=new Lt(1,0,0),e=0){this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,n,i){return this.normal.set(t,e,n),this.constant=i,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,n){const i=Zn.subVectors(n,e).cross(Qn.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(i,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(this.normal).multiplyScalar(-this.distanceToPoint(t)).add(t)}intersectLine(t,e){const n=t.delta(Zn),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(t.start)?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:e.copy(n).multiplyScalar(r).add(t.start)}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||Kn.getNormalMatrix(t),i=this.coplanarPoint(Zn).applyMatrix4(t),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),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)}}$n.prototype.isPlane=!0;const ti=new Zt,ei=new Lt;class ni{constructor(t=new $n,e=new $n,n=new $n,i=new $n,r=new $n,s=new $n){this.planes=[t,e,n,i,r,s]}set(t,e,n,i,r,s){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(t){const e=this.planes;for(let n=0;n<6;n++)e[n].copy(t.planes[n]);return this}setFromProjectionMatrix(t){const e=this.planes,n=t.elements,i=n[0],r=n[1],s=n[2],a=n[3],o=n[4],l=n[5],c=n[6],h=n[7],u=n[8],d=n[9],p=n[10],m=n[11],f=n[12],g=n[13],v=n[14],y=n[15];return e[0].setComponents(a-i,h-o,m-u,y-f).normalize(),e[1].setComponents(a+i,h+o,m+u,y+f).normalize(),e[2].setComponents(a+r,h+l,m+d,y+g).normalize(),e[3].setComponents(a-r,h-l,m-d,y-g).normalize(),e[4].setComponents(a-s,h-c,m-p,y-v).normalize(),e[5].setComponents(a+s,h+c,m+p,y+v).normalize(),this}intersectsObject(t){const e=t.geometry;return null===e.boundingSphere&&e.computeBoundingSphere(),ti.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),this.intersectsSphere(ti)}intersectsSprite(t){return ti.center.set(0,0,0),ti.radius=.7071067811865476,ti.applyMatrix4(t.matrixWorld),this.intersectsSphere(ti)}intersectsSphere(t){const e=this.planes,n=t.center,i=-t.radius;for(let t=0;t<6;t++){if(e[t].distanceToPoint(n)<i)return!1}return!0}intersectsBox(t){const e=this.planes;for(let n=0;n<6;n++){const i=e[n];if(ei.x=i.normal.x>0?t.max.x:t.min.x,ei.y=i.normal.y>0?t.max.y:t.min.y,ei.z=i.normal.z>0?t.max.z:t.min.z,i.distanceToPoint(ei)<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)}}function ii(){let t=null,e=!1,n=null,i=null;function r(e,s){n(e,s),i=t.requestAnimationFrame(r)}return{start:function(){!0!==e&&null!==n&&(i=t.requestAnimationFrame(r),e=!0)},stop:function(){t.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(t){n=t},setContext:function(e){t=e}}}function ri(t,e){const n=e.isWebGL2,i=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),i.get(t)},remove:function(e){e.isInterleavedBufferAttribute&&(e=e.data);const n=i.get(e);n&&(t.deleteBuffer(n.buffer),i.delete(e))},update:function(e,r){if(e.isGLBufferAttribute){const t=i.get(e);return void((!t||t.version<e.version)&&i.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version}))}e.isInterleavedBufferAttribute&&(e=e.data);const s=i.get(e);void 0===s?i.set(e,function(e,i){const r=e.array,s=e.usage,a=t.createBuffer();t.bindBuffer(i,a),t.bufferData(i,r,s),e.onUploadCallback();let o=5126;return r instanceof Float32Array?o=5126:r instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):r instanceof Uint16Array?e.isFloat16BufferAttribute?n?o=5131:console.warn("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2."):o=5123:r instanceof Int16Array?o=5122:r instanceof Uint32Array?o=5125:r instanceof Int32Array?o=5124:r instanceof Int8Array?o=5120:(r instanceof Uint8Array||r instanceof Uint8ClampedArray)&&(o=5121),{buffer:a,type:o,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version}}(e,r)):s.version<e.version&&(!function(e,i,r){const s=i.array,a=i.updateRange;t.bindBuffer(r,e),-1===a.count?t.bufferSubData(r,0,s):(n?t.bufferSubData(r,a.offset*s.BYTES_PER_ELEMENT,s,a.offset,a.count):t.bufferSubData(r,a.offset*s.BYTES_PER_ELEMENT,s.subarray(a.offset,a.offset+a.count)),a.count=-1)}(s.buffer,e,r),s.version=e.version)}}}class si extends xn{constructor(t=1,e=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:t,height:e,widthSegments:n,heightSegments:i};const r=t/2,s=e/2,a=Math.floor(n),o=Math.floor(i),l=a+1,c=o+1,h=t/a,u=e/o,d=[],p=[],m=[],f=[];for(let t=0;t<c;t++){const e=t*u-s;for(let n=0;n<l;n++){const i=n*h-r;p.push(i,-e,0),m.push(0,0,1),f.push(n/a),f.push(1-t/o)}}for(let t=0;t<o;t++)for(let e=0;e<a;e++){const n=e+l*t,i=e+l*(t+1),r=e+1+l*(t+1),s=e+1+l*t;d.push(n,i,s),d.push(i,r,s)}this.setIndex(d),this.setAttribute("position",new hn(p,3)),this.setAttribute("normal",new hn(m,3)),this.setAttribute("uv",new hn(f,2))}static fromJSON(t){return new si(t.width,t.height,t.widthSegments,t.heightSegments)}}const ai={alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",alphatest_fragment:"#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif",alphatest_pars_fragment:"#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",begin_vertex:"vec3 transformed = vec3( position );",beginnormal_vertex:"vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif",bsdfs:"vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn 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\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif",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; }\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 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 ) + 0.5;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\treturn texture2D( envMap, uv ).rgb;\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",encodings_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",encodings_pars_fragment:"vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\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\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= specularColorMapTexelToLinear( texture2D( specularColorMap, vUv ) ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= sheenColorMapTexelToLinear( texture2D( sheenColorMap, vUv ) ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\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\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3(\t\t0, 1,\t\t0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;",normal_fragment_maps:"#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif",output_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn 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\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t\tf.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t\tf.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif",shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",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\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3(\t1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108,\t1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605,\t1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif",uv_pars_fragment:"#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif",uv_vertex:"#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif",uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}",cube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}",depth_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",meshbasic_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",shadow_vert:"#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}"},oi={common:{diffuse:{value:new Ze(16777215)},opacity:{value:1},map:{value:null},uvTransform:{value:new pt},uv2Transform:{value:new pt},alphaMap:{value:null},alphaTest:{value:0}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new dt(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ze(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Ze(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaTest:{value:0},uvTransform:{value:new pt}},sprite:{diffuse:{value:new Ze(16777215)},opacity:{value:1},center:{value:new dt(.5,.5)},rotation:{value:0},map:{value:null},alphaMap:{value:null},alphaTest:{value:0},uvTransform:{value:new pt}}},li={basic:{uniforms:Gn([oi.common,oi.specularmap,oi.envmap,oi.aomap,oi.lightmap,oi.fog]),vertexShader:ai.meshbasic_vert,fragmentShader:ai.meshbasic_frag},lambert:{uniforms:Gn([oi.common,oi.specularmap,oi.envmap,oi.aomap,oi.lightmap,oi.emissivemap,oi.fog,oi.lights,{emissive:{value:new Ze(0)}}]),vertexShader:ai.meshlambert_vert,fragmentShader:ai.meshlambert_frag},phong:{uniforms:Gn([oi.common,oi.specularmap,oi.envmap,oi.aomap,oi.lightmap,oi.emissivemap,oi.bumpmap,oi.normalmap,oi.displacementmap,oi.fog,oi.lights,{emissive:{value:new Ze(0)},specular:{value:new Ze(1118481)},shininess:{value:30}}]),vertexShader:ai.meshphong_vert,fragmentShader:ai.meshphong_frag},standard:{uniforms:Gn([oi.common,oi.envmap,oi.aomap,oi.lightmap,oi.emissivemap,oi.bumpmap,oi.normalmap,oi.displacementmap,oi.roughnessmap,oi.metalnessmap,oi.fog,oi.lights,{emissive:{value:new Ze(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ai.meshphysical_vert,fragmentShader:ai.meshphysical_frag},toon:{uniforms:Gn([oi.common,oi.aomap,oi.lightmap,oi.emissivemap,oi.bumpmap,oi.normalmap,oi.displacementmap,oi.gradientmap,oi.fog,oi.lights,{emissive:{value:new Ze(0)}}]),vertexShader:ai.meshtoon_vert,fragmentShader:ai.meshtoon_frag},matcap:{uniforms:Gn([oi.common,oi.bumpmap,oi.normalmap,oi.displacementmap,oi.fog,{matcap:{value:null}}]),vertexShader:ai.meshmatcap_vert,fragmentShader:ai.meshmatcap_frag},points:{uniforms:Gn([oi.points,oi.fog]),vertexShader:ai.points_vert,fragmentShader:ai.points_frag},dashed:{uniforms:Gn([oi.common,oi.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ai.linedashed_vert,fragmentShader:ai.linedashed_frag},depth:{uniforms:Gn([oi.common,oi.displacementmap]),vertexShader:ai.depth_vert,fragmentShader:ai.depth_frag},normal:{uniforms:Gn([oi.common,oi.bumpmap,oi.normalmap,oi.displacementmap,{opacity:{value:1}}]),vertexShader:ai.meshnormal_vert,fragmentShader:ai.meshnormal_frag},sprite:{uniforms:Gn([oi.sprite,oi.fog]),vertexShader:ai.sprite_vert,fragmentShader:ai.sprite_frag},background:{uniforms:{uvTransform:{value:new pt},t2D:{value:null}},vertexShader:ai.background_vert,fragmentShader:ai.background_frag},cube:{uniforms:Gn([oi.envmap,{opacity:{value:1}}]),vertexShader:ai.cube_vert,fragmentShader:ai.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ai.equirect_vert,fragmentShader:ai.equirect_frag},distanceRGBA:{uniforms:Gn([oi.common,oi.displacementmap,{referencePosition:{value:new Lt},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ai.distanceRGBA_vert,fragmentShader:ai.distanceRGBA_frag},shadow:{uniforms:Gn([oi.lights,oi.fog,{color:{value:new Ze(0)},opacity:{value:1}}]),vertexShader:ai.shadow_vert,fragmentShader:ai.shadow_frag}};function ci(t,e,n,i,r){const s=new Ze(0);let a,o,c=0,h=null,u=0,d=null;function p(t,e){n.buffers.color.setClear(t.r,t.g,t.b,e,r)}return{getClearColor:function(){return s},setClearColor:function(t,e=1){s.set(t),c=e,p(s,c)},getClearAlpha:function(){return c},setClearAlpha:function(t){c=t,p(s,c)},render:function(n,r){let m=!1,f=!0===r.isScene?r.background:null;f&&f.isTexture&&(f=e.get(f));const g=t.xr,v=g.getSession&&g.getSession();v&&"additive"===v.environmentBlendMode&&(f=null),null===f?p(s,c):f&&f.isColor&&(p(f,1),m=!0),(t.autoClear||m)&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),f&&(f.isCubeTexture||f.mapping===l)?(void 0===o&&(o=new Fn(new Un(1,1,1),new Vn({name:"BackgroundCubeMaterial",uniforms:Hn(li.cube.uniforms),vertexShader:li.cube.vertexShader,fragmentShader:li.cube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),o.geometry.deleteAttribute("normal"),o.geometry.deleteAttribute("uv"),o.onBeforeRender=function(t,e,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(o.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(o)),o.material.uniforms.envMap.value=f,o.material.uniforms.flipEnvMap.value=f.isCubeTexture&&!1===f.isRenderTargetTexture?-1:1,h===f&&u===f.version&&d===t.toneMapping||(o.material.needsUpdate=!0,h=f,u=f.version,d=t.toneMapping),n.unshift(o,o.geometry,o.material,0,0,null)):f&&f.isTexture&&(void 0===a&&(a=new Fn(new si(2,2),new Vn({name:"BackgroundMaterial",uniforms:Hn(li.background.uniforms),vertexShader:li.background.vertexShader,fragmentShader:li.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),a.geometry.deleteAttribute("normal"),Object.defineProperty(a.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(a)),a.material.uniforms.t2D.value=f,!0===f.matrixAutoUpdate&&f.updateMatrix(),a.material.uniforms.uvTransform.value.copy(f.matrix),h===f&&u===f.version&&d===t.toneMapping||(a.material.needsUpdate=!0,h=f,u=f.version,d=t.toneMapping),n.unshift(a,a.geometry,a.material,0,0,null))}}}function hi(t,e,n,i){const r=t.getParameter(34921),s=i.isWebGL2?null:e.get("OES_vertex_array_object"),a=i.isWebGL2||null!==s,o={},l=d(null);let c=l;function h(e){return i.isWebGL2?t.bindVertexArray(e):s.bindVertexArrayOES(e)}function u(e){return i.isWebGL2?t.deleteVertexArray(e):s.deleteVertexArrayOES(e)}function d(t){const e=[],n=[],i=[];for(let t=0;t<r;t++)e[t]=0,n[t]=0,i[t]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:e,enabledAttributes:n,attributeDivisors:i,object:t,attributes:{},index:null}}function p(){const t=c.newAttributes;for(let e=0,n=t.length;e<n;e++)t[e]=0}function m(t){f(t,0)}function f(n,r){const s=c.newAttributes,a=c.enabledAttributes,o=c.attributeDivisors;if(s[n]=1,0===a[n]&&(t.enableVertexAttribArray(n),a[n]=1),o[n]!==r){(i.isWebGL2?t:e.get("ANGLE_instanced_arrays"))[i.isWebGL2?"vertexAttribDivisor":"vertexAttribDivisorANGLE"](n,r),o[n]=r}}function g(){const e=c.newAttributes,n=c.enabledAttributes;for(let i=0,r=n.length;i<r;i++)n[i]!==e[i]&&(t.disableVertexAttribArray(i),n[i]=0)}function v(e,n,r,s,a,o){!0!==i.isWebGL2||5124!==r&&5125!==r?t.vertexAttribPointer(e,n,r,s,a,o):t.vertexAttribIPointer(e,n,r,a,o)}function y(){x(),c!==l&&(c=l,h(c.object))}function x(){l.geometry=null,l.program=null,l.wireframe=!1}return{setup:function(r,l,u,y,x){let _=!1;if(a){const e=function(e,n,r){const a=!0===r.wireframe;let l=o[e.id];void 0===l&&(l={},o[e.id]=l);let c=l[n.id];void 0===c&&(c={},l[n.id]=c);let h=c[a];void 0===h&&(h=d(i.isWebGL2?t.createVertexArray():s.createVertexArrayOES()),c[a]=h);return h}(y,u,l);c!==e&&(c=e,h(c.object)),_=function(t,e){const n=c.attributes,i=t.attributes;let r=0;for(const t in i){const e=n[t],s=i[t];if(void 0===e)return!0;if(e.attribute!==s)return!0;if(e.data!==s.data)return!0;r++}return c.attributesNum!==r||c.index!==e}(y,x),_&&function(t,e){const n={},i=t.attributes;let r=0;for(const t in i){const e=i[t],s={};s.attribute=e,e.data&&(s.data=e.data),n[t]=s,r++}c.attributes=n,c.attributesNum=r,c.index=e}(y,x)}else{const t=!0===l.wireframe;c.geometry===y.id&&c.program===u.id&&c.wireframe===t||(c.geometry=y.id,c.program=u.id,c.wireframe=t,_=!0)}!0===r.isInstancedMesh&&(_=!0),null!==x&&n.update(x,34963),_&&(!function(r,s,a,o){if(!1===i.isWebGL2&&(r.isInstancedMesh||o.isInstancedBufferGeometry)&&null===e.get("ANGLE_instanced_arrays"))return;p();const l=o.attributes,c=a.getAttributes(),h=s.defaultAttributeValues;for(const e in c){const i=c[e];if(i.location>=0){let s=l[e];if(void 0===s&&("instanceMatrix"===e&&r.instanceMatrix&&(s=r.instanceMatrix),"instanceColor"===e&&r.instanceColor&&(s=r.instanceColor)),void 0!==s){const e=s.normalized,a=s.itemSize,l=n.get(s);if(void 0===l)continue;const c=l.buffer,h=l.type,u=l.bytesPerElement;if(s.isInterleavedBufferAttribute){const n=s.data,l=n.stride,d=s.offset;if(n&&n.isInstancedInterleavedBuffer){for(let t=0;t<i.locationSize;t++)f(i.location+t,n.meshPerAttribute);!0!==r.isInstancedMesh&&void 0===o._maxInstanceCount&&(o._maxInstanceCount=n.meshPerAttribute*n.count)}else for(let t=0;t<i.locationSize;t++)m(i.location+t);t.bindBuffer(34962,c);for(let t=0;t<i.locationSize;t++)v(i.location+t,a/i.locationSize,h,e,l*u,(d+a/i.locationSize*t)*u)}else{if(s.isInstancedBufferAttribute){for(let t=0;t<i.locationSize;t++)f(i.location+t,s.meshPerAttribute);!0!==r.isInstancedMesh&&void 0===o._maxInstanceCount&&(o._maxInstanceCount=s.meshPerAttribute*s.count)}else for(let t=0;t<i.locationSize;t++)m(i.location+t);t.bindBuffer(34962,c);for(let t=0;t<i.locationSize;t++)v(i.location+t,a/i.locationSize,h,e,a*u,a/i.locationSize*t*u)}}else if(void 0!==h){const n=h[e];if(void 0!==n)switch(n.length){case 2:t.vertexAttrib2fv(i.location,n);break;case 3:t.vertexAttrib3fv(i.location,n);break;case 4:t.vertexAttrib4fv(i.location,n);break;default:t.vertexAttrib1fv(i.location,n)}}}}g()}(r,l,u,y),null!==x&&t.bindBuffer(34963,n.get(x).buffer))},reset:y,resetDefaultState:x,dispose:function(){y();for(const t in o){const e=o[t];for(const t in e){const n=e[t];for(const t in n)u(n[t].object),delete n[t];delete e[t]}delete o[t]}},releaseStatesOfGeometry:function(t){if(void 0===o[t.id])return;const e=o[t.id];for(const t in e){const n=e[t];for(const t in n)u(n[t].object),delete n[t];delete e[t]}delete o[t.id]},releaseStatesOfProgram:function(t){for(const e in o){const n=o[e];if(void 0===n[t.id])continue;const i=n[t.id];for(const t in i)u(i[t].object),delete i[t];delete n[t.id]}},initAttributes:p,enableAttribute:m,disableUnusedAttributes:g}}function ui(t,e,n,i){const r=i.isWebGL2;let s;this.setMode=function(t){s=t},this.render=function(e,i){t.drawArrays(s,e,i),n.update(i,s,1)},this.renderInstances=function(i,a,o){if(0===o)return;let l,c;if(r)l=t,c="drawArraysInstanced";else if(l=e.get("ANGLE_instanced_arrays"),c="drawArraysInstancedANGLE",null===l)return void console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");l[c](s,i,a,o),n.update(a,s,o)}}function di(t,e,n){let i;function r(e){if("highp"===e){if(t.getShaderPrecisionFormat(35633,36338).precision>0&&t.getShaderPrecisionFormat(35632,36338).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(35633,36337).precision>0&&t.getShaderPrecisionFormat(35632,36337).precision>0?"mediump":"lowp"}const s="undefined"!=typeof WebGL2RenderingContext&&t instanceof WebGL2RenderingContext||"undefined"!=typeof WebGL2ComputeRenderingContext&&t instanceof WebGL2ComputeRenderingContext;let a=void 0!==n.precision?n.precision:"highp";const o=r(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=s||e.has("WEBGL_draw_buffers"),c=!0===n.logarithmicDepthBuffer,h=t.getParameter(34930),u=t.getParameter(35660),d=t.getParameter(3379),p=t.getParameter(34076),m=t.getParameter(34921),f=t.getParameter(36347),g=t.getParameter(36348),v=t.getParameter(36349),y=u>0,x=s||e.has("OES_texture_float");return{isWebGL2:s,drawBuffers:l,getMaxAnisotropy:function(){if(void 0!==i)return i;if(!0===e.has("EXT_texture_filter_anisotropic")){const n=e.get("EXT_texture_filter_anisotropic");i=t.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i},getMaxPrecision:r,precision:a,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:u,maxTextureSize:d,maxCubemapSize:p,maxAttributes:m,maxVertexUniforms:f,maxVaryings:g,maxFragmentUniforms:v,vertexTextures:y,floatFragmentTextures:x,floatVertexTextures:y&&x,maxSamples:s?t.getParameter(36183):0}}function pi(t){const e=this;let n=null,i=0,r=!1,s=!1;const a=new $n,o=new pt,l={value:null,needsUpdate:!1};function c(){l.value!==n&&(l.value=n,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function h(t,n,i,r){const s=null!==t?t.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const e=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length<e)&&(c=new Float32Array(e));for(let e=0,n=i;e!==s;++e,n+=4)a.copy(t[e]).applyMatrix4(r,o),a.normal.toArray(c,n),c[n+3]=a.constant}l.value=c,l.needsUpdate=!0}return e.numPlanes=s,e.numIntersection=0,c}this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(t,e,s){const a=0!==t.length||e||0!==i||r;return r=e,n=h(t,s,0),i=t.length,a},this.beginShadows=function(){s=!0,h(null)},this.endShadows=function(){s=!1,c()},this.setState=function(e,a,o){const u=e.clippingPlanes,d=e.clipIntersection,p=e.clipShadows,m=t.get(e);if(!r||null===u||0===u.length||s&&!p)s?h(null):c();else{const t=s?0:i,e=4*t;let r=m.clippingState||null;l.value=r,r=h(u,a,e,o);for(let t=0;t!==e;++t)r[t]=n[t];m.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=t}}}function mi(t){let e=new WeakMap;function n(t,e){return e===a?t.mapping=r:e===o&&(t.mapping=s),t}function i(t){const n=t.target;n.removeEventListener("dispose",i);const r=e.get(n);void 0!==r&&(e.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture&&!1===r.isRenderTargetTexture){const s=r.mapping;if(s===a||s===o){if(e.has(r)){return n(e.get(r).texture,r.mapping)}{const s=r.image;if(s&&s.height>0){const a=t.getRenderTarget(),o=new Yn(s.height/2);return o.fromEquirectangularTexture(t,r),e.set(r,o),t.setRenderTarget(a),r.addEventListener("dispose",i),n(o.texture,r.mapping)}return null}}}return r},dispose:function(){e=new WeakMap}}}li.physical={uniforms:Gn([li.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatNormalScale:{value:new dt(1,1)},clearcoatNormalMap:{value:null},sheen:{value:0},sheenColor:{value:new Ze(0)},sheenColorMap:{value:null},sheenRoughness:{value:0},sheenRoughnessMap:{value:null},transmission:{value:0},transmissionMap:{value:null},transmissionSamplerSize:{value:new dt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},attenuationDistance:{value:0},attenuationColor:{value:new Ze(0)},specularIntensity:{value:0},specularIntensityMap:{value:null},specularColor:{value:new Ze(1,1,1)},specularColorMap:{value:null}}]),vertexShader:ai.meshphysical_vert,fragmentShader:ai.meshphysical_frag};class fi extends Wn{constructor(t=-1,e=1,n=1,i=-1,r=.1,s=2e3){super(),this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=n,this.bottom=i,this.near=r,this.far=s,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=null===t.view?null:Object.assign({},t.view),this}setViewOffset(t,e,n,i,r,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=n-t,s=n+t,a=i+e,o=i-e;if(null!==this.view&&this.view.enabled){const t=(this.right-this.left)/this.view.fullWidth/this.zoom,e=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=t*this.view.offsetX,s=r+t*this.view.width,a-=e*this.view.offsetY,o=a-e*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,this.near,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,null!==this.view&&(e.object.view=Object.assign({},this.view)),e}}fi.prototype.isOrthographicCamera=!0;class gi extends Vn{constructor(t){super(t),this.type="RawShaderMaterial"}}gi.prototype.isRawShaderMaterial=!0;const vi=Math.pow(2,8),yi=[.125,.215,.35,.446,.526,.582],xi=5+yi.length,_i=20,bi={[X]:0,[J]:1},Mi=new fi,{_lodPlanes:wi,_sizeLods:Si,_sigmas:Ti}=Di(),Ei=new Ze;let Ai=null;const Li=(1+Math.sqrt(5))/2,Ri=1/Li,Ci=[new Lt(1,1,1),new Lt(-1,1,1),new Lt(1,1,-1),new Lt(-1,1,-1),new Lt(0,Li,Ri),new Lt(0,Li,-Ri),new Lt(Ri,0,Li),new Lt(-Ri,0,Li),new Lt(Li,Ri,0),new Lt(-Li,Ri,0)];class Pi{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._blurMaterial=function(t){const e=new Float32Array(t),n=new Lt(0,1,0);return new gi({name:"SphericalGaussianBlur",defines:{n:t},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:e},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:Fi(),fragmentShader:`\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t${Oi()}\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t`,blending:0,depthTest:!1,depthWrite:!1})}(_i),this._equirectShader=null,this._cubemapShader=null,this._compileMaterial(this._blurMaterial)}fromScene(t,e=0,n=.1,i=100){Ai=this._renderer.getRenderTarget();const r=this._allocateTargets();return this._sceneToCubeUV(t,n,i,r),e>0&&this._blur(r,0,0,e),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(t){return this._fromTexture(t)}fromCubemap(t){return this._fromTexture(t)}compileCubemapShader(){null===this._cubemapShader&&(this._cubemapShader=Bi(),this._compileMaterial(this._cubemapShader))}compileEquirectangularShader(){null===this._equirectShader&&(this._equirectShader=zi(),this._compileMaterial(this._equirectShader))}dispose(){this._blurMaterial.dispose(),null!==this._cubemapShader&&this._cubemapShader.dispose(),null!==this._equirectShader&&this._equirectShader.dispose();for(let t=0;t<wi.length;t++)wi[t].dispose()}_cleanup(t){this._pingPongRenderTarget.dispose(),this._renderer.setRenderTarget(Ai),t.scissorTest=!1,Ni(t,0,0,t.width,t.height)}_fromTexture(t){Ai=this._renderer.getRenderTarget();const e=this._allocateTargets(t);return this._textureToCubeUV(t,e),this._applyPMREM(e),this._cleanup(e),e}_allocateTargets(t){const e={magFilter:g,minFilter:g,generateMipmaps:!1,type:w,format:E,encoding:X,depthBuffer:!1},n=Ii(e);return n.depthBuffer=!t,this._pingPongRenderTarget=Ii(e),n}_compileMaterial(t){const e=new Fn(wi[0],t);this._renderer.compile(e,Mi)}_sceneToCubeUV(t,e,n,i){const r=new jn(90,1,e,n),s=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(Ei),o.toneMapping=0,o.autoClear=!1;const h=new Qe({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),u=new Fn(new Un,h);let d=!1;const p=t.background;p?p.isColor&&(h.color.copy(p),t.background=null,d=!0):(h.color.copy(Ei),d=!0);for(let e=0;e<6;e++){const n=e%3;0==n?(r.up.set(0,s[e],0),r.lookAt(a[e],0,0)):1==n?(r.up.set(0,0,s[e]),r.lookAt(0,a[e],0)):(r.up.set(0,s[e],0),r.lookAt(0,0,a[e])),Ni(i,n*vi,e>2?vi:0,vi,vi),o.setRenderTarget(i),d&&o.render(u,r),o.render(t,r)}u.geometry.dispose(),u.material.dispose(),o.toneMapping=c,o.autoClear=l,t.background=p}_setEncoding(t,e){!0===this._renderer.capabilities.isWebGL2&&e.format===E&&e.type===x&&e.encoding===J?t.value=bi[3e3]:t.value=bi[e.encoding]}_textureToCubeUV(t,e){const n=this._renderer,i=t.mapping===r||t.mapping===s;i?null==this._cubemapShader&&(this._cubemapShader=Bi()):null==this._equirectShader&&(this._equirectShader=zi());const a=i?this._cubemapShader:this._equirectShader,o=new Fn(wi[0],a),l=a.uniforms;l.envMap.value=t,i||l.texelSize.value.set(1/t.image.width,1/t.image.height),this._setEncoding(l.inputEncoding,t),Ni(e,0,0,3*vi,2*vi),n.setRenderTarget(e),n.render(o,Mi)}_applyPMREM(t){const e=this._renderer,n=e.autoClear;e.autoClear=!1;for(let e=1;e<xi;e++){const n=Math.sqrt(Ti[e]*Ti[e]-Ti[e-1]*Ti[e-1]),i=Ci[(e-1)%Ci.length];this._blur(t,e-1,e,n,i)}e.autoClear=n}_blur(t,e,n,i,r){const s=this._pingPongRenderTarget;this._halfBlur(t,s,e,n,i,"latitudinal",r),this._halfBlur(s,t,n,n,i,"longitudinal",r)}_halfBlur(t,e,n,i,r,s,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==s&&"longitudinal"!==s&&console.error("blur direction must be either latitudinal or longitudinal!");const c=new Fn(wi[i],l),h=l.uniforms,u=Si[n]-1,d=isFinite(r)?Math.PI/(2*u):2*Math.PI/39,p=r/d,m=isFinite(r)?1+Math.floor(3*p):_i;m>_i&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let t=0;t<_i;++t){const e=t/p,n=Math.exp(-e*e/2);f.push(n),0==t?g+=n:t<m&&(g+=2*n)}for(let t=0;t<f.length;t++)f[t]=f[t]/g;h.envMap.value=t.texture,h.samples.value=m,h.weights.value=f,h.latitudinal.value="latitudinal"===s,a&&(h.poleAxis.value=a),h.dTheta.value=d,h.mipInt.value=8-n;const v=Si[i];Ni(e,3*Math.max(0,vi-2*v),(0===i?0:2*vi)+2*v*(i>4?i-8+4:0),3*v,2*v),o.setRenderTarget(e),o.render(c,Mi)}}function Di(){const t=[],e=[],n=[];let i=8;for(let r=0;r<xi;r++){const s=Math.pow(2,i);e.push(s);let a=1/s;r>4?a=yi[r-8+4-1]:0==r&&(a=0),n.push(a);const o=1/(s-1),l=-o/2,c=1+o/2,h=[l,l,c,l,c,c,l,l,c,c,l,c],u=6,d=6,p=3,m=2,f=1,g=new Float32Array(p*d*u),v=new Float32Array(m*d*u),y=new Float32Array(f*d*u);for(let t=0;t<u;t++){const e=t%3*2/3-1,n=t>2?0:-1,i=[e,n,0,e+2/3,n,0,e+2/3,n+1,0,e,n,0,e+2/3,n+1,0,e,n+1,0];g.set(i,p*d*t),v.set(h,m*d*t);const r=[t,t,t,t,t,t];y.set(r,f*d*t)}const x=new xn;x.setAttribute("position",new tn(g,p)),x.setAttribute("uv",new tn(v,m)),x.setAttribute("faceIndex",new tn(y,f)),t.push(x),i>4&&i--}return{_lodPlanes:t,_sizeLods:e,_sigmas:n}}function Ii(t){const e=new St(3*vi,3*vi,t);return e.texture.mapping=l,e.texture.name="PMREM.cubeUv",e.scissorTest=!0,e}function Ni(t,e,n,i,r){t.viewport.set(e,n,i,r),t.scissor.set(e,n,i,r)}function zi(){const t=new dt(1,1);return new gi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null},texelSize:{value:t},inputEncoding:{value:bi[3e3]}},vertexShader:Fi(),fragmentShader:`\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform vec2 texelSize;\n\n\t\t\t${Oi()}\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tvec2 f = fract( uv / texelSize - 0.5 );\n\t\t\t\tuv -= f * texelSize;\n\t\t\t\tvec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x += texelSize.x;\n\t\t\t\tvec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.y += texelSize.y;\n\t\t\t\tvec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x -= texelSize.x;\n\t\t\t\tvec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\n\t\t\t\tvec3 tm = mix( tl, tr, f.x );\n\t\t\t\tvec3 bm = mix( bl, br, f.x );\n\t\t\t\tgl_FragColor.rgb = mix( tm, bm, f.y );\n\n\t\t\t}\n\t\t`,blending:0,depthTest:!1,depthWrite:!1})}function Bi(){return new gi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},inputEncoding:{value:bi[3e3]}},vertexShader:Fi(),fragmentShader:`\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\t${Oi()}\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) );\n\n\t\t\t}\n\t\t`,blending:0,depthTest:!1,depthWrite:!1})}function Fi(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute vec3 position;\n\t\tattribute vec2 uv;\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function Oi(){return"\n\n\t\tuniform int inputEncoding;\n\n\t\t#include <encodings_pars_fragment>\n\n\t\tvec4 inputTexelToLinear( vec4 value ) {\n\n\t\t\tif ( inputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else {\n\n\t\t\t\treturn sRGBToLinear( value );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 envMapTexelToLinear( vec4 color ) {\n\n\t\t\treturn inputTexelToLinear( color );\n\n\t\t}\n\t"}function Ui(t){let e=new WeakMap,n=null;function i(t){const n=t.target;n.removeEventListener("dispose",i);const r=e.get(n);void 0!==r&&(e.delete(n),r.dispose())}return{get:function(l){if(l&&l.isTexture&&!1===l.isRenderTargetTexture){const c=l.mapping,h=c===a||c===o,u=c===r||c===s;if(h||u){if(e.has(l))return e.get(l).texture;{const r=l.image;if(h&&r&&r.height>0||u&&r&&function(t){let e=0;const n=6;for(let i=0;i<n;i++)void 0!==t[i]&&e++;return e===n}(r)){const r=t.getRenderTarget();null===n&&(n=new Pi(t));const s=h?n.fromEquirectangular(l):n.fromCubemap(l);return e.set(l,s),t.setRenderTarget(r),l.addEventListener("dispose",i),s.texture}return null}}}return l},dispose:function(){e=new WeakMap,null!==n&&(n.dispose(),n=null)}}}function Hi(t){const e={};function n(n){if(void 0!==e[n])return e[n];let i;switch(n){case"WEBGL_depth_texture":i=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=t.getExtension(n)}return e[n]=i,i}return{has:function(t){return null!==n(t)},init:function(t){t.isWebGL2?n("EXT_color_buffer_float"):(n("WEBGL_depth_texture"),n("OES_texture_float"),n("OES_texture_half_float"),n("OES_texture_half_float_linear"),n("OES_standard_derivatives"),n("OES_element_index_uint"),n("OES_vertex_array_object"),n("ANGLE_instanced_arrays")),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture")},get:function(t){const e=n(t);return null===e&&console.warn("THREE.WebGLRenderer: "+t+" extension not supported."),e}}}function Gi(t,e,n,i){const r={},s=new WeakMap;function a(t){const o=t.target;null!==o.index&&e.remove(o.index);for(const t in o.attributes)e.remove(o.attributes[t]);o.removeEventListener("dispose",a),delete r[o.id];const l=s.get(o);l&&(e.remove(l),s.delete(o)),i.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,n.memory.geometries--}function o(t){const n=[],i=t.index,r=t.attributes.position;let a=0;if(null!==i){const t=i.array;a=i.version;for(let e=0,i=t.length;e<i;e+=3){const i=t[e+0],r=t[e+1],s=t[e+2];n.push(i,r,r,s,s,i)}}else{const t=r.array;a=r.version;for(let e=0,i=t.length/3-1;e<i;e+=3){const t=e+0,i=e+1,r=e+2;n.push(t,i,i,r,r,t)}}const o=new(mt(n)>65535?ln:an)(n,1);o.version=a;const l=s.get(t);l&&e.remove(l),s.set(t,o)}return{get:function(t,e){return!0===r[e.id]||(e.addEventListener("dispose",a),r[e.id]=!0,n.memory.geometries++),e},update:function(t){const n=t.attributes;for(const t in n)e.update(n[t],34962);const i=t.morphAttributes;for(const t in i){const n=i[t];for(let t=0,i=n.length;t<i;t++)e.update(n[t],34962)}},getWireframeAttribute:function(t){const e=s.get(t);if(e){const n=t.index;null!==n&&e.version<n.version&&o(t)}else o(t);return s.get(t)}}}function ki(t,e,n,i){const r=i.isWebGL2;let s,a,o;this.setMode=function(t){s=t},this.setIndex=function(t){a=t.type,o=t.bytesPerElement},this.render=function(e,i){t.drawElements(s,i,a,e*o),n.update(i,s,1)},this.renderInstances=function(i,l,c){if(0===c)return;let h,u;if(r)h=t,u="drawElementsInstanced";else if(h=e.get("ANGLE_instanced_arrays"),u="drawElementsInstancedANGLE",null===h)return void console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");h[u](s,l,a,i*o,c),n.update(l,s,c)}}function Vi(t){const e={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:e,programs:null,autoReset:!0,reset:function(){e.frame++,e.calls=0,e.triangles=0,e.points=0,e.lines=0},update:function(t,n,i){switch(e.calls++,n){case 4:e.triangles+=i*(t/3);break;case 1:e.lines+=i*(t/2);break;case 3:e.lines+=i*(t-1);break;case 2:e.lines+=i*t;break;case 0:e.points+=i*t;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",n)}}}}class Wi extends bt{constructor(t=null,e=1,n=1,i=1){super(null),this.image={data:t,width:e,height:n,depth:i},this.magFilter=p,this.minFilter=p,this.wrapR=u,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}function ji(t,e){return t[0]-e[0]}function qi(t,e){return Math.abs(e[1])-Math.abs(t[1])}function Xi(t,e){let n=1;const i=e.isInterleavedBufferAttribute?e.data.array:e.array;i instanceof Int8Array?n=127:i instanceof Int16Array?n=32767:i instanceof Int32Array?n=2147483647:console.error("THREE.WebGLMorphtargets: Unsupported morph attribute data type: ",i),t.divideScalar(n)}function Ji(t,e,n){const i={},r=new Float32Array(8),s=new WeakMap,a=new Lt,o=[];for(let t=0;t<8;t++)o[t]=[t,0];return{update:function(l,c,h,u){const d=l.morphTargetInfluences;if(!0===e.isWebGL2){const i=c.morphAttributes.position.length;let r=s.get(c);if(void 0===r||r.count!==i){void 0!==r&&r.texture.dispose();const t=void 0!==c.morphAttributes.normal,n=c.morphAttributes.position,o=c.morphAttributes.normal||[],l=!0===t?2:1;let h=c.attributes.position.count*l,u=1;h>e.maxTextureSize&&(u=Math.ceil(h/e.maxTextureSize),h=e.maxTextureSize);const d=new Float32Array(h*u*4*i),p=new Wi(d,h,u,i);p.format=E,p.type=M,p.needsUpdate=!0;const m=4*l;for(let e=0;e<i;e++){const i=n[e],r=o[e],s=h*u*4*e;for(let e=0;e<i.count;e++){a.fromBufferAttribute(i,e),!0===i.normalized&&Xi(a,i);const n=e*m;d[s+n+0]=a.x,d[s+n+1]=a.y,d[s+n+2]=a.z,d[s+n+3]=0,!0===t&&(a.fromBufferAttribute(r,e),!0===r.normalized&&Xi(a,r),d[s+n+4]=a.x,d[s+n+5]=a.y,d[s+n+6]=a.z,d[s+n+7]=0)}}r={count:i,texture:p,size:new dt(h,u)},s.set(c,r)}let o=0;for(let t=0;t<d.length;t++)o+=d[t];const l=c.morphTargetsRelative?1:1-o;u.getUniforms().setValue(t,"morphTargetBaseInfluence",l),u.getUniforms().setValue(t,"morphTargetInfluences",d),u.getUniforms().setValue(t,"morphTargetsTexture",r.texture,n),u.getUniforms().setValue(t,"morphTargetsTextureSize",r.size)}else{const e=void 0===d?0:d.length;let n=i[c.id];if(void 0===n||n.length!==e){n=[];for(let t=0;t<e;t++)n[t]=[t,0];i[c.id]=n}for(let t=0;t<e;t++){const e=n[t];e[0]=t,e[1]=d[t]}n.sort(qi);for(let t=0;t<8;t++)t<e&&n[t][1]?(o[t][0]=n[t][0],o[t][1]=n[t][1]):(o[t][0]=Number.MAX_SAFE_INTEGER,o[t][1]=0);o.sort(ji);const s=c.morphAttributes.position,a=c.morphAttributes.normal;let l=0;for(let t=0;t<8;t++){const e=o[t],n=e[0],i=e[1];n!==Number.MAX_SAFE_INTEGER&&i?(s&&c.getAttribute("morphTarget"+t)!==s[n]&&c.setAttribute("morphTarget"+t,s[n]),a&&c.getAttribute("morphNormal"+t)!==a[n]&&c.setAttribute("morphNormal"+t,a[n]),r[t]=i,l+=i):(s&&!0===c.hasAttribute("morphTarget"+t)&&c.deleteAttribute("morphTarget"+t),a&&!0===c.hasAttribute("morphNormal"+t)&&c.deleteAttribute("morphNormal"+t),r[t]=0)}const h=c.morphTargetsRelative?1:1-l;u.getUniforms().setValue(t,"morphTargetBaseInfluence",h),u.getUniforms().setValue(t,"morphTargetInfluences",r)}}}}function Yi(t,e,n,i){let r=new WeakMap;function s(t){const e=t.target;e.removeEventListener("dispose",s),n.remove(e.instanceMatrix),null!==e.instanceColor&&n.remove(e.instanceColor)}return{update:function(t){const a=i.render.frame,o=t.geometry,l=e.get(t,o);return r.get(l)!==a&&(e.update(l),r.set(l,a)),t.isInstancedMesh&&(!1===t.hasEventListener("dispose",s)&&t.addEventListener("dispose",s),n.update(t.instanceMatrix,34962),null!==t.instanceColor&&n.update(t.instanceColor,34962)),l},dispose:function(){r=new WeakMap}}}Wi.prototype.isDataTexture2DArray=!0;class Zi extends bt{constructor(t=null,e=1,n=1,i=1){super(null),this.image={data:t,width:e,height:n,depth:i},this.magFilter=p,this.minFilter=p,this.wrapR=u,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}Zi.prototype.isDataTexture3D=!0;const Qi=new bt,Ki=new Wi,$i=new Zi,tr=new Jn,er=[],nr=[],ir=new Float32Array(16),rr=new Float32Array(9),sr=new Float32Array(4);function ar(t,e,n){const i=t[0];if(i<=0||i>0)return t;const r=e*n;let s=er[r];if(void 0===s&&(s=new Float32Array(r),er[r]=s),0!==e){i.toArray(s,0);for(let i=1,r=0;i!==e;++i)r+=n,t[i].toArray(s,r)}return s}function or(t,e){if(t.length!==e.length)return!1;for(let n=0,i=t.length;n<i;n++)if(t[n]!==e[n])return!1;return!0}function lr(t,e){for(let n=0,i=e.length;n<i;n++)t[n]=e[n]}function cr(t,e){let n=nr[e];void 0===n&&(n=new Int32Array(e),nr[e]=n);for(let i=0;i!==e;++i)n[i]=t.allocateTextureUnit();return n}function hr(t,e){const n=this.cache;n[0]!==e&&(t.uniform1f(this.addr,e),n[0]=e)}function ur(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y||(t.uniform2f(this.addr,e.x,e.y),n[0]=e.x,n[1]=e.y);else{if(or(n,e))return;t.uniform2fv(this.addr,e),lr(n,e)}}function dr(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y&&n[2]===e.z||(t.uniform3f(this.addr,e.x,e.y,e.z),n[0]=e.x,n[1]=e.y,n[2]=e.z);else if(void 0!==e.r)n[0]===e.r&&n[1]===e.g&&n[2]===e.b||(t.uniform3f(this.addr,e.r,e.g,e.b),n[0]=e.r,n[1]=e.g,n[2]=e.b);else{if(or(n,e))return;t.uniform3fv(this.addr,e),lr(n,e)}}function pr(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y&&n[2]===e.z&&n[3]===e.w||(t.uniform4f(this.addr,e.x,e.y,e.z,e.w),n[0]=e.x,n[1]=e.y,n[2]=e.z,n[3]=e.w);else{if(or(n,e))return;t.uniform4fv(this.addr,e),lr(n,e)}}function mr(t,e){const n=this.cache,i=e.elements;if(void 0===i){if(or(n,e))return;t.uniformMatrix2fv(this.addr,!1,e),lr(n,e)}else{if(or(n,i))return;sr.set(i),t.uniformMatrix2fv(this.addr,!1,sr),lr(n,i)}}function fr(t,e){const n=this.cache,i=e.elements;if(void 0===i){if(or(n,e))return;t.uniformMatrix3fv(this.addr,!1,e),lr(n,e)}else{if(or(n,i))return;rr.set(i),t.uniformMatrix3fv(this.addr,!1,rr),lr(n,i)}}function gr(t,e){const n=this.cache,i=e.elements;if(void 0===i){if(or(n,e))return;t.uniformMatrix4fv(this.addr,!1,e),lr(n,e)}else{if(or(n,i))return;ir.set(i),t.uniformMatrix4fv(this.addr,!1,ir),lr(n,i)}}function vr(t,e){const n=this.cache;n[0]!==e&&(t.uniform1i(this.addr,e),n[0]=e)}function yr(t,e){const n=this.cache;or(n,e)||(t.uniform2iv(this.addr,e),lr(n,e))}function xr(t,e){const n=this.cache;or(n,e)||(t.uniform3iv(this.addr,e),lr(n,e))}function _r(t,e){const n=this.cache;or(n,e)||(t.uniform4iv(this.addr,e),lr(n,e))}function br(t,e){const n=this.cache;n[0]!==e&&(t.uniform1ui(this.addr,e),n[0]=e)}function Mr(t,e){const n=this.cache;or(n,e)||(t.uniform2uiv(this.addr,e),lr(n,e))}function wr(t,e){const n=this.cache;or(n,e)||(t.uniform3uiv(this.addr,e),lr(n,e))}function Sr(t,e){const n=this.cache;or(n,e)||(t.uniform4uiv(this.addr,e),lr(n,e))}function Tr(t,e,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(t.uniform1i(this.addr,r),i[0]=r),n.safeSetTexture2D(e||Qi,r)}function Er(t,e,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(t.uniform1i(this.addr,r),i[0]=r),n.setTexture3D(e||$i,r)}function Ar(t,e,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(t.uniform1i(this.addr,r),i[0]=r),n.safeSetTextureCube(e||tr,r)}function Lr(t,e,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(t.uniform1i(this.addr,r),i[0]=r),n.setTexture2DArray(e||Ki,r)}function Rr(t,e){t.uniform1fv(this.addr,e)}function Cr(t,e){const n=ar(e,this.size,2);t.uniform2fv(this.addr,n)}function Pr(t,e){const n=ar(e,this.size,3);t.uniform3fv(this.addr,n)}function Dr(t,e){const n=ar(e,this.size,4);t.uniform4fv(this.addr,n)}function Ir(t,e){const n=ar(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,n)}function Nr(t,e){const n=ar(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,n)}function zr(t,e){const n=ar(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,n)}function Br(t,e){t.uniform1iv(this.addr,e)}function Fr(t,e){t.uniform2iv(this.addr,e)}function Or(t,e){t.uniform3iv(this.addr,e)}function Ur(t,e){t.uniform4iv(this.addr,e)}function Hr(t,e){t.uniform1uiv(this.addr,e)}function Gr(t,e){t.uniform2uiv(this.addr,e)}function kr(t,e){t.uniform3uiv(this.addr,e)}function Vr(t,e){t.uniform4uiv(this.addr,e)}function Wr(t,e,n){const i=e.length,r=cr(n,i);t.uniform1iv(this.addr,r);for(let t=0;t!==i;++t)n.safeSetTexture2D(e[t]||Qi,r[t])}function jr(t,e,n){const i=e.length,r=cr(n,i);t.uniform1iv(this.addr,r);for(let t=0;t!==i;++t)n.setTexture3D(e[t]||$i,r[t])}function qr(t,e,n){const i=e.length,r=cr(n,i);t.uniform1iv(this.addr,r);for(let t=0;t!==i;++t)n.safeSetTextureCube(e[t]||tr,r[t])}function Xr(t,e,n){const i=e.length,r=cr(n,i);t.uniform1iv(this.addr,r);for(let t=0;t!==i;++t)n.setTexture2DArray(e[t]||Ki,r[t])}function Jr(t,e,n){this.id=t,this.addr=n,this.cache=[],this.setValue=function(t){switch(t){case 5126:return hr;case 35664:return ur;case 35665:return dr;case 35666:return pr;case 35674:return mr;case 35675:return fr;case 35676:return gr;case 5124:case 35670:return vr;case 35667:case 35671:return yr;case 35668:case 35672:return xr;case 35669:case 35673:return _r;case 5125:return br;case 36294:return Mr;case 36295:return wr;case 36296:return Sr;case 35678:case 36198:case 36298:case 36306:case 35682:return Tr;case 35679:case 36299:case 36307:return Er;case 35680:case 36300:case 36308:case 36293:return Ar;case 36289:case 36303:case 36311:case 36292:return Lr}}(e.type)}function Yr(t,e,n){this.id=t,this.addr=n,this.cache=[],this.size=e.size,this.setValue=function(t){switch(t){case 5126:return Rr;case 35664:return Cr;case 35665:return Pr;case 35666:return Dr;case 35674:return Ir;case 35675:return Nr;case 35676:return zr;case 5124:case 35670:return Br;case 35667:case 35671:return Fr;case 35668:case 35672:return Or;case 35669:case 35673:return Ur;case 5125:return Hr;case 36294:return Gr;case 36295:return kr;case 36296:return Vr;case 35678:case 36198:case 36298:case 36306:case 35682:return Wr;case 35679:case 36299:case 36307:return jr;case 35680:case 36300:case 36308:case 36293:return qr;case 36289:case 36303:case 36311:case 36292:return Xr}}(e.type)}function Zr(t){this.id=t,this.seq=[],this.map={}}Yr.prototype.updateCache=function(t){const e=this.cache;t instanceof Float32Array&&e.length!==t.length&&(this.cache=new Float32Array(t.length)),lr(e,t)},Zr.prototype.setValue=function(t,e,n){const i=this.seq;for(let r=0,s=i.length;r!==s;++r){const s=i[r];s.setValue(t,e[s.id],n)}};const Qr=/(\w+)(\])?(\[|\.)?/g;function Kr(t,e){t.seq.push(e),t.map[e.id]=e}function $r(t,e,n){const i=t.name,r=i.length;for(Qr.lastIndex=0;;){const s=Qr.exec(i),a=Qr.lastIndex;let o=s[1];const l="]"===s[2],c=s[3];if(l&&(o|=0),void 0===c||"["===c&&a+2===r){Kr(n,void 0===c?new Jr(o,t,e):new Yr(o,t,e));break}{let t=n.map[o];void 0===t&&(t=new Zr(o),Kr(n,t)),n=t}}}function ts(t,e){this.seq=[],this.map={};const n=t.getProgramParameter(e,35718);for(let i=0;i<n;++i){const n=t.getActiveUniform(e,i);$r(n,t.getUniformLocation(e,n.name),this)}}function es(t,e,n){const i=t.createShader(e);return t.shaderSource(i,n),t.compileShader(i),i}ts.prototype.setValue=function(t,e,n,i){const r=this.map[e];void 0!==r&&r.setValue(t,n,i)},ts.prototype.setOptional=function(t,e,n){const i=e[n];void 0!==i&&this.setValue(t,n,i)},ts.upload=function(t,e,n,i){for(let r=0,s=e.length;r!==s;++r){const s=e[r],a=n[s.id];!1!==a.needsUpdate&&s.setValue(t,a.value,i)}},ts.seqWithValue=function(t,e){const n=[];for(let i=0,r=t.length;i!==r;++i){const r=t[i];r.id in e&&n.push(r)}return n};let ns=0;function is(t){switch(t){case X:return["Linear","( value )"];case J:return["sRGB","( value )"];default:return console.warn("THREE.WebGLProgram: Unsupported encoding:",t),["Linear","( value )"]}}function rs(t,e,n){const i=t.getShaderParameter(e,35713),r=t.getShaderInfoLog(e).trim();return i&&""===r?"":n.toUpperCase()+"\n\n"+r+"\n\n"+function(t){const e=t.split("\n");for(let t=0;t<e.length;t++)e[t]=t+1+": "+e[t];return e.join("\n")}(t.getShaderSource(e))}function ss(t,e){const n=is(e);return"vec4 "+t+"( vec4 value ) { return "+n[0]+"ToLinear"+n[1]+"; }"}function as(t,e){const n=is(e);return"vec4 "+t+"( vec4 value ) { return LinearTo"+n[0]+n[1]+"; }"}function os(t,e){let n;switch(e){case 1:n="Linear";break;case 2:n="Reinhard";break;case 3:n="OptimizedCineon";break;case 4:n="ACESFilmic";break;case 5:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}function ls(t){return""!==t}function cs(t,e){return t.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function hs(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const us=/^[ \t]*#include +<([\w\d./]+)>/gm;function ds(t){return t.replace(us,ps)}function ps(t,e){const n=ai[e];if(void 0===n)throw new Error("Can not resolve #include <"+e+">");return ds(n)}const ms=/#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,fs=/#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 gs(t){return t.replace(fs,ys).replace(ms,vs)}function vs(t,e,n,i){return console.warn("WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead."),ys(t,e,n,i)}function ys(t,e,n,i){let r="";for(let t=parseInt(e);t<parseInt(n);t++)r+=i.replace(/\[\s*i\s*\]/g,"[ "+t+" ]").replace(/UNROLLED_LOOP_INDEX/g,t);return r}function xs(t){let e="precision "+t.precision+" float;\nprecision "+t.precision+" int;";return"highp"===t.precision?e+="\n#define HIGH_PRECISION":"mediump"===t.precision?e+="\n#define MEDIUM_PRECISION":"lowp"===t.precision&&(e+="\n#define LOW_PRECISION"),e}function _s(t,e,n,i){const a=t.getContext(),o=n.defines;let h=n.vertexShader,u=n.fragmentShader;const d=function(t){let e="SHADOWMAP_TYPE_BASIC";return 1===t.shadowMapType?e="SHADOWMAP_TYPE_PCF":2===t.shadowMapType?e="SHADOWMAP_TYPE_PCF_SOFT":3===t.shadowMapType&&(e="SHADOWMAP_TYPE_VSM"),e}(n),p=function(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case r:case s:e="ENVMAP_TYPE_CUBE";break;case l:case c:e="ENVMAP_TYPE_CUBE_UV"}return e}(n),m=function(t){let e="ENVMAP_MODE_REFLECTION";if(t.envMap)switch(t.envMapMode){case s:case c:e="ENVMAP_MODE_REFRACTION"}return e}(n),f=function(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case 0:e="ENVMAP_BLENDING_MULTIPLY";break;case 1:e="ENVMAP_BLENDING_MIX";break;case 2:e="ENVMAP_BLENDING_ADD"}return e}(n),g=n.isWebGL2?"":function(t){return[t.extensionDerivatives||t.envMapCubeUV||t.bumpMap||t.tangentSpaceNormalMap||t.clearcoatNormalMap||t.flatShading||"physical"===t.shaderID?"#extension GL_OES_standard_derivatives : enable":"",(t.extensionFragDepth||t.logarithmicDepthBuffer)&&t.rendererExtensionFragDepth?"#extension GL_EXT_frag_depth : enable":"",t.extensionDrawBuffers&&t.rendererExtensionDrawBuffers?"#extension GL_EXT_draw_buffers : require":"",(t.extensionShaderTextureLOD||t.envMap||t.transmission)&&t.rendererExtensionShaderTextureLod?"#extension GL_EXT_shader_texture_lod : enable":""].filter(ls).join("\n")}(n),v=function(t){const e=[];for(const n in t){const i=t[n];!1!==i&&e.push("#define "+n+" "+i)}return e.join("\n")}(o),y=a.createProgram();let x,_,b=n.glslVersion?"#version "+n.glslVersion+"\n":"";n.isRawShaderMaterial?(x=[v].filter(ls).join("\n"),x.length>0&&(x+="\n"),_=[g,v].filter(ls).join("\n"),_.length>0&&(_+="\n")):(x=[xs(n),"#define SHADER_NAME "+n.shaderName,v,n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define MAX_BONES "+n.maxBones,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+m:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMap&&n.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",n.normalMap&&n.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.displacementMap&&n.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",n.specularColorMap?"#define USE_SPECULARCOLORMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEENCOLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",n.vertexTangents?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUvs?"#define USE_UV":"",n.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.useVertexTexture?"#define BONE_TEXTURE":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphTargets&&n.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",n.morphTargets&&n.isWebGL2?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+d:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.logarithmicDepthBuffer&&n.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(ls).join("\n"),_=[g,xs(n),"#define SHADER_NAME "+n.shaderName,v,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+p:"",n.envMap?"#define "+m:"",n.envMap?"#define "+f:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMap&&n.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",n.normalMap&&n.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",n.specularColorMap?"#define USE_SPECULARCOLORMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEENCOLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUvs?"#define USE_UV":"",n.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+d:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.logarithmicDepthBuffer&&n.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"",(n.extensionShaderTextureLOD||n.envMap)&&n.rendererExtensionShaderTextureLod?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?ai.tonemapping_pars_fragment:"",0!==n.toneMapping?os("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.format===T?"#define OPAQUE":"",ai.encodings_pars_fragment,n.map?ss("mapTexelToLinear",n.mapEncoding):"",n.matcap?ss("matcapTexelToLinear",n.matcapEncoding):"",n.envMap?ss("envMapTexelToLinear",n.envMapEncoding):"",n.emissiveMap?ss("emissiveMapTexelToLinear",n.emissiveMapEncoding):"",n.specularColorMap?ss("specularColorMapTexelToLinear",n.specularColorMapEncoding):"",n.sheenColorMap?ss("sheenColorMapTexelToLinear",n.sheenColorMapEncoding):"",n.lightMap?ss("lightMapTexelToLinear",n.lightMapEncoding):"",as("linearToOutputTexel",n.outputEncoding),n.depthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(ls).join("\n")),h=ds(h),h=cs(h,n),h=hs(h,n),u=ds(u),u=cs(u,n),u=hs(u,n),h=gs(h),u=gs(u),n.isWebGL2&&!0!==n.isRawShaderMaterial&&(b="#version 300 es\n",x=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+x,_=["#define varying in",n.glslVersion===K?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===K?"":"#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"+_);const M=b+_+u,w=es(a,35633,b+x+h),S=es(a,35632,M);if(a.attachShader(y,w),a.attachShader(y,S),void 0!==n.index0AttributeName?a.bindAttribLocation(y,0,n.index0AttributeName):!0===n.morphTargets&&a.bindAttribLocation(y,0,"position"),a.linkProgram(y),t.debug.checkShaderErrors){const t=a.getProgramInfoLog(y).trim(),e=a.getShaderInfoLog(w).trim(),n=a.getShaderInfoLog(S).trim();let i=!0,r=!0;if(!1===a.getProgramParameter(y,35714)){i=!1;const e=rs(a,w,"vertex"),n=rs(a,S,"fragment");console.error("THREE.WebGLProgram: Shader Error "+a.getError()+" - VALIDATE_STATUS "+a.getProgramParameter(y,35715)+"\n\nProgram Info Log: "+t+"\n"+e+"\n"+n)}else""!==t?console.warn("THREE.WebGLProgram: Program Info Log:",t):""!==e&&""!==n||(r=!1);r&&(this.diagnostics={runnable:i,programLog:t,vertexShader:{log:e,prefix:x},fragmentShader:{log:n,prefix:_}})}let E,A;return a.deleteShader(w),a.deleteShader(S),this.getUniforms=function(){return void 0===E&&(E=new ts(a,y)),E},this.getAttributes=function(){return void 0===A&&(A=function(t,e){const n={},i=t.getProgramParameter(e,35721);for(let r=0;r<i;r++){const i=t.getActiveAttrib(e,r),s=i.name;let a=1;35674===i.type&&(a=2),35675===i.type&&(a=3),35676===i.type&&(a=4),n[s]={type:i.type,location:t.getAttribLocation(e,s),locationSize:a}}return n}(a,y)),A},this.destroy=function(){i.releaseStatesOfProgram(this),a.deleteProgram(y),this.program=void 0},this.name=n.shaderName,this.id=ns++,this.cacheKey=e,this.usedTimes=1,this.program=y,this.vertexShader=w,this.fragmentShader=S,this}let bs=0;class Ms{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t){const e=t.vertexShader,n=t.fragmentShader,i=this._getShaderStage(e),r=this._getShaderStage(n),s=this._getShaderCacheForMaterial(t);return!1===s.has(i)&&(s.add(i),i.usedTimes++),!1===s.has(r)&&(s.add(r),r.usedTimes++),this}remove(t){const e=this.materialCache.get(t);for(const t of e)t.usedTimes--,0===t.usedTimes&&this.shaderCache.delete(t);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;return!1===e.has(t)&&e.set(t,new Set),e.get(t)}_getShaderStage(t){const e=this.shaderCache;if(!1===e.has(t)){const n=new ws;e.set(t,n)}return e.get(t)}}class ws{constructor(){this.id=bs++,this.usedTimes=0}}function Ss(t,e,n,i,r,s,a){const o=new ge,h=new Ms,u=[],d=r.isWebGL2,p=r.logarithmicDepthBuffer,m=r.floatVertexTextures,f=r.maxVertexUniforms,g=r.vertexTextures;let v=r.precision;const y={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",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 _(t){let e;return t&&t.isTexture?e=t.encoding:t&&t.isWebGLRenderTarget?(console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead."),e=t.texture.encoding):e=X,d&&t&&t.isTexture&&t.format===E&&t.type===x&&t.encoding===J&&(e=X),e}return{getParameters:function(s,o,u,x,b){const M=x.fog,w=s.isMeshStandardMaterial?x.environment:null,S=(s.isMeshStandardMaterial?n:e).get(s.envMap||w),T=y[s.type],E=b.isSkinnedMesh?function(t){const e=t.skeleton.bones;if(m)return 1024;{const t=f,n=Math.floor((t-20)/4),i=Math.min(n,e.length);return i<e.length?(console.warn("THREE.WebGLRenderer: Skeleton has "+e.length+" bones. This GPU supports "+i+"."),0):i}}(b):0;let A,L,R,C;if(null!==s.precision&&(v=r.getMaxPrecision(s.precision),v!==s.precision&&console.warn("THREE.WebGLProgram.getParameters:",s.precision,"not supported, using",v,"instead.")),T){const t=li[T];A=t.vertexShader,L=t.fragmentShader}else A=s.vertexShader,L=s.fragmentShader,h.update(s),R=h.getVertexShaderID(s),C=h.getFragmentShaderID(s);const P=t.getRenderTarget(),D=s.alphaTest>0,I=s.clearcoat>0;return{isWebGL2:d,shaderID:T,shaderName:s.type,vertexShader:A,fragmentShader:L,defines:s.defines,customVertexShaderID:R,customFragmentShaderID:C,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:v,instancing:!0===b.isInstancedMesh,instancingColor:!0===b.isInstancedMesh&&null!==b.instanceColor,supportsVertexTextures:g,outputEncoding:null!==P?_(P.texture):t.outputEncoding,map:!!s.map,mapEncoding:_(s.map),matcap:!!s.matcap,matcapEncoding:_(s.matcap),envMap:!!S,envMapMode:S&&S.mapping,envMapEncoding:_(S),envMapCubeUV:!!S&&(S.mapping===l||S.mapping===c),lightMap:!!s.lightMap,lightMapEncoding:_(s.lightMap),aoMap:!!s.aoMap,emissiveMap:!!s.emissiveMap,emissiveMapEncoding:_(s.emissiveMap),bumpMap:!!s.bumpMap,normalMap:!!s.normalMap,objectSpaceNormalMap:1===s.normalMapType,tangentSpaceNormalMap:0===s.normalMapType,clearcoat:I,clearcoatMap:I&&!!s.clearcoatMap,clearcoatRoughnessMap:I&&!!s.clearcoatRoughnessMap,clearcoatNormalMap:I&&!!s.clearcoatNormalMap,displacementMap:!!s.displacementMap,roughnessMap:!!s.roughnessMap,metalnessMap:!!s.metalnessMap,specularMap:!!s.specularMap,specularIntensityMap:!!s.specularIntensityMap,specularColorMap:!!s.specularColorMap,specularColorMapEncoding:_(s.specularColorMap),alphaMap:!!s.alphaMap,alphaTest:D,gradientMap:!!s.gradientMap,sheen:s.sheen>0,sheenColorMap:!!s.sheenColorMap,sheenColorMapEncoding:_(s.sheenColorMap),sheenRoughnessMap:!!s.sheenRoughnessMap,transmission:s.transmission>0,transmissionMap:!!s.transmissionMap,thicknessMap:!!s.thicknessMap,combine:s.combine,vertexTangents:!!s.normalMap&&!!b.geometry&&!!b.geometry.attributes.tangent,vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!b.geometry&&!!b.geometry.attributes.color&&4===b.geometry.attributes.color.itemSize,vertexUvs:!!(s.map||s.bumpMap||s.normalMap||s.specularMap||s.alphaMap||s.emissiveMap||s.roughnessMap||s.metalnessMap||s.clearcoatMap||s.clearcoatRoughnessMap||s.clearcoatNormalMap||s.displacementMap||s.transmissionMap||s.thicknessMap||s.specularIntensityMap||s.specularColorMap||s.sheenColorMap||s.sheenRoughnessMap),uvsVertexOnly:!(s.map||s.bumpMap||s.normalMap||s.specularMap||s.alphaMap||s.emissiveMap||s.roughnessMap||s.metalnessMap||s.clearcoatNormalMap||s.transmission>0||s.transmissionMap||s.thicknessMap||s.specularIntensityMap||s.specularColorMap||s.sheen>0||s.sheenColorMap||s.sheenRoughnessMap||!s.displacementMap),fog:!!M,useFog:s.fog,fogExp2:M&&M.isFogExp2,flatShading:!!s.flatShading,sizeAttenuation:s.sizeAttenuation,logarithmicDepthBuffer:p,skinning:!0===b.isSkinnedMesh&&E>0,maxBones:E,useVertexTexture:m,morphTargets:!!b.geometry&&!!b.geometry.morphAttributes.position,morphNormals:!!b.geometry&&!!b.geometry.morphAttributes.normal,morphTargetsCount:b.geometry&&b.geometry.morphAttributes.position?b.geometry.morphAttributes.position.length:0,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,format:s.format,dithering:s.dithering,shadowMapEnabled:t.shadowMap.enabled&&u.length>0,shadowMapType:t.shadowMap.type,toneMapping:s.toneMapped?t.toneMapping:0,physicallyCorrectLights:t.physicallyCorrectLights,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:1===s.side,depthPacking:void 0!==s.depthPacking&&s.depthPacking,index0AttributeName:s.index0AttributeName,extensionDerivatives:s.extensions&&s.extensions.derivatives,extensionFragDepth:s.extensions&&s.extensions.fragDepth,extensionDrawBuffers:s.extensions&&s.extensions.drawBuffers,extensionShaderTextureLOD:s.extensions&&s.extensions.shaderTextureLOD,rendererExtensionFragDepth:d||i.has("EXT_frag_depth"),rendererExtensionDrawBuffers:d||i.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:d||i.has("EXT_shader_texture_lod"),customProgramCacheKey:s.customProgramCacheKey()}},getProgramCacheKey:function(e){const n=[];if(e.shaderID?n.push(e.shaderID):(n.push(e.customVertexShaderID),n.push(e.customFragmentShaderID)),void 0!==e.defines)for(const t in e.defines)n.push(t),n.push(e.defines[t]);return!1===e.isRawShaderMaterial&&(!function(t,e){t.push(e.precision),t.push(e.outputEncoding),t.push(e.mapEncoding),t.push(e.matcapEncoding),t.push(e.envMapMode),t.push(e.envMapEncoding),t.push(e.lightMapEncoding),t.push(e.emissiveMapEncoding),t.push(e.combine),t.push(e.vertexUvs),t.push(e.fogExp2),t.push(e.sizeAttenuation),t.push(e.maxBones),t.push(e.morphTargetsCount),t.push(e.numDirLights),t.push(e.numPointLights),t.push(e.numSpotLights),t.push(e.numHemiLights),t.push(e.numRectAreaLights),t.push(e.numDirLightShadows),t.push(e.numPointLightShadows),t.push(e.numSpotLightShadows),t.push(e.shadowMapType),t.push(e.toneMapping),t.push(e.numClippingPlanes),t.push(e.numClipIntersection),t.push(e.format),t.push(e.specularColorMapEncoding),t.push(e.sheenColorMapEncoding)}(n,e),function(t,e){o.disableAll(),e.isWebGL2&&o.enable(0);e.supportsVertexTextures&&o.enable(1);e.instancing&&o.enable(2);e.instancingColor&&o.enable(3);e.map&&o.enable(4);e.matcap&&o.enable(5);e.envMap&&o.enable(6);e.envMapCubeUV&&o.enable(7);e.lightMap&&o.enable(8);e.aoMap&&o.enable(9);e.emissiveMap&&o.enable(10);e.bumpMap&&o.enable(11);e.normalMap&&o.enable(12);e.objectSpaceNormalMap&&o.enable(13);e.tangentSpaceNormalMap&&o.enable(14);e.clearcoat&&o.enable(15);e.clearcoatMap&&o.enable(16);e.clearcoatRoughnessMap&&o.enable(17);e.clearcoatNormalMap&&o.enable(18);e.displacementMap&&o.enable(19);e.specularMap&&o.enable(20);e.roughnessMap&&o.enable(21);e.metalnessMap&&o.enable(22);e.gradientMap&&o.enable(23);e.alphaMap&&o.enable(24);e.alphaTest&&o.enable(25);e.vertexColors&&o.enable(26);e.vertexAlphas&&o.enable(27);e.vertexUvs&&o.enable(28);e.vertexTangents&&o.enable(29);e.uvsVertexOnly&&o.enable(30);e.fog&&o.enable(31);t.push(o.mask),o.disableAll(),e.useFog&&o.enable(0);e.flatShading&&o.enable(1);e.logarithmicDepthBuffer&&o.enable(2);e.skinning&&o.enable(3);e.useVertexTexture&&o.enable(4);e.morphTargets&&o.enable(5);e.morphNormals&&o.enable(6);e.premultipliedAlpha&&o.enable(7);e.shadowMapEnabled&&o.enable(8);e.physicallyCorrectLights&&o.enable(9);e.doubleSided&&o.enable(10);e.flipSided&&o.enable(11);e.depthPacking&&o.enable(12);e.dithering&&o.enable(13);e.specularIntensityMap&&o.enable(14);e.specularColorMap&&o.enable(15);e.transmission&&o.enable(16);e.transmissionMap&&o.enable(17);e.thicknessMap&&o.enable(18);e.sheen&&o.enable(19);e.sheenColorMap&&o.enable(20);e.sheenRoughnessMap&&o.enable(21);t.push(o.mask)}(n,e),n.push(t.outputEncoding)),n.push(e.customProgramCacheKey),n.join()},getUniforms:function(t){const e=y[t.type];let n;if(e){const t=li[e];n=kn.clone(t.uniforms)}else n=t.uniforms;return n},acquireProgram:function(e,n){let i;for(let t=0,e=u.length;t<e;t++){const e=u[t];if(e.cacheKey===n){i=e,++i.usedTimes;break}}return void 0===i&&(i=new _s(t,n,e,s),u.push(i)),i},releaseProgram:function(t){if(0==--t.usedTimes){const e=u.indexOf(t);u[e]=u[u.length-1],u.pop(),t.destroy()}},releaseShaderCache:function(t){h.remove(t)},programs:u,dispose:function(){h.dispose()}}}function Ts(){let t=new WeakMap;return{get:function(e){let n=t.get(e);return void 0===n&&(n={},t.set(e,n)),n},remove:function(e){t.delete(e)},update:function(e,n,i){t.get(e)[n]=i},dispose:function(){t=new WeakMap}}}function Es(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function As(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function Ls(){const t=[];let e=0;const n=[],i=[],r=[];function s(n,i,r,s,a,o){let l=t[e];return void 0===l?(l={id:n.id,object:n,geometry:i,material:r,groupOrder:s,renderOrder:n.renderOrder,z:a,group:o},t[e]=l):(l.id=n.id,l.object=n,l.geometry=i,l.material=r,l.groupOrder=s,l.renderOrder=n.renderOrder,l.z=a,l.group=o),e++,l}return{opaque:n,transmissive:i,transparent:r,init:function(){e=0,n.length=0,i.length=0,r.length=0},push:function(t,e,a,o,l,c){const h=s(t,e,a,o,l,c);a.transmission>0?i.push(h):!0===a.transparent?r.push(h):n.push(h)},unshift:function(t,e,a,o,l,c){const h=s(t,e,a,o,l,c);a.transmission>0?i.unshift(h):!0===a.transparent?r.unshift(h):n.unshift(h)},finish:function(){for(let n=e,i=t.length;n<i;n++){const e=t[n];if(null===e.id)break;e.id=null,e.object=null,e.geometry=null,e.material=null,e.group=null}},sort:function(t,e){n.length>1&&n.sort(t||Es),i.length>1&&i.sort(e||As),r.length>1&&r.sort(e||As)}}}function Rs(){let t=new WeakMap;return{get:function(e,n){let i;return!1===t.has(e)?(i=new Ls,t.set(e,[i])):n>=t.get(e).length?(i=new Ls,t.get(e).push(i)):i=t.get(e)[n],i},dispose:function(){t=new WeakMap}}}function Cs(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let n;switch(e.type){case"DirectionalLight":n={direction:new Lt,color:new Ze};break;case"SpotLight":n={position:new Lt,direction:new Lt,color:new Ze,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Lt,color:new Ze,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Lt,skyColor:new Ze,groundColor:new Ze};break;case"RectAreaLight":n={color:new Ze,position:new Lt,halfWidth:new Lt,halfHeight:new Lt}}return t[e.id]=n,n}}}let Ps=0;function Ds(t,e){return(e.castShadow?1:0)-(t.castShadow?1:0)}function Is(t,e){const n=new Cs,i=function(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let n;switch(e.type){case"DirectionalLight":case"SpotLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new dt};break;case"PointLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new dt,shadowCameraNear:1,shadowCameraFar:1e3}}return t[e.id]=n,n}}}(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadow:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]};for(let t=0;t<9;t++)r.probe.push(new Lt);const s=new Lt,a=new se,o=new se;return{setup:function(s,a){let o=0,l=0,c=0;for(let t=0;t<9;t++)r.probe[t].set(0,0,0);let h=0,u=0,d=0,p=0,m=0,f=0,g=0,v=0;s.sort(Ds);const y=!0!==a?Math.PI:1;for(let t=0,e=s.length;t<e;t++){const e=s[t],a=e.color,x=e.intensity,_=e.distance,b=e.shadow&&e.shadow.map?e.shadow.map.texture:null;if(e.isAmbientLight)o+=a.r*x*y,l+=a.g*x*y,c+=a.b*x*y;else if(e.isLightProbe)for(let t=0;t<9;t++)r.probe[t].addScaledVector(e.sh.coefficients[t],x);else if(e.isDirectionalLight){const t=n.get(e);if(t.color.copy(e.color).multiplyScalar(e.intensity*y),e.castShadow){const t=e.shadow,n=i.get(e);n.shadowBias=t.bias,n.shadowNormalBias=t.normalBias,n.shadowRadius=t.radius,n.shadowMapSize=t.mapSize,r.directionalShadow[h]=n,r.directionalShadowMap[h]=b,r.directionalShadowMatrix[h]=e.shadow.matrix,f++}r.directional[h]=t,h++}else if(e.isSpotLight){const t=n.get(e);if(t.position.setFromMatrixPosition(e.matrixWorld),t.color.copy(a).multiplyScalar(x*y),t.distance=_,t.coneCos=Math.cos(e.angle),t.penumbraCos=Math.cos(e.angle*(1-e.penumbra)),t.decay=e.decay,e.castShadow){const t=e.shadow,n=i.get(e);n.shadowBias=t.bias,n.shadowNormalBias=t.normalBias,n.shadowRadius=t.radius,n.shadowMapSize=t.mapSize,r.spotShadow[d]=n,r.spotShadowMap[d]=b,r.spotShadowMatrix[d]=e.shadow.matrix,v++}r.spot[d]=t,d++}else if(e.isRectAreaLight){const t=n.get(e);t.color.copy(a).multiplyScalar(x),t.halfWidth.set(.5*e.width,0,0),t.halfHeight.set(0,.5*e.height,0),r.rectArea[p]=t,p++}else if(e.isPointLight){const t=n.get(e);if(t.color.copy(e.color).multiplyScalar(e.intensity*y),t.distance=e.distance,t.decay=e.decay,e.castShadow){const t=e.shadow,n=i.get(e);n.shadowBias=t.bias,n.shadowNormalBias=t.normalBias,n.shadowRadius=t.radius,n.shadowMapSize=t.mapSize,n.shadowCameraNear=t.camera.near,n.shadowCameraFar=t.camera.far,r.pointShadow[u]=n,r.pointShadowMap[u]=b,r.pointShadowMatrix[u]=e.shadow.matrix,g++}r.point[u]=t,u++}else if(e.isHemisphereLight){const t=n.get(e);t.skyColor.copy(e.color).multiplyScalar(x*y),t.groundColor.copy(e.groundColor).multiplyScalar(x*y),r.hemi[m]=t,m++}}p>0&&(e.isWebGL2||!0===t.has("OES_texture_float_linear")?(r.rectAreaLTC1=oi.LTC_FLOAT_1,r.rectAreaLTC2=oi.LTC_FLOAT_2):!0===t.has("OES_texture_half_float_linear")?(r.rectAreaLTC1=oi.LTC_HALF_1,r.rectAreaLTC2=oi.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),r.ambient[0]=o,r.ambient[1]=l,r.ambient[2]=c;const x=r.hash;x.directionalLength===h&&x.pointLength===u&&x.spotLength===d&&x.rectAreaLength===p&&x.hemiLength===m&&x.numDirectionalShadows===f&&x.numPointShadows===g&&x.numSpotShadows===v||(r.directional.length=h,r.spot.length=d,r.rectArea.length=p,r.point.length=u,r.hemi.length=m,r.directionalShadow.length=f,r.directionalShadowMap.length=f,r.pointShadow.length=g,r.pointShadowMap.length=g,r.spotShadow.length=v,r.spotShadowMap.length=v,r.directionalShadowMatrix.length=f,r.pointShadowMatrix.length=g,r.spotShadowMatrix.length=v,x.directionalLength=h,x.pointLength=u,x.spotLength=d,x.rectAreaLength=p,x.hemiLength=m,x.numDirectionalShadows=f,x.numPointShadows=g,x.numSpotShadows=v,r.version=Ps++)},setupView:function(t,e){let n=0,i=0,l=0,c=0,h=0;const u=e.matrixWorldInverse;for(let e=0,d=t.length;e<d;e++){const d=t[e];if(d.isDirectionalLight){const t=r.directional[n];t.direction.setFromMatrixPosition(d.matrixWorld),s.setFromMatrixPosition(d.target.matrixWorld),t.direction.sub(s),t.direction.transformDirection(u),n++}else if(d.isSpotLight){const t=r.spot[l];t.position.setFromMatrixPosition(d.matrixWorld),t.position.applyMatrix4(u),t.direction.setFromMatrixPosition(d.matrixWorld),s.setFromMatrixPosition(d.target.matrixWorld),t.direction.sub(s),t.direction.transformDirection(u),l++}else if(d.isRectAreaLight){const t=r.rectArea[c];t.position.setFromMatrixPosition(d.matrixWorld),t.position.applyMatrix4(u),o.identity(),a.copy(d.matrixWorld),a.premultiply(u),o.extractRotation(a),t.halfWidth.set(.5*d.width,0,0),t.halfHeight.set(0,.5*d.height,0),t.halfWidth.applyMatrix4(o),t.halfHeight.applyMatrix4(o),c++}else if(d.isPointLight){const t=r.point[i];t.position.setFromMatrixPosition(d.matrixWorld),t.position.applyMatrix4(u),i++}else if(d.isHemisphereLight){const t=r.hemi[h];t.direction.setFromMatrixPosition(d.matrixWorld),t.direction.transformDirection(u),t.direction.normalize(),h++}}},state:r}}function Ns(t,e){const n=new Is(t,e),i=[],r=[];return{init:function(){i.length=0,r.length=0},state:{lightsArray:i,shadowsArray:r,lights:n},setupLights:function(t){n.setup(i,t)},setupLightsView:function(t){n.setupView(i,t)},pushLight:function(t){i.push(t)},pushShadow:function(t){r.push(t)}}}function zs(t,e){let n=new WeakMap;return{get:function(i,r=0){let s;return!1===n.has(i)?(s=new Ns(t,e),n.set(i,[s])):r>=n.get(i).length?(s=new Ns(t,e),n.get(i).push(s)):s=n.get(i)[r],s},dispose:function(){n=new WeakMap}}}class Bs extends Ve{constructor(t){super(),this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!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}}Bs.prototype.isMeshDepthMaterial=!0;class Fs extends Ve{constructor(t){super(),this.type="MeshDistanceMaterial",this.referencePosition=new Lt,this.nearDistance=1,this.farDistance=1e3,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.fog=!1,this.setValues(t)}copy(t){return super.copy(t),this.referencePosition.copy(t.referencePosition),this.nearDistance=t.nearDistance,this.farDistance=t.farDistance,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}Fs.prototype.isMeshDistanceMaterial=!0;function Os(t,e,n){let i=new ni;const r=new dt,s=new dt,a=new wt,o=new Bs({depthPacking:3201}),l=new Fs,c={},h=n.maxTextureSize,u={0:1,1:0,2:2},d=new Vn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new dt},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),m=d.clone();m.defines.HORIZONTAL_PASS=1;const f=new xn;f.setAttribute("position",new tn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Fn(f,d),y=this;function x(n,i){const r=e.update(v);d.defines.VSM_SAMPLES!==n.blurSamples&&(d.defines.VSM_SAMPLES=n.blurSamples,m.defines.VSM_SAMPLES=n.blurSamples,d.needsUpdate=!0,m.needsUpdate=!0),d.uniforms.shadow_pass.value=n.map.texture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,t.setRenderTarget(n.mapPass),t.clear(),t.renderBufferDirect(i,null,r,d,v,null),m.uniforms.shadow_pass.value=n.mapPass.texture,m.uniforms.resolution.value=n.mapSize,m.uniforms.radius.value=n.radius,t.setRenderTarget(n.map),t.clear(),t.renderBufferDirect(i,null,r,m,v,null)}function _(e,n,i,r,s,a,h){let d=null;const p=!0===r.isPointLight?e.customDistanceMaterial:e.customDepthMaterial;if(d=void 0!==p?p:!0===r.isPointLight?l:o,t.localClippingEnabled&&!0===i.clipShadows&&0!==i.clippingPlanes.length||i.displacementMap&&0!==i.displacementScale||i.alphaMap&&i.alphaTest>0){const t=d.uuid,e=i.uuid;let n=c[t];void 0===n&&(n={},c[t]=n);let r=n[e];void 0===r&&(r=d.clone(),n[e]=r),d=r}return d.visible=i.visible,d.wireframe=i.wireframe,d.side=3===h?null!==i.shadowSide?i.shadowSide:i.side:null!==i.shadowSide?i.shadowSide:u[i.side],d.alphaMap=i.alphaMap,d.alphaTest=i.alphaTest,d.clipShadows=i.clipShadows,d.clippingPlanes=i.clippingPlanes,d.clipIntersection=i.clipIntersection,d.displacementMap=i.displacementMap,d.displacementScale=i.displacementScale,d.displacementBias=i.displacementBias,d.wireframeLinewidth=i.wireframeLinewidth,d.linewidth=i.linewidth,!0===r.isPointLight&&!0===d.isMeshDistanceMaterial&&(d.referencePosition.setFromMatrixPosition(r.matrixWorld),d.nearDistance=s,d.farDistance=a),d}function b(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===o)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=e.update(n),r=n.material;if(Array.isArray(r)){const e=i.groups;for(let l=0,c=e.length;l<c;l++){const c=e[l],h=r[c.materialIndex];if(h&&h.visible){const e=_(n,0,h,a,s.near,s.far,o);t.renderBufferDirect(s,null,i,e,n,c)}}}else if(r.visible){const e=_(n,0,r,a,s.near,s.far,o);t.renderBufferDirect(s,null,i,e,n,null)}}const l=n.children;for(let t=0,e=l.length;t<e;t++)b(l[t],r,s,a,o)}this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1,this.render=function(e,n,o){if(!1===y.enabled)return;if(!1===y.autoUpdate&&!1===y.needsUpdate)return;if(0===e.length)return;const l=t.getRenderTarget(),c=t.getActiveCubeFace(),u=t.getActiveMipmapLevel(),d=t.state;d.setBlending(0),d.buffers.color.setClear(1,1,1,1),d.buffers.depth.setTest(!0),d.setScissorTest(!1);for(let l=0,c=e.length;l<c;l++){const c=e[l],u=c.shadow;if(void 0===u){console.warn("THREE.WebGLShadowMap:",c,"has no shadow.");continue}if(!1===u.autoUpdate&&!1===u.needsUpdate)continue;r.copy(u.mapSize);const m=u.getFrameExtents();if(r.multiply(m),s.copy(u.mapSize),(r.x>h||r.y>h)&&(r.x>h&&(s.x=Math.floor(h/m.x),r.x=s.x*m.x,u.mapSize.x=s.x),r.y>h&&(s.y=Math.floor(h/m.y),r.y=s.y*m.y,u.mapSize.y=s.y)),null===u.map&&!u.isPointLightShadow&&3===this.type){const t={minFilter:g,magFilter:g,format:E};u.map=new St(r.x,r.y,t),u.map.texture.name=c.name+".shadowMap",u.mapPass=new St(r.x,r.y,t),u.camera.updateProjectionMatrix()}if(null===u.map){const t={minFilter:p,magFilter:p,format:E};u.map=new St(r.x,r.y,t),u.map.texture.name=c.name+".shadowMap",u.camera.updateProjectionMatrix()}t.setRenderTarget(u.map),t.clear();const f=u.getViewportCount();for(let t=0;t<f;t++){const e=u.getViewport(t);a.set(s.x*e.x,s.y*e.y,s.x*e.z,s.y*e.w),d.viewport(a),u.updateMatrices(c,t),i=u.getFrustum(),b(n,o,u.camera,c,this.type)}u.isPointLightShadow||3!==this.type||x(u,o),u.needsUpdate=!1}y.needsUpdate=!1,t.setRenderTarget(l,c,u)}}function Us(t,e,i){const r=i.isWebGL2;const s=new function(){let e=!1;const n=new wt;let i=null;const r=new wt(0,0,0,0);return{setMask:function(n){i===n||e||(t.colorMask(n,n,n,n),i=n)},setLocked:function(t){e=t},setClear:function(e,i,s,a,o){!0===o&&(e*=a,i*=a,s*=a),n.set(e,i,s,a),!1===r.equals(n)&&(t.clearColor(e,i,s,a),r.copy(n))},reset:function(){e=!1,i=null,r.set(-1,0,0,0)}}},a=new function(){let e=!1,n=null,i=null,r=null;return{setTest:function(t){t?F(2929):O(2929)},setMask:function(i){n===i||e||(t.depthMask(i),n=i)},setFunc:function(e){if(i!==e){if(e)switch(e){case 0:t.depthFunc(512);break;case 1:t.depthFunc(519);break;case 2:t.depthFunc(513);break;default:t.depthFunc(515);break;case 4:t.depthFunc(514);break;case 5:t.depthFunc(518);break;case 6:t.depthFunc(516);break;case 7:t.depthFunc(517)}else t.depthFunc(515);i=e}},setLocked:function(t){e=t},setClear:function(e){r!==e&&(t.clearDepth(e),r=e)},reset:function(){e=!1,n=null,i=null,r=null}}},o=new function(){let e=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,c=null;return{setTest:function(t){e||(t?F(2960):O(2960))},setMask:function(i){n===i||e||(t.stencilMask(i),n=i)},setFunc:function(e,n,a){i===e&&r===n&&s===a||(t.stencilFunc(e,n,a),i=e,r=n,s=a)},setOp:function(e,n,i){a===e&&o===n&&l===i||(t.stencilOp(e,n,i),a=e,o=n,l=i)},setLocked:function(t){e=t},setClear:function(e){c!==e&&(t.clearStencil(e),c=e)},reset:function(){e=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,c=null}}};let l={},c={},h=null,u=!1,d=null,p=null,m=null,f=null,g=null,v=null,y=null,x=!1,_=null,b=null,M=null,w=null,S=null;const T=t.getParameter(35661);let E=!1,A=0;const L=t.getParameter(7938);-1!==L.indexOf("WebGL")?(A=parseFloat(/^WebGL (\d)/.exec(L)[1]),E=A>=1):-1!==L.indexOf("OpenGL ES")&&(A=parseFloat(/^OpenGL ES (\d)/.exec(L)[1]),E=A>=2);let R=null,C={};const P=t.getParameter(3088),D=t.getParameter(2978),I=(new wt).fromArray(P),N=(new wt).fromArray(D);function z(e,n,i){const r=new Uint8Array(4),s=t.createTexture();t.bindTexture(e,s),t.texParameteri(e,10241,9728),t.texParameteri(e,10240,9728);for(let e=0;e<i;e++)t.texImage2D(n+e,0,6408,1,1,0,6408,5121,r);return s}const B={};function F(e){!0!==l[e]&&(t.enable(e),l[e]=!0)}function O(e){!1!==l[e]&&(t.disable(e),l[e]=!1)}B[3553]=z(3553,3553,1),B[34067]=z(34067,34069,6),s.setClear(0,0,0,1),a.setClear(1),o.setClear(0),F(2929),a.setFunc(3),k(!1),V(1),F(2884),G(0);const U={[n]:32774,101:32778,102:32779};if(r)U[103]=32775,U[104]=32776;else{const t=e.get("EXT_blend_minmax");null!==t&&(U[103]=t.MIN_EXT,U[104]=t.MAX_EXT)}const H={200:0,201:1,202:768,204:770,210:776,208:774,206:772,203:769,205:771,209:775,207:773};function G(e,i,r,s,a,o,l,c){if(0!==e){if(!1===u&&(F(3042),u=!0),5===e)a=a||i,o=o||r,l=l||s,i===p&&a===g||(t.blendEquationSeparate(U[i],U[a]),p=i,g=a),r===m&&s===f&&o===v&&l===y||(t.blendFuncSeparate(H[r],H[s],H[o],H[l]),m=r,f=s,v=o,y=l),d=e,x=null;else if(e!==d||c!==x){if(p===n&&g===n||(t.blendEquation(32774),p=n,g=n),c)switch(e){case 1:t.blendFuncSeparate(1,771,1,771);break;case 2:t.blendFunc(1,1);break;case 3:t.blendFuncSeparate(0,0,769,771);break;case 4:t.blendFuncSeparate(0,768,0,770);break;default:console.error("THREE.WebGLState: Invalid blending: ",e)}else switch(e){case 1:t.blendFuncSeparate(770,771,1,771);break;case 2:t.blendFunc(770,1);break;case 3:t.blendFunc(0,769);break;case 4:t.blendFunc(0,768);break;default:console.error("THREE.WebGLState: Invalid blending: ",e)}m=null,f=null,v=null,y=null,d=e,x=c}}else!0===u&&(O(3042),u=!1)}function k(e){_!==e&&(e?t.frontFace(2304):t.frontFace(2305),_=e)}function V(e){0!==e?(F(2884),e!==b&&(1===e?t.cullFace(1029):2===e?t.cullFace(1028):t.cullFace(1032))):O(2884),b=e}function W(e,n,i){e?(F(32823),w===n&&S===i||(t.polygonOffset(n,i),w=n,S=i)):O(32823)}function j(e){void 0===e&&(e=33984+T-1),R!==e&&(t.activeTexture(e),R=e)}return{buffers:{color:s,depth:a,stencil:o},enable:F,disable:O,bindFramebuffer:function(e,n){return c[e]!==n&&(t.bindFramebuffer(e,n),c[e]=n,r&&(36009===e&&(c[36160]=n),36160===e&&(c[36009]=n)),!0)},useProgram:function(e){return h!==e&&(t.useProgram(e),h=e,!0)},setBlending:G,setMaterial:function(t,e){2===t.side?O(2884):F(2884);let n=1===t.side;e&&(n=!n),k(n),1===t.blending&&!1===t.transparent?G(0):G(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.premultipliedAlpha),a.setFunc(t.depthFunc),a.setTest(t.depthTest),a.setMask(t.depthWrite),s.setMask(t.colorWrite);const i=t.stencilWrite;o.setTest(i),i&&(o.setMask(t.stencilWriteMask),o.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),o.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),W(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),!0===t.alphaToCoverage?F(32926):O(32926)},setFlipSided:k,setCullFace:V,setLineWidth:function(e){e!==M&&(E&&t.lineWidth(e),M=e)},setPolygonOffset:W,setScissorTest:function(t){t?F(3089):O(3089)},activeTexture:j,bindTexture:function(e,n){null===R&&j();let i=C[R];void 0===i&&(i={type:void 0,texture:void 0},C[R]=i),i.type===e&&i.texture===n||(t.bindTexture(e,n||B[e]),i.type=e,i.texture=n)},unbindTexture:function(){const e=C[R];void 0!==e&&void 0!==e.type&&(t.bindTexture(e.type,null),e.type=void 0,e.texture=void 0)},compressedTexImage2D:function(){try{t.compressedTexImage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texImage2D:function(){try{t.texImage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texImage3D:function(){try{t.texImage3D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texStorage2D:function(){try{t.texStorage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texStorage3D:function(){try{t.texStorage3D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texSubImage2D:function(){try{t.texSubImage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texSubImage3D:function(){try{t.texSubImage3D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},compressedTexSubImage2D:function(){try{t.compressedTexSubImage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},scissor:function(e){!1===I.equals(e)&&(t.scissor(e.x,e.y,e.z,e.w),I.copy(e))},viewport:function(e){!1===N.equals(e)&&(t.viewport(e.x,e.y,e.z,e.w),N.copy(e))},reset:function(){t.disable(3042),t.disable(2884),t.disable(2929),t.disable(32823),t.disable(3089),t.disable(2960),t.disable(32926),t.blendEquation(32774),t.blendFunc(1,0),t.blendFuncSeparate(1,0,1,0),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(513),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(519,0,4294967295),t.stencilOp(7680,7680,7680),t.clearStencil(0),t.cullFace(1029),t.frontFace(2305),t.polygonOffset(0,0),t.activeTexture(33984),t.bindFramebuffer(36160,null),!0===r&&(t.bindFramebuffer(36009,null),t.bindFramebuffer(36008,null)),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),l={},R=null,C={},c={},h=null,u=!1,d=null,p=null,m=null,f=null,g=null,v=null,y=null,x=!1,_=null,b=null,M=null,w=null,S=null,I.set(0,0,t.canvas.width,t.canvas.height),N.set(0,0,t.canvas.width,t.canvas.height),s.reset(),a.reset(),o.reset()}}}function Hs(t,e,n,i,r,s,a){const o=r.isWebGL2,l=r.maxTextures,c=r.maxCubemapSize,x=r.maxTextureSize,R=r.maxSamples,C=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):void 0,P=new WeakMap;let D,I=!1;try{I="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(t){}function N(t,e){return I?new OffscreenCanvas(t,e):vt("canvas")}function z(t,e,n,i){let r=1;if((t.width>i||t.height>i)&&(r=i/Math.max(t.width,t.height)),r<1||!0===e){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const i=e?ht:Math.floor,s=i(r*t.width),a=i(r*t.height);void 0===D&&(D=N(s,a));const o=n?N(s,a):D;o.width=s,o.height=a;return o.getContext("2d").drawImage(t,0,0,s,a),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+t.width+"x"+t.height+") to ("+s+"x"+a+")."),o}return"data"in t&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+t.width+"x"+t.height+")."),t}return t}function B(t){return lt(t.width)&&lt(t.height)}function F(t,e){return t.generateMipmaps&&e&&t.minFilter!==p&&t.minFilter!==g}function O(e){t.generateMipmap(e)}function U(n,i,r,s){if(!1===o)return i;if(null!==n){if(void 0!==t[n])return t[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let a=i;return 6403===i&&(5126===r&&(a=33326),5131===r&&(a=33325),5121===r&&(a=33321)),6407===i&&(5126===r&&(a=34837),5131===r&&(a=34843),5121===r&&(a=32849)),6408===i&&(5126===r&&(a=34836),5131===r&&(a=34842),5121===r&&(a=s===J?35907:32856)),33325!==a&&33326!==a&&34842!==a&&34836!==a||e.get("EXT_color_buffer_float"),a}function H(t,e,n){return!0===F(t,n)||t.isFramebufferTexture&&t.minFilter!==p&&t.minFilter!==g?Math.log2(Math.max(e.width,e.height))+1:void 0!==t.mipmaps&&t.mipmaps.length>0?t.mipmaps.length:t.isCompressedTexture&&Array.isArray(t.image)?e.mipmaps.length:1}function G(t){return t===p||t===m||t===f?9728:9729}function k(e){const n=e.target;n.removeEventListener("dispose",k),function(e){const n=i.get(e);if(void 0===n.__webglInit)return;t.deleteTexture(n.__webglTexture),i.remove(e)}(n),n.isVideoTexture&&P.delete(n),a.memory.textures--}function V(e){const n=e.target;n.removeEventListener("dispose",V),function(e){const n=e.texture,r=i.get(e),s=i.get(n);if(!e)return;void 0!==s.__webglTexture&&(t.deleteTexture(s.__webglTexture),a.memory.textures--);e.depthTexture&&e.depthTexture.dispose();if(e.isWebGLCubeRenderTarget)for(let e=0;e<6;e++)t.deleteFramebuffer(r.__webglFramebuffer[e]),r.__webglDepthbuffer&&t.deleteRenderbuffer(r.__webglDepthbuffer[e]);else t.deleteFramebuffer(r.__webglFramebuffer),r.__webglDepthbuffer&&t.deleteRenderbuffer(r.__webglDepthbuffer),r.__webglMultisampledFramebuffer&&t.deleteFramebuffer(r.__webglMultisampledFramebuffer),r.__webglColorRenderbuffer&&t.deleteRenderbuffer(r.__webglColorRenderbuffer),r.__webglDepthRenderbuffer&&t.deleteRenderbuffer(r.__webglDepthRenderbuffer);if(e.isWebGLMultipleRenderTargets)for(let e=0,r=n.length;e<r;e++){const r=i.get(n[e]);r.__webglTexture&&(t.deleteTexture(r.__webglTexture),a.memory.textures--),i.remove(n[e])}i.remove(n),i.remove(e)}(n)}let W=0;function j(t,e){const r=i.get(t);if(t.isVideoTexture&&function(t){const e=a.render.frame;P.get(t)!==e&&(P.set(t,e),t.update())}(t),t.version>0&&r.__version!==t.version){const n=t.image;if(void 0===n)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined");else{if(!1!==n.complete)return void K(r,t,e);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}n.activeTexture(33984+e),n.bindTexture(3553,r.__webglTexture)}function q(e,r){const a=i.get(e);e.version>0&&a.__version!==e.version?function(e,i,r){if(6!==i.image.length)return;Q(e,i),n.activeTexture(33984+r),n.bindTexture(34067,e.__webglTexture),t.pixelStorei(37440,i.flipY),t.pixelStorei(37441,i.premultiplyAlpha),t.pixelStorei(3317,i.unpackAlignment),t.pixelStorei(37443,0);const a=i&&(i.isCompressedTexture||i.image[0].isCompressedTexture),l=i.image[0]&&i.image[0].isDataTexture,h=[];for(let t=0;t<6;t++)h[t]=a||l?l?i.image[t].image:i.image[t]:z(i.image[t],!1,!0,c);const u=h[0],d=B(u)||o,p=s.convert(i.format),m=s.convert(i.type),f=U(i.internalFormat,p,m,i.encoding),g=o&&!0!==i.isVideoTexture,v=void 0===e.__version;let y,x=H(i,u,d);if(Z(34067,i,d),a){g&&v&&n.texStorage2D(34067,x,f,u.width,u.height);for(let t=0;t<6;t++){y=h[t].mipmaps;for(let e=0;e<y.length;e++){const r=y[e];i.format!==E&&i.format!==T?null!==p?g?n.compressedTexSubImage2D(34069+t,e,0,0,r.width,r.height,p,r.data):n.compressedTexImage2D(34069+t,e,f,r.width,r.height,0,r.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):g?n.texSubImage2D(34069+t,e,0,0,r.width,r.height,p,m,r.data):n.texImage2D(34069+t,e,f,r.width,r.height,0,p,m,r.data)}}}else{y=i.mipmaps,g&&v&&(y.length>0&&x++,n.texStorage2D(34067,x,f,h[0].width,h[0].height));for(let t=0;t<6;t++)if(l){g?n.texSubImage2D(34069+t,0,0,0,h[t].width,h[t].height,p,m,h[t].data):n.texImage2D(34069+t,0,f,h[t].width,h[t].height,0,p,m,h[t].data);for(let e=0;e<y.length;e++){const i=y[e].image[t].image;g?n.texSubImage2D(34069+t,e+1,0,0,i.width,i.height,p,m,i.data):n.texImage2D(34069+t,e+1,f,i.width,i.height,0,p,m,i.data)}}else{g?n.texSubImage2D(34069+t,0,0,0,p,m,h[t]):n.texImage2D(34069+t,0,f,p,m,h[t]);for(let e=0;e<y.length;e++){const i=y[e];g?n.texSubImage2D(34069+t,e+1,0,0,p,m,i.image[t]):n.texImage2D(34069+t,e+1,f,p,m,i.image[t])}}}F(i,d)&&O(34067);e.__version=i.version,i.onUpdate&&i.onUpdate(i)}(a,e,r):(n.activeTexture(33984+r),n.bindTexture(34067,a.__webglTexture))}const X={[h]:10497,[u]:33071,[d]:33648},Y={[p]:9728,[m]:9984,[f]:9986,[g]:9729,[v]:9985,[y]:9987};function Z(n,s,a){if(a?(t.texParameteri(n,10242,X[s.wrapS]),t.texParameteri(n,10243,X[s.wrapT]),32879!==n&&35866!==n||t.texParameteri(n,32882,X[s.wrapR]),t.texParameteri(n,10240,Y[s.magFilter]),t.texParameteri(n,10241,Y[s.minFilter])):(t.texParameteri(n,10242,33071),t.texParameteri(n,10243,33071),32879!==n&&35866!==n||t.texParameteri(n,32882,33071),s.wrapS===u&&s.wrapT===u||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),t.texParameteri(n,10240,G(s.magFilter)),t.texParameteri(n,10241,G(s.minFilter)),s.minFilter!==p&&s.minFilter!==g&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),!0===e.has("EXT_texture_filter_anisotropic")){const a=e.get("EXT_texture_filter_anisotropic");if(s.type===M&&!1===e.has("OES_texture_float_linear"))return;if(!1===o&&s.type===w&&!1===e.has("OES_texture_half_float_linear"))return;(s.anisotropy>1||i.get(s).__currentAnisotropy)&&(t.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy)}}function Q(e,n){void 0===e.__webglInit&&(e.__webglInit=!0,n.addEventListener("dispose",k),e.__webglTexture=t.createTexture(),a.memory.textures++)}function K(e,i,r){let a=3553;i.isDataTexture2DArray&&(a=35866),i.isDataTexture3D&&(a=32879),Q(e,i),n.activeTexture(33984+r),n.bindTexture(a,e.__webglTexture),t.pixelStorei(37440,i.flipY),t.pixelStorei(37441,i.premultiplyAlpha),t.pixelStorei(3317,i.unpackAlignment),t.pixelStorei(37443,0);const l=function(t){return!o&&(t.wrapS!==u||t.wrapT!==u||t.minFilter!==p&&t.minFilter!==g)}(i)&&!1===B(i.image),c=z(i.image,l,!1,x),h=B(c)||o,d=s.convert(i.format);let m,f=s.convert(i.type),v=U(i.internalFormat,d,f,i.encoding);Z(a,i,h);const y=i.mipmaps,w=o&&!0!==i.isVideoTexture,R=void 0===e.__version,C=H(i,c,h);if(i.isDepthTexture)v=6402,o?v=i.type===M?36012:i.type===b?33190:i.type===S?35056:33189:i.type===M&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),i.format===A&&6402===v&&i.type!==_&&i.type!==b&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),i.type=_,f=s.convert(i.type)),i.format===L&&6402===v&&(v=34041,i.type!==S&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),i.type=S,f=s.convert(i.type))),w&&R?n.texStorage2D(3553,1,v,c.width,c.height):n.texImage2D(3553,0,v,c.width,c.height,0,d,f,null);else if(i.isDataTexture)if(y.length>0&&h){w&&R&&n.texStorage2D(3553,C,v,y[0].width,y[0].height);for(let t=0,e=y.length;t<e;t++)m=y[t],w?n.texSubImage2D(3553,0,0,0,m.width,m.height,d,f,m.data):n.texImage2D(3553,t,v,m.width,m.height,0,d,f,m.data);i.generateMipmaps=!1}else w?(R&&n.texStorage2D(3553,C,v,c.width,c.height),n.texSubImage2D(3553,0,0,0,c.width,c.height,d,f,c.data)):n.texImage2D(3553,0,v,c.width,c.height,0,d,f,c.data);else if(i.isCompressedTexture){w&&R&&n.texStorage2D(3553,C,v,y[0].width,y[0].height);for(let t=0,e=y.length;t<e;t++)m=y[t],i.format!==E&&i.format!==T?null!==d?w?n.compressedTexSubImage2D(3553,t,0,0,m.width,m.height,d,m.data):n.compressedTexImage2D(3553,t,v,m.width,m.height,0,m.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):w?n.texSubImage2D(3553,t,0,0,m.width,m.height,d,f,m.data):n.texImage2D(3553,t,v,m.width,m.height,0,d,f,m.data)}else if(i.isDataTexture2DArray)w?(R&&n.texStorage3D(35866,C,v,c.width,c.height,c.depth),n.texSubImage3D(35866,0,0,0,0,c.width,c.height,c.depth,d,f,c.data)):n.texImage3D(35866,0,v,c.width,c.height,c.depth,0,d,f,c.data);else if(i.isDataTexture3D)w?(R&&n.texStorage3D(32879,C,v,c.width,c.height,c.depth),n.texSubImage3D(32879,0,0,0,0,c.width,c.height,c.depth,d,f,c.data)):n.texImage3D(32879,0,v,c.width,c.height,c.depth,0,d,f,c.data);else if(i.isFramebufferTexture)w&&R?n.texStorage2D(3553,C,v,c.width,c.height):n.texImage2D(3553,0,v,c.width,c.height,0,d,f,null);else if(y.length>0&&h){w&&R&&n.texStorage2D(3553,C,v,y[0].width,y[0].height);for(let t=0,e=y.length;t<e;t++)m=y[t],w?n.texSubImage2D(3553,t,0,0,d,f,m):n.texImage2D(3553,t,v,d,f,m);i.generateMipmaps=!1}else w?(R&&n.texStorage2D(3553,C,v,c.width,c.height),n.texSubImage2D(3553,0,0,0,d,f,c)):n.texImage2D(3553,0,v,d,f,c);F(i,h)&&O(a),e.__version=i.version,i.onUpdate&&i.onUpdate(i)}function $(e,r,a,o,l){const c=s.convert(a.format),h=s.convert(a.type),u=U(a.internalFormat,c,h,a.encoding);i.get(r).__hasExternalTextures||(32879===l||35866===l?n.texImage3D(l,0,u,r.width,r.height,r.depth,0,c,h,null):n.texImage2D(l,0,u,r.width,r.height,0,c,h,null)),n.bindFramebuffer(36160,e),r.useRenderToTexture?C.framebufferTexture2DMultisampleEXT(36160,o,l,i.get(a).__webglTexture,0,nt(r)):t.framebufferTexture2D(36160,o,l,i.get(a).__webglTexture,0),n.bindFramebuffer(36160,null)}function tt(e,n,i){if(t.bindRenderbuffer(36161,e),n.depthBuffer&&!n.stencilBuffer){let r=33189;if(i||n.useRenderToTexture){const e=n.depthTexture;e&&e.isDepthTexture&&(e.type===M?r=36012:e.type===b&&(r=33190));const i=nt(n);n.useRenderToTexture?C.renderbufferStorageMultisampleEXT(36161,i,r,n.width,n.height):t.renderbufferStorageMultisample(36161,i,r,n.width,n.height)}else t.renderbufferStorage(36161,r,n.width,n.height);t.framebufferRenderbuffer(36160,36096,36161,e)}else if(n.depthBuffer&&n.stencilBuffer){const r=nt(n);i&&n.useRenderbuffer?t.renderbufferStorageMultisample(36161,r,35056,n.width,n.height):n.useRenderToTexture?C.renderbufferStorageMultisampleEXT(36161,r,35056,n.width,n.height):t.renderbufferStorage(36161,34041,n.width,n.height),t.framebufferRenderbuffer(36160,33306,36161,e)}else{const e=!0===n.isWebGLMultipleRenderTargets?n.texture[0]:n.texture,r=s.convert(e.format),a=s.convert(e.type),o=U(e.internalFormat,r,a,e.encoding),l=nt(n);i&&n.useRenderbuffer?t.renderbufferStorageMultisample(36161,l,o,n.width,n.height):n.useRenderToTexture?C.renderbufferStorageMultisampleEXT(36161,l,o,n.width,n.height):t.renderbufferStorage(36161,o,n.width,n.height)}t.bindRenderbuffer(36161,null)}function et(e){const r=i.get(e),s=!0===e.isWebGLCubeRenderTarget;if(e.depthTexture&&!r.__autoAllocateDepthBuffer){if(s)throw new Error("target.depthTexture not supported in Cube render targets");!function(e,r){if(r&&r.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(36160,e),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");i.get(r.depthTexture).__webglTexture&&r.depthTexture.image.width===r.width&&r.depthTexture.image.height===r.height||(r.depthTexture.image.width=r.width,r.depthTexture.image.height=r.height,r.depthTexture.needsUpdate=!0),j(r.depthTexture,0);const s=i.get(r.depthTexture).__webglTexture,a=nt(r);if(r.depthTexture.format===A)r.useRenderToTexture?C.framebufferTexture2DMultisampleEXT(36160,36096,3553,s,0,a):t.framebufferTexture2D(36160,36096,3553,s,0);else{if(r.depthTexture.format!==L)throw new Error("Unknown depthTexture format");r.useRenderToTexture?C.framebufferTexture2DMultisampleEXT(36160,33306,3553,s,0,a):t.framebufferTexture2D(36160,33306,3553,s,0)}}(r.__webglFramebuffer,e)}else if(s){r.__webglDepthbuffer=[];for(let i=0;i<6;i++)n.bindFramebuffer(36160,r.__webglFramebuffer[i]),r.__webglDepthbuffer[i]=t.createRenderbuffer(),tt(r.__webglDepthbuffer[i],e,!1)}else n.bindFramebuffer(36160,r.__webglFramebuffer),r.__webglDepthbuffer=t.createRenderbuffer(),tt(r.__webglDepthbuffer,e,!1);n.bindFramebuffer(36160,null)}function nt(t){return o&&(t.useRenderbuffer||t.useRenderToTexture)?Math.min(R,t.samples):0}let it=!1,rt=!1;this.allocateTextureUnit=function(){const t=W;return t>=l&&console.warn("THREE.WebGLTextures: Trying to use "+t+" texture units while this GPU supports only "+l),W+=1,t},this.resetTextureUnits=function(){W=0},this.setTexture2D=j,this.setTexture2DArray=function(t,e){const r=i.get(t);t.version>0&&r.__version!==t.version?K(r,t,e):(n.activeTexture(33984+e),n.bindTexture(35866,r.__webglTexture))},this.setTexture3D=function(t,e){const r=i.get(t);t.version>0&&r.__version!==t.version?K(r,t,e):(n.activeTexture(33984+e),n.bindTexture(32879,r.__webglTexture))},this.setTextureCube=q,this.rebindTextures=function(t,e,n){const r=i.get(t);void 0!==e&&$(r.__webglFramebuffer,t,t.texture,36064,3553),void 0!==n&&et(t)},this.setupRenderTarget=function(e){const l=e.texture,c=i.get(e),h=i.get(l);e.addEventListener("dispose",V),!0!==e.isWebGLMultipleRenderTargets&&(void 0===h.__webglTexture&&(h.__webglTexture=t.createTexture()),h.__version=l.version,a.memory.textures++);const u=!0===e.isWebGLCubeRenderTarget,d=!0===e.isWebGLMultipleRenderTargets,p=l.isDataTexture3D||l.isDataTexture2DArray,m=B(e)||o;if(!o||l.format!==T||l.type!==M&&l.type!==w||(l.format=E,console.warn("THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.")),u){c.__webglFramebuffer=[];for(let e=0;e<6;e++)c.__webglFramebuffer[e]=t.createFramebuffer()}else if(c.__webglFramebuffer=t.createFramebuffer(),d)if(r.drawBuffers){const n=e.texture;for(let e=0,r=n.length;e<r;e++){const r=i.get(n[e]);void 0===r.__webglTexture&&(r.__webglTexture=t.createTexture(),a.memory.textures++)}}else console.warn("THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.");else if(e.useRenderbuffer)if(o){c.__webglMultisampledFramebuffer=t.createFramebuffer(),c.__webglColorRenderbuffer=t.createRenderbuffer(),t.bindRenderbuffer(36161,c.__webglColorRenderbuffer);const i=s.convert(l.format),r=s.convert(l.type),a=U(l.internalFormat,i,r,l.encoding),o=nt(e);t.renderbufferStorageMultisample(36161,o,a,e.width,e.height),n.bindFramebuffer(36160,c.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(36160,36064,36161,c.__webglColorRenderbuffer),t.bindRenderbuffer(36161,null),e.depthBuffer&&(c.__webglDepthRenderbuffer=t.createRenderbuffer(),tt(c.__webglDepthRenderbuffer,e,!0)),n.bindFramebuffer(36160,null)}else console.warn("THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.");if(u){n.bindTexture(34067,h.__webglTexture),Z(34067,l,m);for(let t=0;t<6;t++)$(c.__webglFramebuffer[t],e,l,36064,34069+t);F(l,m)&&O(34067),n.unbindTexture()}else if(d){const t=e.texture;for(let r=0,s=t.length;r<s;r++){const s=t[r],a=i.get(s);n.bindTexture(3553,a.__webglTexture),Z(3553,s,m),$(c.__webglFramebuffer,e,s,36064+r,3553),F(s,m)&&O(3553)}n.unbindTexture()}else{let t=3553;if(p)if(o){t=l.isDataTexture3D?32879:35866}else console.warn("THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.");n.bindTexture(t,h.__webglTexture),Z(t,l,m),$(c.__webglFramebuffer,e,l,36064,t),F(l,m)&&O(t),n.unbindTexture()}e.depthBuffer&&et(e)},this.updateRenderTargetMipmap=function(t){const e=B(t)||o,r=!0===t.isWebGLMultipleRenderTargets?t.texture:[t.texture];for(let s=0,a=r.length;s<a;s++){const a=r[s];if(F(a,e)){const e=t.isWebGLCubeRenderTarget?34067:3553,r=i.get(a).__webglTexture;n.bindTexture(e,r),O(e),n.unbindTexture()}}},this.updateMultisampleRenderTarget=function(e){if(e.useRenderbuffer)if(o){const r=e.width,s=e.height;let a=16384;const o=[36064],l=e.stencilBuffer?33306:36096;e.depthBuffer&&o.push(l),e.ignoreDepthForMultisampleCopy||(e.depthBuffer&&(a|=256),e.stencilBuffer&&(a|=1024));const c=i.get(e);n.bindFramebuffer(36008,c.__webglMultisampledFramebuffer),n.bindFramebuffer(36009,c.__webglFramebuffer),e.ignoreDepthForMultisampleCopy&&(t.invalidateFramebuffer(36008,[l]),t.invalidateFramebuffer(36009,[l])),t.blitFramebuffer(0,0,r,s,0,0,r,s,a,9728),t.invalidateFramebuffer(36008,o),n.bindFramebuffer(36008,null),n.bindFramebuffer(36009,c.__webglMultisampledFramebuffer)}else console.warn("THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.")},this.setupDepthRenderbuffer=et,this.setupFrameBufferTexture=$,this.safeSetTexture2D=function(t,e){t&&t.isWebGLRenderTarget&&(!1===it&&(console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead."),it=!0),t=t.texture),j(t,e)},this.safeSetTextureCube=function(t,e){t&&t.isWebGLCubeRenderTarget&&(!1===rt&&(console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead."),rt=!0),t=t.texture),q(t,e)}}function Gs(t,e,n){const i=n.isWebGL2;return{convert:function(t){let n;if(t===x)return 5121;if(1017===t)return 32819;if(1018===t)return 32820;if(1019===t)return 33635;if(1010===t)return 5120;if(1011===t)return 5122;if(t===_)return 5123;if(1013===t)return 5124;if(t===b)return 5125;if(t===M)return 5126;if(t===w)return i?5131:(n=e.get("OES_texture_half_float"),null!==n?n.HALF_FLOAT_OES:null);if(1021===t)return 6406;if(t===T)return 6407;if(t===E)return 6408;if(1024===t)return 6409;if(1025===t)return 6410;if(t===A)return 6402;if(t===L)return 34041;if(1028===t)return 6403;if(1029===t)return 36244;if(1030===t)return 33319;if(1031===t)return 33320;if(1032===t)return 36248;if(1033===t)return 36249;if(t===R||t===C||t===P||t===D){if(n=e.get("WEBGL_compressed_texture_s3tc"),null===n)return null;if(t===R)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(t===C)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(t===P)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(t===D)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(t===I||t===N||t===z||t===B){if(n=e.get("WEBGL_compressed_texture_pvrtc"),null===n)return null;if(t===I)return n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(t===N)return n.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(t===z)return n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(t===B)return n.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===t)return n=e.get("WEBGL_compressed_texture_etc1"),null!==n?n.COMPRESSED_RGB_ETC1_WEBGL:null;if((t===F||t===O)&&(n=e.get("WEBGL_compressed_texture_etc"),null!==n)){if(t===F)return n.COMPRESSED_RGB8_ETC2;if(t===O)return n.COMPRESSED_RGBA8_ETC2_EAC}return 37808===t||37809===t||37810===t||37811===t||37812===t||37813===t||37814===t||37815===t||37816===t||37817===t||37818===t||37819===t||37820===t||37821===t||37840===t||37841===t||37842===t||37843===t||37844===t||37845===t||37846===t||37847===t||37848===t||37849===t||37850===t||37851===t||37852===t||37853===t?(n=e.get("WEBGL_compressed_texture_astc"),null!==n?t:null):36492===t?(n=e.get("EXT_texture_compression_bptc"),null!==n?t:null):t===S?i?34042:(n=e.get("WEBGL_depth_texture"),null!==n?n.UNSIGNED_INT_24_8_WEBGL:null):void 0}}}class ks extends jn{constructor(t=[]){super(),this.cameras=t}}ks.prototype.isArrayCamera=!0;class Vs extends Ce{constructor(){super(),this.type="Group"}}Vs.prototype.isGroup=!0;const Ws={type:"move"};class js{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Vs,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new Vs,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Lt,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Lt),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Vs,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Lt,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Lt),this._grip}dispatchEvent(t){return null!==this._targetRay&&this._targetRay.dispatchEvent(t),null!==this._grip&&this._grip.dispatchEvent(t),null!==this._hand&&this._hand.dispatchEvent(t),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(t,e,n){let i=null,r=null,s=null;const a=this._targetRay,o=this._grip,l=this._hand;if(t&&"visible-blurred"!==e.session.visibilityState)if(null!==a&&(i=e.getPose(t.targetRaySpace,n),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Ws))),l&&t.hand){s=!0;for(const i of t.hand.values()){const t=e.getJointPose(i,n);if(void 0===l.joints[i.jointName]){const t=new Vs;t.matrixAutoUpdate=!1,t.visible=!1,l.joints[i.jointName]=t,l.add(t)}const r=l.joints[i.jointName];null!==t&&(r.matrix.fromArray(t.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.jointRadius=t.radius),r.visible=null!==t}const i=l.joints["index-finger-tip"],r=l.joints["thumb-tip"],a=i.position.distanceTo(r.position),o=.02,c=.005;l.inputState.pinching&&a>o+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&a<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else null!==o&&t.gripSpace&&(r=e.getPose(t.gripSpace,n),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1));return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}}class qs extends bt{constructor(t,e,n,i,r,s,a,o,l,c){if((c=void 0!==c?c:A)!==A&&c!==L)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===n&&c===A&&(n=_),void 0===n&&c===L&&(n=S),super(null,i,r,s,a,o,c,n,l),this.image={width:t,height:e},this.magFilter=void 0!==a?a:p,this.minFilter=void 0!==o?o:p,this.flipY=!1,this.generateMipmaps=!1}}qs.prototype.isDepthTexture=!0;class Xs extends ${constructor(t,e){super();const n=this;let i=null,r=1,s=null,a="local-floor";const o=t.extensions.has("WEBGL_multisampled_render_to_texture");let l=null,c=null,h=null,u=null,d=!1,p=null;const m=e.getContextAttributes();let f=null,g=null;const v=[],y=new Map,b=new jn;b.layers.enable(1),b.viewport=new wt;const M=new jn;M.layers.enable(2),M.viewport=new wt;const w=[b,M],R=new ks;R.layers.enable(1),R.layers.enable(2);let C=null,P=null;function D(t){const e=y.get(t.inputSource);e&&e.dispatchEvent({type:t.type,data:t.inputSource})}function I(){y.forEach((function(t,e){t.disconnect(e)})),y.clear(),C=null,P=null,t.setRenderTarget(f),u=null,h=null,c=null,i=null,g=null,U.stop(),n.isPresenting=!1,n.dispatchEvent({type:"sessionend"})}function N(t){const e=i.inputSources;for(let t=0;t<v.length;t++)y.set(e[t],v[t]);for(let e=0;e<t.removed.length;e++){const n=t.removed[e],i=y.get(n);i&&(i.dispatchEvent({type:"disconnected",data:n}),y.delete(n))}for(let e=0;e<t.added.length;e++){const n=t.added[e],i=y.get(n);i&&i.dispatchEvent({type:"connected",data:n})}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(t){let e=v[t];return void 0===e&&(e=new js,v[t]=e),e.getTargetRaySpace()},this.getControllerGrip=function(t){let e=v[t];return void 0===e&&(e=new js,v[t]=e),e.getGripSpace()},this.getHand=function(t){let e=v[t];return void 0===e&&(e=new js,v[t]=e),e.getHandSpace()},this.setFramebufferScaleFactor=function(t){r=t,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(t){a=t,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return s},this.getBaseLayer=function(){return null!==h?h:u},this.getBinding=function(){return c},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(l){if(i=l,null!==i){if(f=t.getRenderTarget(),i.addEventListener("select",D),i.addEventListener("selectstart",D),i.addEventListener("selectend",D),i.addEventListener("squeeze",D),i.addEventListener("squeezestart",D),i.addEventListener("squeezeend",D),i.addEventListener("end",I),i.addEventListener("inputsourceschange",N),!0!==m.xrCompatible&&await e.makeXRCompatible(),void 0===i.renderState.layers||!1===t.capabilities.isWebGL2){const n={antialias:void 0!==i.renderState.layers||m.antialias,alpha:m.alpha,depth:m.depth,stencil:m.stencil,framebufferScaleFactor:r};u=new XRWebGLLayer(i,e,n),i.updateRenderState({baseLayer:u}),g=new St(u.framebufferWidth,u.framebufferHeight,{format:E,type:x,encoding:t.outputEncoding})}else{d=m.antialias;let n=null,s=null,a=null;m.depth&&(a=m.stencil?35056:33190,n=m.stencil?L:A,s=m.stencil?S:_);const l={colorFormat:m.alpha||d?32856:32849,depthFormat:a,scaleFactor:r};c=new XRWebGLBinding(i,e),h=c.createProjectionLayer(l),i.updateRenderState({layers:[h]}),g=d?new Et(h.textureWidth,h.textureHeight,{format:E,type:x,depthTexture:new qs(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:m.stencil,ignoreDepth:h.ignoreDepthValues,useRenderToTexture:o,encoding:t.outputEncoding}):new St(h.textureWidth,h.textureHeight,{format:m.alpha?E:T,type:x,depthTexture:new qs(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:m.stencil,ignoreDepth:h.ignoreDepthValues,encoding:t.outputEncoding})}this.setFoveation(1),s=await i.requestReferenceSpace(a),U.setContext(i),U.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}};const z=new Lt,B=new Lt;function F(t,e){null===e?t.matrixWorld.copy(t.matrix):t.matrixWorld.multiplyMatrices(e.matrixWorld,t.matrix),t.matrixWorldInverse.copy(t.matrixWorld).invert()}this.updateCamera=function(t){if(null===i)return;R.near=M.near=b.near=t.near,R.far=M.far=b.far=t.far,C===R.near&&P===R.far||(i.updateRenderState({depthNear:R.near,depthFar:R.far}),C=R.near,P=R.far);const e=t.parent,n=R.cameras;F(R,e);for(let t=0;t<n.length;t++)F(n[t],e);R.matrixWorld.decompose(R.position,R.quaternion,R.scale),t.position.copy(R.position),t.quaternion.copy(R.quaternion),t.scale.copy(R.scale),t.matrix.copy(R.matrix),t.matrixWorld.copy(R.matrixWorld);const r=t.children;for(let t=0,e=r.length;t<e;t++)r[t].updateMatrixWorld(!0);2===n.length?function(t,e,n){z.setFromMatrixPosition(e.matrixWorld),B.setFromMatrixPosition(n.matrixWorld);const i=z.distanceTo(B),r=e.projectionMatrix.elements,s=n.projectionMatrix.elements,a=r[14]/(r[10]-1),o=r[14]/(r[10]+1),l=(r[9]+1)/r[5],c=(r[9]-1)/r[5],h=(r[8]-1)/r[0],u=(s[8]+1)/s[0],d=a*h,p=a*u,m=i/(-h+u),f=m*-h;e.matrixWorld.decompose(t.position,t.quaternion,t.scale),t.translateX(f),t.translateZ(m),t.matrixWorld.compose(t.position,t.quaternion,t.scale),t.matrixWorldInverse.copy(t.matrixWorld).invert();const g=a+m,v=o+m,y=d-f,x=p+(i-f),_=l*o/v*g,b=c*o/v*g;t.projectionMatrix.makePerspective(y,x,_,b,g,v)}(R,b,M):R.projectionMatrix.copy(b.projectionMatrix)},this.getCamera=function(){return R},this.getFoveation=function(){return null!==h?h.fixedFoveation:null!==u?u.fixedFoveation:void 0},this.setFoveation=function(t){null!==h&&(h.fixedFoveation=t),null!==u&&void 0!==u.fixedFoveation&&(u.fixedFoveation=t)};let O=null;const U=new ii;U.setAnimationLoop((function(e,n){if(l=n.getViewerPose(s),p=n,null!==l){const e=l.views;null!==u&&(t.setRenderTargetFramebuffer(g,u.framebuffer),t.setRenderTarget(g));let n=!1;e.length!==R.cameras.length&&(R.cameras.length=0,n=!0);for(let i=0;i<e.length;i++){const r=e[i];let s=null;if(null!==u)s=u.getViewport(r);else{const e=c.getViewSubImage(h,r);s=e.viewport,0===i&&(t.setRenderTargetTextures(g,e.colorTexture,h.ignoreDepthValues?void 0:e.depthStencilTexture),t.setRenderTarget(g))}const a=w[i];a.matrix.fromArray(r.transform.matrix),a.projectionMatrix.fromArray(r.projectionMatrix),a.viewport.set(s.x,s.y,s.width,s.height),0===i&&R.matrix.copy(a.matrix),!0===n&&R.cameras.push(a)}}const r=i.inputSources;for(let t=0;t<v.length;t++){const e=v[t],i=r[t];e.update(i,n,s)}O&&O(e,n),p=null})),this.setAnimationLoop=function(t){O=t},this.dispose=function(){}}}function Js(t){function e(e,n){e.opacity.value=n.opacity,n.color&&e.diffuse.value.copy(n.color),n.emissive&&e.emissive.value.copy(n.emissive).multiplyScalar(n.emissiveIntensity),n.map&&(e.map.value=n.map),n.alphaMap&&(e.alphaMap.value=n.alphaMap),n.specularMap&&(e.specularMap.value=n.specularMap),n.alphaTest>0&&(e.alphaTest.value=n.alphaTest);const i=t.get(n).envMap;let r,s;i&&(e.envMap.value=i,e.flipEnvMap.value=i.isCubeTexture&&!1===i.isRenderTargetTexture?-1:1,e.reflectivity.value=n.reflectivity,e.ior.value=n.ior,e.refractionRatio.value=n.refractionRatio),n.lightMap&&(e.lightMap.value=n.lightMap,e.lightMapIntensity.value=n.lightMapIntensity),n.aoMap&&(e.aoMap.value=n.aoMap,e.aoMapIntensity.value=n.aoMapIntensity),n.map?r=n.map:n.specularMap?r=n.specularMap:n.displacementMap?r=n.displacementMap:n.normalMap?r=n.normalMap:n.bumpMap?r=n.bumpMap:n.roughnessMap?r=n.roughnessMap:n.metalnessMap?r=n.metalnessMap:n.alphaMap?r=n.alphaMap:n.emissiveMap?r=n.emissiveMap:n.clearcoatMap?r=n.clearcoatMap:n.clearcoatNormalMap?r=n.clearcoatNormalMap:n.clearcoatRoughnessMap?r=n.clearcoatRoughnessMap:n.specularIntensityMap?r=n.specularIntensityMap:n.specularColorMap?r=n.specularColorMap:n.transmissionMap?r=n.transmissionMap:n.thicknessMap?r=n.thicknessMap:n.sheenColorMap?r=n.sheenColorMap:n.sheenRoughnessMap&&(r=n.sheenRoughnessMap),void 0!==r&&(r.isWebGLRenderTarget&&(r=r.texture),!0===r.matrixAutoUpdate&&r.updateMatrix(),e.uvTransform.value.copy(r.matrix)),n.aoMap?s=n.aoMap:n.lightMap&&(s=n.lightMap),void 0!==s&&(s.isWebGLRenderTarget&&(s=s.texture),!0===s.matrixAutoUpdate&&s.updateMatrix(),e.uv2Transform.value.copy(s.matrix))}function n(e,n){e.roughness.value=n.roughness,e.metalness.value=n.metalness,n.roughnessMap&&(e.roughnessMap.value=n.roughnessMap),n.metalnessMap&&(e.metalnessMap.value=n.metalnessMap),n.emissiveMap&&(e.emissiveMap.value=n.emissiveMap),n.bumpMap&&(e.bumpMap.value=n.bumpMap,e.bumpScale.value=n.bumpScale,1===n.side&&(e.bumpScale.value*=-1)),n.normalMap&&(e.normalMap.value=n.normalMap,e.normalScale.value.copy(n.normalScale),1===n.side&&e.normalScale.value.negate()),n.displacementMap&&(e.displacementMap.value=n.displacementMap,e.displacementScale.value=n.displacementScale,e.displacementBias.value=n.displacementBias);t.get(n).envMap&&(e.envMapIntensity.value=n.envMapIntensity)}return{refreshFogUniforms:function(t,e){t.fogColor.value.copy(e.color),e.isFog?(t.fogNear.value=e.near,t.fogFar.value=e.far):e.isFogExp2&&(t.fogDensity.value=e.density)},refreshMaterialUniforms:function(t,i,r,s,a){i.isMeshBasicMaterial?e(t,i):i.isMeshLambertMaterial?(e(t,i),function(t,e){e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap)}(t,i)):i.isMeshToonMaterial?(e(t,i),function(t,e){e.gradientMap&&(t.gradientMap.value=e.gradientMap);e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap);e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale,1===e.side&&(t.bumpScale.value*=-1));e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale),1===e.side&&t.normalScale.value.negate());e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(t,i)):i.isMeshPhongMaterial?(e(t,i),function(t,e){t.specular.value.copy(e.specular),t.shininess.value=Math.max(e.shininess,1e-4),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap);e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale,1===e.side&&(t.bumpScale.value*=-1));e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale),1===e.side&&t.normalScale.value.negate());e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(t,i)):i.isMeshStandardMaterial?(e(t,i),i.isMeshPhysicalMaterial?function(t,e,i){n(t,e),t.ior.value=e.ior,e.sheen>0&&(t.sheenColor.value.copy(e.sheenColor).multiplyScalar(e.sheen),t.sheenRoughness.value=e.sheenRoughness,e.sheenColorMap&&(t.sheenColorMap.value=e.sheenColorMap),e.sheenRoughnessMap&&(t.sheenRoughnessMap.value=e.sheenRoughnessMap));e.clearcoat>0&&(t.clearcoat.value=e.clearcoat,t.clearcoatRoughness.value=e.clearcoatRoughness,e.clearcoatMap&&(t.clearcoatMap.value=e.clearcoatMap),e.clearcoatRoughnessMap&&(t.clearcoatRoughnessMap.value=e.clearcoatRoughnessMap),e.clearcoatNormalMap&&(t.clearcoatNormalScale.value.copy(e.clearcoatNormalScale),t.clearcoatNormalMap.value=e.clearcoatNormalMap,1===e.side&&t.clearcoatNormalScale.value.negate()));e.transmission>0&&(t.transmission.value=e.transmission,t.transmissionSamplerMap.value=i.texture,t.transmissionSamplerSize.value.set(i.width,i.height),e.transmissionMap&&(t.transmissionMap.value=e.transmissionMap),t.thickness.value=e.thickness,e.thicknessMap&&(t.thicknessMap.value=e.thicknessMap),t.attenuationDistance.value=e.attenuationDistance,t.attenuationColor.value.copy(e.attenuationColor));t.specularIntensity.value=e.specularIntensity,t.specularColor.value.copy(e.specularColor),e.specularIntensityMap&&(t.specularIntensityMap.value=e.specularIntensityMap);e.specularColorMap&&(t.specularColorMap.value=e.specularColorMap)}(t,i,a):n(t,i)):i.isMeshMatcapMaterial?(e(t,i),function(t,e){e.matcap&&(t.matcap.value=e.matcap);e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale,1===e.side&&(t.bumpScale.value*=-1));e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale),1===e.side&&t.normalScale.value.negate());e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(t,i)):i.isMeshDepthMaterial?(e(t,i),function(t,e){e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(t,i)):i.isMeshDistanceMaterial?(e(t,i),function(t,e){e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias);t.referencePosition.value.copy(e.referencePosition),t.nearDistance.value=e.nearDistance,t.farDistance.value=e.farDistance}(t,i)):i.isMeshNormalMaterial?(e(t,i),function(t,e){e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale,1===e.side&&(t.bumpScale.value*=-1));e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale),1===e.side&&t.normalScale.value.negate());e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(t,i)):i.isLineBasicMaterial?(function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity}(t,i),i.isLineDashedMaterial&&function(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}(t,i)):i.isPointsMaterial?function(t,e,n,i){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.size.value=e.size*n,t.scale.value=.5*i,e.map&&(t.map.value=e.map);e.alphaMap&&(t.alphaMap.value=e.alphaMap);e.alphaTest>0&&(t.alphaTest.value=e.alphaTest);let r;e.map?r=e.map:e.alphaMap&&(r=e.alphaMap);void 0!==r&&(!0===r.matrixAutoUpdate&&r.updateMatrix(),t.uvTransform.value.copy(r.matrix))}(t,i,r,s):i.isSpriteMaterial?function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.rotation.value=e.rotation,e.map&&(t.map.value=e.map);e.alphaMap&&(t.alphaMap.value=e.alphaMap);e.alphaTest>0&&(t.alphaTest.value=e.alphaTest);let n;e.map?n=e.map:e.alphaMap&&(n=e.alphaMap);void 0!==n&&(!0===n.matrixAutoUpdate&&n.updateMatrix(),t.uvTransform.value.copy(n.matrix))}(t,i):i.isShadowMaterial?(t.color.value.copy(i.color),t.opacity.value=i.opacity):i.isShaderMaterial&&(i.uniformsNeedUpdate=!1)}}}function Ys(t={}){const e=void 0!==t.canvas?t.canvas:function(){const t=vt("canvas");return t.style.display="block",t}(),n=void 0!==t.context?t.context:null,i=void 0!==t.alpha&&t.alpha,r=void 0===t.depth||t.depth,s=void 0===t.stencil||t.stencil,a=void 0!==t.antialias&&t.antialias,o=void 0===t.premultipliedAlpha||t.premultipliedAlpha,l=void 0!==t.preserveDrawingBuffer&&t.preserveDrawingBuffer,c=void 0!==t.powerPreference?t.powerPreference:"default",h=void 0!==t.failIfMajorPerformanceCaveat&&t.failIfMajorPerformanceCaveat;let d=null,m=null;const f=[],g=[];this.domElement=e,this.debug={checkShaderErrors:!0},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.outputEncoding=X,this.physicallyCorrectLights=!1,this.toneMapping=0,this.toneMappingExposure=1;const v=this;let _=!1,b=0,S=0,T=null,A=-1,L=null;const R=new wt,C=new wt;let P=null,D=e.width,I=e.height,N=1,z=null,B=null;const F=new wt(0,0,D,I),O=new wt(0,0,D,I);let U=!1;const H=[],G=new ni;let k=!1,V=!1,W=null;const j=new se,q=new Lt,J={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function Y(){return null===T?N:1}let Z,Q,K,$,tt,et,nt,it,rt,st,at,ot,lt,ct,ht,ut,dt,pt,mt,ft,gt,yt,xt,_t=n;function bt(t,n){for(let i=0;i<t.length;i++){const r=t[i],s=e.getContext(r,n);if(null!==s)return s}return null}try{const t={alpha:i,depth:r,stencil:s,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:l,powerPreference:c,failIfMajorPerformanceCaveat:h};if("setAttribute"in e&&e.setAttribute("data-engine","three.js r136"),e.addEventListener("webglcontextlost",At,!1),e.addEventListener("webglcontextrestored",Rt,!1),null===_t){const e=["webgl2","webgl","experimental-webgl"];if(!0===v.isWebGL1Renderer&&e.shift(),_t=bt(e,t),null===_t)throw bt(e)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}void 0===_t.getShaderPrecisionFormat&&(_t.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(t){throw console.error("THREE.WebGLRenderer: "+t.message),t}function Mt(){Z=new Hi(_t),Q=new di(_t,Z,t),Z.init(Q),yt=new Gs(_t,Z,Q),K=new Us(_t,Z,Q),H[0]=1029,$=new Vi(_t),tt=new Ts,et=new Hs(_t,Z,K,tt,Q,yt,$),nt=new mi(v),it=new Ui(v),rt=new ri(_t,Q),xt=new hi(_t,Z,rt,Q),st=new Gi(_t,rt,$,xt),at=new Yi(_t,st,rt,$),mt=new Ji(_t,Q,et),ut=new pi(tt),ot=new Ss(v,nt,it,Z,Q,xt,ut),lt=new Js(tt),ct=new Rs,ht=new zs(Z,Q),pt=new ci(v,nt,K,at,o),dt=new Os(v,at,Q),ft=new ui(_t,Z,$,Q),gt=new ki(_t,Z,$,Q),$.programs=ot.programs,v.capabilities=Q,v.extensions=Z,v.properties=tt,v.renderLists=ct,v.shadowMap=dt,v.state=K,v.info=$}Mt();const Tt=new Xs(v,_t);function At(t){t.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),_=!0}function Rt(){console.log("THREE.WebGLRenderer: Context Restored."),_=!1;const t=$.autoReset,e=dt.enabled,n=dt.autoUpdate,i=dt.needsUpdate,r=dt.type;Mt(),$.autoReset=t,dt.enabled=e,dt.autoUpdate=n,dt.needsUpdate=i,dt.type=r}function Ct(t){const e=t.target;e.removeEventListener("dispose",Ct),function(t){(function(t){const e=tt.get(t).programs;void 0!==e&&(e.forEach((function(t){ot.releaseProgram(t)})),t.isShaderMaterial&&ot.releaseShaderCache(t))})(t),tt.remove(t)}(e)}this.xr=Tt,this.getContext=function(){return _t},this.getContextAttributes=function(){return _t.getContextAttributes()},this.forceContextLoss=function(){const t=Z.get("WEBGL_lose_context");t&&t.loseContext()},this.forceContextRestore=function(){const t=Z.get("WEBGL_lose_context");t&&t.restoreContext()},this.getPixelRatio=function(){return N},this.setPixelRatio=function(t){void 0!==t&&(N=t,this.setSize(D,I,!1))},this.getSize=function(t){return t.set(D,I)},this.setSize=function(t,n,i){Tt.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(D=t,I=n,e.width=Math.floor(t*N),e.height=Math.floor(n*N),!1!==i&&(e.style.width=t+"px",e.style.height=n+"px"),this.setViewport(0,0,t,n))},this.getDrawingBufferSize=function(t){return t.set(D*N,I*N).floor()},this.setDrawingBufferSize=function(t,n,i){D=t,I=n,N=i,e.width=Math.floor(t*i),e.height=Math.floor(n*i),this.setViewport(0,0,t,n)},this.getCurrentViewport=function(t){return t.copy(R)},this.getViewport=function(t){return t.copy(F)},this.setViewport=function(t,e,n,i){t.isVector4?F.set(t.x,t.y,t.z,t.w):F.set(t,e,n,i),K.viewport(R.copy(F).multiplyScalar(N).floor())},this.getScissor=function(t){return t.copy(O)},this.setScissor=function(t,e,n,i){t.isVector4?O.set(t.x,t.y,t.z,t.w):O.set(t,e,n,i),K.scissor(C.copy(O).multiplyScalar(N).floor())},this.getScissorTest=function(){return U},this.setScissorTest=function(t){K.setScissorTest(U=t)},this.setOpaqueSort=function(t){z=t},this.setTransparentSort=function(t){B=t},this.getClearColor=function(t){return t.copy(pt.getClearColor())},this.setClearColor=function(){pt.setClearColor.apply(pt,arguments)},this.getClearAlpha=function(){return pt.getClearAlpha()},this.setClearAlpha=function(){pt.setClearAlpha.apply(pt,arguments)},this.clear=function(t,e,n){let i=0;(void 0===t||t)&&(i|=16384),(void 0===e||e)&&(i|=256),(void 0===n||n)&&(i|=1024),_t.clear(i)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){e.removeEventListener("webglcontextlost",At,!1),e.removeEventListener("webglcontextrestored",Rt,!1),ct.dispose(),ht.dispose(),tt.dispose(),nt.dispose(),it.dispose(),at.dispose(),xt.dispose(),ot.dispose(),Tt.dispose(),Tt.removeEventListener("sessionstart",Dt),Tt.removeEventListener("sessionend",It),W&&(W.dispose(),W=null),Nt.stop()},this.renderBufferDirect=function(t,e,n,i,r,s){null===e&&(e=J);const a=r.isMesh&&r.matrixWorld.determinant()<0,o=function(t,e,n,i,r){!0!==e.isScene&&(e=J);et.resetTextureUnits();const s=e.fog,a=i.isMeshStandardMaterial?e.environment:null,o=null===T?v.outputEncoding:T.texture.encoding,l=(i.isMeshStandardMaterial?it:nt).get(i.envMap||a),c=!0===i.vertexColors&&!!n.attributes.color&&4===n.attributes.color.itemSize,h=!!i.normalMap&&!!n.attributes.tangent,u=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=n.morphAttributes.position?n.morphAttributes.position.length:0,f=i.toneMapped?v.toneMapping:0,g=tt.get(i),y=m.state.lights;if(!0===k&&(!0===V||t!==L)){const e=t===L&&i.id===A;ut.setState(i,t,e)}let x=!1;i.version===g.__version?g.needsLights&&g.lightsStateVersion!==y.state.version||g.outputEncoding!==o||r.isInstancedMesh&&!1===g.instancing?x=!0:r.isInstancedMesh||!0!==g.instancing?r.isSkinnedMesh&&!1===g.skinning?x=!0:r.isSkinnedMesh||!0!==g.skinning?g.envMap!==l||i.fog&&g.fog!==s?x=!0:void 0===g.numClippingPlanes||g.numClippingPlanes===ut.numPlanes&&g.numIntersection===ut.numIntersection?(g.vertexAlphas!==c||g.vertexTangents!==h||g.morphTargets!==u||g.morphNormals!==d||g.toneMapping!==f||!0===Q.isWebGL2&&g.morphTargetsCount!==p)&&(x=!0):x=!0:x=!0:x=!0:(x=!0,g.__version=i.version);let _=g.currentProgram;!0===x&&(_=Ut(i,e,r));let b=!1,M=!1,w=!1;const S=_.getUniforms(),E=g.uniforms;K.useProgram(_.program)&&(b=!0,M=!0,w=!0);i.id!==A&&(A=i.id,M=!0);if(b||L!==t){if(S.setValue(_t,"projectionMatrix",t.projectionMatrix),Q.logarithmicDepthBuffer&&S.setValue(_t,"logDepthBufFC",2/(Math.log(t.far+1)/Math.LN2)),L!==t&&(L=t,M=!0,w=!0),i.isShaderMaterial||i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshStandardMaterial||i.envMap){const e=S.map.cameraPosition;void 0!==e&&e.setValue(_t,q.setFromMatrixPosition(t.matrixWorld))}(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&S.setValue(_t,"isOrthographic",!0===t.isOrthographicCamera),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial||i.isShadowMaterial||r.isSkinnedMesh)&&S.setValue(_t,"viewMatrix",t.matrixWorldInverse)}if(r.isSkinnedMesh){S.setOptional(_t,r,"bindMatrix"),S.setOptional(_t,r,"bindMatrixInverse");const t=r.skeleton;t&&(Q.floatVertexTextures?(null===t.boneTexture&&t.computeBoneTexture(),S.setValue(_t,"boneTexture",t.boneTexture,et),S.setValue(_t,"boneTextureSize",t.boneTextureSize)):S.setOptional(_t,t,"boneMatrices"))}!n||void 0===n.morphAttributes.position&&void 0===n.morphAttributes.normal||mt.update(r,n,i,_);(M||g.receiveShadow!==r.receiveShadow)&&(g.receiveShadow=r.receiveShadow,S.setValue(_t,"receiveShadow",r.receiveShadow));M&&(S.setValue(_t,"toneMappingExposure",v.toneMappingExposure),g.needsLights&&(C=w,(R=E).ambientLightColor.needsUpdate=C,R.lightProbe.needsUpdate=C,R.directionalLights.needsUpdate=C,R.directionalLightShadows.needsUpdate=C,R.pointLights.needsUpdate=C,R.pointLightShadows.needsUpdate=C,R.spotLights.needsUpdate=C,R.spotLightShadows.needsUpdate=C,R.rectAreaLights.needsUpdate=C,R.hemisphereLights.needsUpdate=C),s&&i.fog&&lt.refreshFogUniforms(E,s),lt.refreshMaterialUniforms(E,i,N,I,W),ts.upload(_t,g.uniformsList,E,et));var R,C;i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(ts.upload(_t,g.uniformsList,E,et),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&S.setValue(_t,"center",r.center);return S.setValue(_t,"modelViewMatrix",r.modelViewMatrix),S.setValue(_t,"normalMatrix",r.normalMatrix),S.setValue(_t,"modelMatrix",r.matrixWorld),_}(t,e,n,i,r);K.setMaterial(i,a);let l=n.index;const c=n.attributes.position;if(null===l){if(void 0===c||0===c.count)return}else if(0===l.count)return;let h,u=1;!0===i.wireframe&&(l=st.getWireframeAttribute(n),u=2),xt.setup(r,i,o,n,l);let d=ft;null!==l&&(h=rt.get(l),d=gt,d.setIndex(h));const p=null!==l?l.count:c.count,f=n.drawRange.start*u,g=n.drawRange.count*u,y=null!==s?s.start*u:0,x=null!==s?s.count*u:1/0,_=Math.max(f,y),b=Math.min(p,f+g,y+x)-1,M=Math.max(0,b-_+1);if(0!==M){if(r.isMesh)!0===i.wireframe?(K.setLineWidth(i.wireframeLinewidth*Y()),d.setMode(1)):d.setMode(4);else if(r.isLine){let t=i.linewidth;void 0===t&&(t=1),K.setLineWidth(t*Y()),r.isLineSegments?d.setMode(1):r.isLineLoop?d.setMode(2):d.setMode(3)}else r.isPoints?d.setMode(0):r.isSprite&&d.setMode(4);if(r.isInstancedMesh)d.renderInstances(_,M,r.count);else if(n.isInstancedBufferGeometry){const t=Math.min(n.instanceCount,n._maxInstanceCount);d.renderInstances(_,M,t)}else d.render(_,M)}},this.compile=function(t,e){m=ht.get(t),m.init(),g.push(m),t.traverseVisible((function(t){t.isLight&&t.layers.test(e.layers)&&(m.pushLight(t),t.castShadow&&m.pushShadow(t))})),m.setupLights(v.physicallyCorrectLights),t.traverse((function(e){const n=e.material;if(n)if(Array.isArray(n))for(let i=0;i<n.length;i++){Ut(n[i],t,e)}else Ut(n,t,e)})),g.pop(),m=null};let Pt=null;function Dt(){Nt.stop()}function It(){Nt.start()}const Nt=new ii;function zt(t,e,n,i){if(!1===t.visible)return;if(t.layers.test(e.layers))if(t.isGroup)n=t.renderOrder;else if(t.isLOD)!0===t.autoUpdate&&t.update(e);else if(t.isLight)m.pushLight(t),t.castShadow&&m.pushShadow(t);else if(t.isSprite){if(!t.frustumCulled||G.intersectsSprite(t)){i&&q.setFromMatrixPosition(t.matrixWorld).applyMatrix4(j);const e=at.update(t),r=t.material;r.visible&&d.push(t,e,r,n,q.z,null)}}else if((t.isMesh||t.isLine||t.isPoints)&&(t.isSkinnedMesh&&t.skeleton.frame!==$.render.frame&&(t.skeleton.update(),t.skeleton.frame=$.render.frame),!t.frustumCulled||G.intersectsObject(t))){i&&q.setFromMatrixPosition(t.matrixWorld).applyMatrix4(j);const e=at.update(t),r=t.material;if(Array.isArray(r)){const i=e.groups;for(let s=0,a=i.length;s<a;s++){const a=i[s],o=r[a.materialIndex];o&&o.visible&&d.push(t,e,o,n,q.z,a)}}else r.visible&&d.push(t,e,r,n,q.z,null)}const r=t.children;for(let t=0,s=r.length;t<s;t++)zt(r[t],e,n,i)}function Bt(t,e,n,i){const r=t.opaque,s=t.transmissive,o=t.transparent;m.setupLightsView(n),s.length>0&&function(t,e,n){if(null===W){const t=!0===a&&!0===Q.isWebGL2;W=new(t?Et:St)(1024,1024,{generateMipmaps:!0,type:null!==yt.convert(w)?w:x,minFilter:y,magFilter:p,wrapS:u,wrapT:u,useRenderToTexture:Z.has("WEBGL_multisampled_render_to_texture")})}const i=v.getRenderTarget();v.setRenderTarget(W),v.clear();const r=v.toneMapping;v.toneMapping=0,Ft(t,e,n),v.toneMapping=r,et.updateMultisampleRenderTarget(W),et.updateRenderTargetMipmap(W),v.setRenderTarget(i)}(r,e,n),i&&K.viewport(R.copy(i)),r.length>0&&Ft(r,e,n),s.length>0&&Ft(s,e,n),o.length>0&&Ft(o,e,n)}function Ft(t,e,n){const i=!0===e.isScene?e.overrideMaterial:null;for(let r=0,s=t.length;r<s;r++){const s=t[r],a=s.object,o=s.geometry,l=null===i?s.material:i,c=s.group;a.layers.test(n.layers)&&Ot(a,e,n,o,l,c)}}function Ot(t,e,n,i,r,s){t.onBeforeRender(v,e,n,i,r,s),t.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix),r.onBeforeRender(v,e,n,i,t,s),!0===r.transparent&&2===r.side?(r.side=1,r.needsUpdate=!0,v.renderBufferDirect(n,e,i,r,t,s),r.side=0,r.needsUpdate=!0,v.renderBufferDirect(n,e,i,r,t,s),r.side=2):v.renderBufferDirect(n,e,i,r,t,s),t.onAfterRender(v,e,n,i,r,s)}function Ut(t,e,n){!0!==e.isScene&&(e=J);const i=tt.get(t),r=m.state.lights,s=m.state.shadowsArray,a=r.state.version,o=ot.getParameters(t,r.state,s,e,n),l=ot.getProgramCacheKey(o);let c=i.programs;i.environment=t.isMeshStandardMaterial?e.environment:null,i.fog=e.fog,i.envMap=(t.isMeshStandardMaterial?it:nt).get(t.envMap||i.environment),void 0===c&&(t.addEventListener("dispose",Ct),c=new Map,i.programs=c);let h=c.get(l);if(void 0!==h){if(i.currentProgram===h&&i.lightsStateVersion===a)return Ht(t,o),h}else o.uniforms=ot.getUniforms(t),t.onBuild(n,o,v),t.onBeforeCompile(o,v),h=ot.acquireProgram(o,l),c.set(l,h),i.uniforms=o.uniforms;const u=i.uniforms;(t.isShaderMaterial||t.isRawShaderMaterial)&&!0!==t.clipping||(u.clippingPlanes=ut.uniform),Ht(t,o),i.needsLights=function(t){return t.isMeshLambertMaterial||t.isMeshToonMaterial||t.isMeshPhongMaterial||t.isMeshStandardMaterial||t.isShadowMaterial||t.isShaderMaterial&&!0===t.lights}(t),i.lightsStateVersion=a,i.needsLights&&(u.ambientLightColor.value=r.state.ambient,u.lightProbe.value=r.state.probe,u.directionalLights.value=r.state.directional,u.directionalLightShadows.value=r.state.directionalShadow,u.spotLights.value=r.state.spot,u.spotLightShadows.value=r.state.spotShadow,u.rectAreaLights.value=r.state.rectArea,u.ltc_1.value=r.state.rectAreaLTC1,u.ltc_2.value=r.state.rectAreaLTC2,u.pointLights.value=r.state.point,u.pointLightShadows.value=r.state.pointShadow,u.hemisphereLights.value=r.state.hemi,u.directionalShadowMap.value=r.state.directionalShadowMap,u.directionalShadowMatrix.value=r.state.directionalShadowMatrix,u.spotShadowMap.value=r.state.spotShadowMap,u.spotShadowMatrix.value=r.state.spotShadowMatrix,u.pointShadowMap.value=r.state.pointShadowMap,u.pointShadowMatrix.value=r.state.pointShadowMatrix);const d=h.getUniforms(),p=ts.seqWithValue(d.seq,u);return i.currentProgram=h,i.uniformsList=p,h}function Ht(t,e){const n=tt.get(t);n.outputEncoding=e.outputEncoding,n.instancing=e.instancing,n.skinning=e.skinning,n.morphTargets=e.morphTargets,n.morphNormals=e.morphNormals,n.morphTargetsCount=e.morphTargetsCount,n.numClippingPlanes=e.numClippingPlanes,n.numIntersection=e.numClipIntersection,n.vertexAlphas=e.vertexAlphas,n.vertexTangents=e.vertexTangents,n.toneMapping=e.toneMapping}Nt.setAnimationLoop((function(t){Pt&&Pt(t)})),"undefined"!=typeof window&&Nt.setContext(window),this.setAnimationLoop=function(t){Pt=t,Tt.setAnimationLoop(t),null===t?Nt.stop():Nt.start()},Tt.addEventListener("sessionstart",Dt),Tt.addEventListener("sessionend",It),this.render=function(t,e){if(void 0!==e&&!0!==e.isCamera)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");if(!0===_)return;!0===t.autoUpdate&&t.updateMatrixWorld(),null===e.parent&&e.updateMatrixWorld(),!0===Tt.enabled&&!0===Tt.isPresenting&&(!0===Tt.cameraAutoUpdate&&Tt.updateCamera(e),e=Tt.getCamera()),!0===t.isScene&&t.onBeforeRender(v,t,e,T),m=ht.get(t,g.length),m.init(),g.push(m),j.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),G.setFromProjectionMatrix(j),V=this.localClippingEnabled,k=ut.init(this.clippingPlanes,V,e),d=ct.get(t,f.length),d.init(),f.push(d),zt(t,e,0,v.sortObjects),d.finish(),!0===v.sortObjects&&d.sort(z,B),!0===k&&ut.beginShadows();const n=m.state.shadowsArray;if(dt.render(n,t,e),!0===k&&ut.endShadows(),!0===this.info.autoReset&&this.info.reset(),pt.render(d,t),m.setupLights(v.physicallyCorrectLights),e.isArrayCamera){const n=e.cameras;for(let e=0,i=n.length;e<i;e++){const i=n[e];Bt(d,t,i,i.viewport)}}else Bt(d,t,e);null!==T&&(et.updateMultisampleRenderTarget(T),et.updateRenderTargetMipmap(T)),!0===t.isScene&&t.onAfterRender(v,t,e),K.buffers.depth.setTest(!0),K.buffers.depth.setMask(!0),K.buffers.color.setMask(!0),K.setPolygonOffset(!1),xt.resetDefaultState(),A=-1,L=null,g.pop(),m=g.length>0?g[g.length-1]:null,f.pop(),d=f.length>0?f[f.length-1]:null},this.getActiveCubeFace=function(){return b},this.getActiveMipmapLevel=function(){return S},this.getRenderTarget=function(){return T},this.setRenderTargetTextures=function(t,e,n){tt.get(t.texture).__webglTexture=e,tt.get(t.depthTexture).__webglTexture=n;const i=tt.get(t);i.__hasExternalTextures=!0,i.__hasExternalTextures&&(i.__autoAllocateDepthBuffer=void 0===n,i.__autoAllocateDepthBuffer||t.useRenderToTexture&&(console.warn("render-to-texture extension was disabled because an external texture was provided"),t.useRenderToTexture=!1,t.useRenderbuffer=!0))},this.setRenderTargetFramebuffer=function(t,e){const n=tt.get(t);n.__webglFramebuffer=e,n.__useDefaultFramebuffer=void 0===e},this.setRenderTarget=function(t,e=0,n=0){T=t,b=e,S=n;let i=!0;if(t){const e=tt.get(t);void 0!==e.__useDefaultFramebuffer?(K.bindFramebuffer(36160,null),i=!1):void 0===e.__webglFramebuffer?et.setupRenderTarget(t):e.__hasExternalTextures&&et.rebindTextures(t,tt.get(t.texture).__webglTexture,tt.get(t.depthTexture).__webglTexture)}let r=null,s=!1,a=!1;if(t){const n=t.texture;(n.isDataTexture3D||n.isDataTexture2DArray)&&(a=!0);const i=tt.get(t).__webglFramebuffer;t.isWebGLCubeRenderTarget?(r=i[e],s=!0):r=t.useRenderbuffer?tt.get(t).__webglMultisampledFramebuffer:i,R.copy(t.viewport),C.copy(t.scissor),P=t.scissorTest}else R.copy(F).multiplyScalar(N).floor(),C.copy(O).multiplyScalar(N).floor(),P=U;if(K.bindFramebuffer(36160,r)&&Q.drawBuffers&&i){let e=!1;if(t)if(t.isWebGLMultipleRenderTargets){const n=t.texture;if(H.length!==n.length||36064!==H[0]){for(let t=0,e=n.length;t<e;t++)H[t]=36064+t;H.length=n.length,e=!0}}else 1===H.length&&36064===H[0]||(H[0]=36064,H.length=1,e=!0);else 1===H.length&&1029===H[0]||(H[0]=1029,H.length=1,e=!0);e&&(Q.isWebGL2?_t.drawBuffers(H):Z.get("WEBGL_draw_buffers").drawBuffersWEBGL(H))}if(K.viewport(R),K.scissor(C),K.setScissorTest(P),s){const i=tt.get(t.texture);_t.framebufferTexture2D(36160,36064,34069+e,i.__webglTexture,n)}else if(a){const i=tt.get(t.texture),r=e||0;_t.framebufferTextureLayer(36160,36064,i.__webglTexture,n||0,r)}A=-1},this.readRenderTargetPixels=function(t,e,n,i,r,s,a){if(!t||!t.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=tt.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){K.bindFramebuffer(36160,o);try{const a=t.texture,o=a.format,l=a.type;if(o!==E&&yt.convert(o)!==_t.getParameter(35739))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");const c=l===w&&(Z.has("EXT_color_buffer_half_float")||Q.isWebGL2&&Z.has("EXT_color_buffer_float"));if(!(l===x||yt.convert(l)===_t.getParameter(35738)||l===M&&(Q.isWebGL2||Z.has("OES_texture_float")||Z.has("WEBGL_color_buffer_float"))||c))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");36053===_t.checkFramebufferStatus(36160)?e>=0&&e<=t.width-i&&n>=0&&n<=t.height-r&&_t.readPixels(e,n,i,r,yt.convert(o),yt.convert(l),s):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{const t=null!==T?tt.get(T).__webglFramebuffer:null;K.bindFramebuffer(36160,t)}}},this.copyFramebufferToTexture=function(t,e,n=0){if(!0!==e.isFramebufferTexture)return void console.error("THREE.WebGLRenderer: copyFramebufferToTexture() can only be used with FramebufferTexture.");const i=Math.pow(2,-n),r=Math.floor(e.image.width*i),s=Math.floor(e.image.height*i);et.setTexture2D(e,0),_t.copyTexSubImage2D(3553,n,0,0,t.x,t.y,r,s),K.unbindTexture()},this.copyTextureToTexture=function(t,e,n,i=0){const r=e.image.width,s=e.image.height,a=yt.convert(n.format),o=yt.convert(n.type);et.setTexture2D(n,0),_t.pixelStorei(37440,n.flipY),_t.pixelStorei(37441,n.premultiplyAlpha),_t.pixelStorei(3317,n.unpackAlignment),e.isDataTexture?_t.texSubImage2D(3553,i,t.x,t.y,r,s,a,o,e.image.data):e.isCompressedTexture?_t.compressedTexSubImage2D(3553,i,t.x,t.y,e.mipmaps[0].width,e.mipmaps[0].height,a,e.mipmaps[0].data):_t.texSubImage2D(3553,i,t.x,t.y,a,o,e.image),0===i&&n.generateMipmaps&&_t.generateMipmap(3553),K.unbindTexture()},this.copyTextureToTexture3D=function(t,e,n,i,r=0){if(v.isWebGL1Renderer)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");const s=t.max.x-t.min.x+1,a=t.max.y-t.min.y+1,o=t.max.z-t.min.z+1,l=yt.convert(i.format),c=yt.convert(i.type);let h;if(i.isDataTexture3D)et.setTexture3D(i,0),h=32879;else{if(!i.isDataTexture2DArray)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");et.setTexture2DArray(i,0),h=35866}_t.pixelStorei(37440,i.flipY),_t.pixelStorei(37441,i.premultiplyAlpha),_t.pixelStorei(3317,i.unpackAlignment);const u=_t.getParameter(3314),d=_t.getParameter(32878),p=_t.getParameter(3316),m=_t.getParameter(3315),f=_t.getParameter(32877),g=n.isCompressedTexture?n.mipmaps[0]:n.image;_t.pixelStorei(3314,g.width),_t.pixelStorei(32878,g.height),_t.pixelStorei(3316,t.min.x),_t.pixelStorei(3315,t.min.y),_t.pixelStorei(32877,t.min.z),n.isDataTexture||n.isDataTexture3D?_t.texSubImage3D(h,r,e.x,e.y,e.z,s,a,o,l,c,g.data):n.isCompressedTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),_t.compressedTexSubImage3D(h,r,e.x,e.y,e.z,s,a,o,l,g.data)):_t.texSubImage3D(h,r,e.x,e.y,e.z,s,a,o,l,c,g),_t.pixelStorei(3314,u),_t.pixelStorei(32878,d),_t.pixelStorei(3316,p),_t.pixelStorei(3315,m),_t.pixelStorei(32877,f),0===r&&i.generateMipmaps&&_t.generateMipmap(h),K.unbindTexture()},this.initTexture=function(t){et.setTexture2D(t,0),K.unbindTexture()},this.resetState=function(){b=0,S=0,T=null,K.reset(),xt.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}Ys.prototype.isWebGLRenderer=!0;class Zs extends Ys{}Zs.prototype.isWebGL1Renderer=!0;class Qs{constructor(t,e=25e-5){this.name="",this.color=new Ze(t),this.density=e}clone(){return new Qs(this.color,this.density)}toJSON(){return{type:"FogExp2",color:this.color.getHex(),density:this.density}}}Qs.prototype.isFogExp2=!0;class Ks{constructor(t,e=1,n=1e3){this.name="",this.color=new Ze(t),this.near=e,this.far=n}clone(){return new Ks(this.color,this.near,this.far)}toJSON(){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}}}Ks.prototype.isFog=!0;class $s extends Ce{constructor(){super(),this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),null!==t.background&&(this.background=t.background.clone()),null!==t.environment&&(this.environment=t.environment.clone()),null!==t.fog&&(this.fog=t.fog.clone()),null!==t.overrideMaterial&&(this.overrideMaterial=t.overrideMaterial.clone()),this.autoUpdate=t.autoUpdate,this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return null!==this.fog&&(e.object.fog=this.fog.toJSON()),e}}$s.prototype.isScene=!0;class ta{constructor(t,e){this.array=t,this.stride=e,this.count=void 0!==t?t.length/e:0,this.usage=Z,this.updateRange={offset:0,count:-1},this.version=0,this.uuid=rt()}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,n){t*=this.stride,n*=e.stride;for(let i=0,r=this.stride;i<r;i++)this.array[t+i]=e.array[n+i];return this}set(t,e=0){return this.array.set(t,e),this}clone(t){void 0===t.arrayBuffers&&(t.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=rt()),void 0===t.arrayBuffers[this.array.buffer._uuid]&&(t.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const e=new this.array.constructor(t.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(e,this.stride);return n.setUsage(this.usage),n}onUpload(t){return this.onUploadCallback=t,this}toJSON(t){return void 0===t.arrayBuffers&&(t.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=rt()),void 0===t.arrayBuffers[this.array.buffer._uuid]&&(t.arrayBuffers[this.array.buffer._uuid]=Array.prototype.slice.call(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}ta.prototype.isInterleavedBuffer=!0;const ea=new Lt;class na{constructor(t,e,n,i=!1){this.name="",this.data=t,this.itemSize=e,this.offset=n,this.normalized=!0===i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(t){this.data.needsUpdate=t}applyMatrix4(t){for(let e=0,n=this.data.count;e<n;e++)ea.x=this.getX(e),ea.y=this.getY(e),ea.z=this.getZ(e),ea.applyMatrix4(t),this.setXYZ(e,ea.x,ea.y,ea.z);return this}applyNormalMatrix(t){for(let e=0,n=this.count;e<n;e++)ea.x=this.getX(e),ea.y=this.getY(e),ea.z=this.getZ(e),ea.applyNormalMatrix(t),this.setXYZ(e,ea.x,ea.y,ea.z);return this}transformDirection(t){for(let e=0,n=this.count;e<n;e++)ea.x=this.getX(e),ea.y=this.getY(e),ea.z=this.getZ(e),ea.transformDirection(t),this.setXYZ(e,ea.x,ea.y,ea.z);return this}setX(t,e){return this.data.array[t*this.data.stride+this.offset]=e,this}setY(t,e){return this.data.array[t*this.data.stride+this.offset+1]=e,this}setZ(t,e){return this.data.array[t*this.data.stride+this.offset+2]=e,this}setW(t,e){return this.data.array[t*this.data.stride+this.offset+3]=e,this}getX(t){return this.data.array[t*this.data.stride+this.offset]}getY(t){return this.data.array[t*this.data.stride+this.offset+1]}getZ(t){return this.data.array[t*this.data.stride+this.offset+2]}getW(t){return this.data.array[t*this.data.stride+this.offset+3]}setXY(t,e,n){return t=t*this.data.stride+this.offset,this.data.array[t+0]=e,this.data.array[t+1]=n,this}setXYZ(t,e,n,i){return t=t*this.data.stride+this.offset,this.data.array[t+0]=e,this.data.array[t+1]=n,this.data.array[t+2]=i,this}setXYZW(t,e,n,i,r){return t=t*this.data.stride+this.offset,this.data.array[t+0]=e,this.data.array[t+1]=n,this.data.array[t+2]=i,this.data.array[t+3]=r,this}clone(t){if(void 0===t){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.");const t=[];for(let e=0;e<this.count;e++){const n=e*this.data.stride+this.offset;for(let e=0;e<this.itemSize;e++)t.push(this.data.array[n+e])}return new tn(new this.array.constructor(t),this.itemSize,this.normalized)}return void 0===t.interleavedBuffers&&(t.interleavedBuffers={}),void 0===t.interleavedBuffers[this.data.uuid]&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new na(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(t){if(void 0===t){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.");const t=[];for(let e=0;e<this.count;e++){const n=e*this.data.stride+this.offset;for(let e=0;e<this.itemSize;e++)t.push(this.data.array[n+e])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}return void 0===t.interleavedBuffers&&(t.interleavedBuffers={}),void 0===t.interleavedBuffers[this.data.uuid]&&(t.interleavedBuffers[this.data.uuid]=this.data.toJSON(t)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}na.prototype.isInterleavedBufferAttribute=!0;class ia extends Ve{constructor(t){super(),this.type="SpriteMaterial",this.color=new Ze(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!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}}let ra;ia.prototype.isSpriteMaterial=!0;const sa=new Lt,aa=new Lt,oa=new Lt,la=new dt,ca=new dt,ha=new se,ua=new Lt,da=new Lt,pa=new Lt,ma=new dt,fa=new dt,ga=new dt;class va extends Ce{constructor(t){if(super(),this.type="Sprite",void 0===ra){ra=new xn;const t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),e=new ta(t,5);ra.setIndex([0,1,2,0,2,3]),ra.setAttribute("position",new na(e,3,0,!1)),ra.setAttribute("uv",new na(e,2,3,!1))}this.geometry=ra,this.material=void 0!==t?t:new ia,this.center=new dt(.5,.5)}raycast(t,e){null===t.camera&&console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),aa.setFromMatrixScale(this.matrixWorld),ha.copy(t.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(t.camera.matrixWorldInverse,this.matrixWorld),oa.setFromMatrixPosition(this.modelViewMatrix),t.camera.isPerspectiveCamera&&!1===this.material.sizeAttenuation&&aa.multiplyScalar(-oa.z);const n=this.material.rotation;let i,r;0!==n&&(r=Math.cos(n),i=Math.sin(n));const s=this.center;ya(ua.set(-.5,-.5,0),oa,s,aa,i,r),ya(da.set(.5,-.5,0),oa,s,aa,i,r),ya(pa.set(.5,.5,0),oa,s,aa,i,r),ma.set(0,0),fa.set(1,0),ga.set(1,1);let a=t.ray.intersectTriangle(ua,da,pa,!1,sa);if(null===a&&(ya(da.set(-.5,.5,0),oa,s,aa,i,r),fa.set(0,1),a=t.ray.intersectTriangle(ua,pa,da,!1,sa),null===a))return;const o=t.ray.origin.distanceTo(sa);o<t.near||o>t.far||e.push({distance:o,point:sa.clone(),uv:Ge.getUV(sa,ua,da,pa,ma,fa,ga,new dt),face:null,object:this})}copy(t){return super.copy(t),void 0!==t.center&&this.center.copy(t.center),this.material=t.material,this}}function ya(t,e,n,i,r,s){la.subVectors(t,n).addScalar(.5).multiply(i),void 0!==r?(ca.x=s*la.x-r*la.y,ca.y=r*la.x+s*la.y):ca.copy(la),t.copy(e),t.x+=ca.x,t.y+=ca.y,t.applyMatrix4(ha)}va.prototype.isSprite=!0;const xa=new Lt,_a=new Lt;class ba extends Ce{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(t){super.copy(t,!1);const e=t.levels;for(let t=0,n=e.length;t<n;t++){const n=e[t];this.addLevel(n.object.clone(),n.distance)}return this.autoUpdate=t.autoUpdate,this}addLevel(t,e=0){e=Math.abs(e);const n=this.levels;let i;for(i=0;i<n.length&&!(e<n[i].distance);i++);return n.splice(i,0,{distance:e,object:t}),this.add(t),this}getCurrentLevel(){return this._currentLevel}getObjectForDistance(t){const e=this.levels;if(e.length>0){let n,i;for(n=1,i=e.length;n<i&&!(t<e[n].distance);n++);return e[n-1].object}return null}raycast(t,e){if(this.levels.length>0){xa.setFromMatrixPosition(this.matrixWorld);const n=t.ray.origin.distanceTo(xa);this.getObjectForDistance(n).raycast(t,e)}}update(t){const e=this.levels;if(e.length>1){xa.setFromMatrixPosition(t.matrixWorld),_a.setFromMatrixPosition(this.matrixWorld);const n=xa.distanceTo(_a)/t.zoom;let i,r;for(e[0].object.visible=!0,i=1,r=e.length;i<r&&n>=e[i].distance;i++)e[i-1].object.visible=!1,e[i].object.visible=!0;for(this._currentLevel=i-1;i<r;i++)e[i].object.visible=!1}}toJSON(t){const e=super.toJSON(t);!1===this.autoUpdate&&(e.object.autoUpdate=!1),e.object.levels=[];const n=this.levels;for(let t=0,i=n.length;t<i;t++){const i=n[t];e.object.levels.push({object:i.object.uuid,distance:i.distance})}return e}}const Ma=new Lt,wa=new wt,Sa=new wt,Ta=new Lt,Ea=new se;class Aa extends Fn{constructor(t,e){super(t,e),this.type="SkinnedMesh",this.bindMode="attached",this.bindMatrix=new se,this.bindMatrixInverse=new se}copy(t){return super.copy(t),this.bindMode=t.bindMode,this.bindMatrix.copy(t.bindMatrix),this.bindMatrixInverse.copy(t.bindMatrixInverse),this.skeleton=t.skeleton,this}bind(t,e){this.skeleton=t,void 0===e&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),e=this.matrixWorld),this.bindMatrix.copy(e),this.bindMatrixInverse.copy(e).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const t=new wt,e=this.geometry.attributes.skinWeight;for(let n=0,i=e.count;n<i;n++){t.x=e.getX(n),t.y=e.getY(n),t.z=e.getZ(n),t.w=e.getW(n);const i=1/t.manhattanLength();i!==1/0?t.multiplyScalar(i):t.set(1,0,0,0),e.setXYZW(n,t.x,t.y,t.z,t.w)}}updateMatrixWorld(t){super.updateMatrixWorld(t),"attached"===this.bindMode?this.bindMatrixInverse.copy(this.matrixWorld).invert():"detached"===this.bindMode?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}boneTransform(t,e){const n=this.skeleton,i=this.geometry;wa.fromBufferAttribute(i.attributes.skinIndex,t),Sa.fromBufferAttribute(i.attributes.skinWeight,t),Ma.copy(e).applyMatrix4(this.bindMatrix),e.set(0,0,0);for(let t=0;t<4;t++){const i=Sa.getComponent(t);if(0!==i){const r=wa.getComponent(t);Ea.multiplyMatrices(n.bones[r].matrixWorld,n.boneInverses[r]),e.addScaledVector(Ta.copy(Ma).applyMatrix4(Ea),i)}}return e.applyMatrix4(this.bindMatrixInverse)}}Aa.prototype.isSkinnedMesh=!0;class La extends Ce{constructor(){super(),this.type="Bone"}}La.prototype.isBone=!0;class Ra extends bt{constructor(t=null,e=1,n=1,i,r,s,a,o,l=1003,c=1003,h,u){super(null,s,a,o,l,c,i,r,h,u),this.image={data:t,width:e,height:n},this.magFilter=l,this.minFilter=c,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}Ra.prototype.isDataTexture=!0;const Ca=new se,Pa=new se;class Da{constructor(t=[],e=[]){this.uuid=rt(),this.bones=t.slice(0),this.boneInverses=e,this.boneMatrices=null,this.boneTexture=null,this.boneTextureSize=0,this.frame=-1,this.init()}init(){const t=this.bones,e=this.boneInverses;if(this.boneMatrices=new Float32Array(16*t.length),0===e.length)this.calculateInverses();else if(t.length!==e.length){console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let t=0,e=this.bones.length;t<e;t++)this.boneInverses.push(new se)}}calculateInverses(){this.boneInverses.length=0;for(let t=0,e=this.bones.length;t<e;t++){const e=new se;this.bones[t]&&e.copy(this.bones[t].matrixWorld).invert(),this.boneInverses.push(e)}}pose(){for(let t=0,e=this.bones.length;t<e;t++){const e=this.bones[t];e&&e.matrixWorld.copy(this.boneInverses[t]).invert()}for(let t=0,e=this.bones.length;t<e;t++){const e=this.bones[t];e&&(e.parent&&e.parent.isBone?(e.matrix.copy(e.parent.matrixWorld).invert(),e.matrix.multiply(e.matrixWorld)):e.matrix.copy(e.matrixWorld),e.matrix.decompose(e.position,e.quaternion,e.scale))}}update(){const t=this.bones,e=this.boneInverses,n=this.boneMatrices,i=this.boneTexture;for(let i=0,r=t.length;i<r;i++){const r=t[i]?t[i].matrixWorld:Pa;Ca.multiplyMatrices(r,e[i]),Ca.toArray(n,16*i)}null!==i&&(i.needsUpdate=!0)}clone(){return new Da(this.bones,this.boneInverses)}computeBoneTexture(){let t=Math.sqrt(4*this.bones.length);t=ct(t),t=Math.max(t,4);const e=new Float32Array(t*t*4);e.set(this.boneMatrices);const n=new Ra(e,t,t,E,M);return n.needsUpdate=!0,this.boneMatrices=e,this.boneTexture=n,this.boneTextureSize=t,this}getBoneByName(t){for(let e=0,n=this.bones.length;e<n;e++){const n=this.bones[e];if(n.name===t)return n}}dispose(){null!==this.boneTexture&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(t,e){this.uuid=t.uuid;for(let n=0,i=t.bones.length;n<i;n++){const i=t.bones[n];let r=e[i];void 0===r&&(console.warn("THREE.Skeleton: No bone found with UUID:",i),r=new La),this.bones.push(r),this.boneInverses.push((new se).fromArray(t.boneInverses[n]))}return this.init(),this}toJSON(){const t={metadata:{version:4.5,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};t.uuid=this.uuid;const e=this.bones,n=this.boneInverses;for(let i=0,r=e.length;i<r;i++){const r=e[i];t.bones.push(r.uuid);const s=n[i];t.boneInverses.push(s.toArray())}return t}}class Ia extends tn{constructor(t,e,n,i=1){"number"==typeof n&&(i=n,n=!1,console.error("THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.")),super(t,e,n),this.meshPerAttribute=i}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}toJSON(){const t=super.toJSON();return t.meshPerAttribute=this.meshPerAttribute,t.isInstancedBufferAttribute=!0,t}}Ia.prototype.isInstancedBufferAttribute=!0;const Na=new se,za=new se,Ba=[],Fa=new Fn;class Oa extends Fn{constructor(t,e,n){super(t,e),this.instanceMatrix=new Ia(new Float32Array(16*n),16),this.instanceColor=null,this.count=n,this.frustumCulled=!1}copy(t){return super.copy(t),this.instanceMatrix.copy(t.instanceMatrix),null!==t.instanceColor&&(this.instanceColor=t.instanceColor.clone()),this.count=t.count,this}getColorAt(t,e){e.fromArray(this.instanceColor.array,3*t)}getMatrixAt(t,e){e.fromArray(this.instanceMatrix.array,16*t)}raycast(t,e){const n=this.matrixWorld,i=this.count;if(Fa.geometry=this.geometry,Fa.material=this.material,void 0!==Fa.material)for(let r=0;r<i;r++){this.getMatrixAt(r,Na),za.multiplyMatrices(n,Na),Fa.matrixWorld=za,Fa.raycast(t,Ba);for(let t=0,n=Ba.length;t<n;t++){const n=Ba[t];n.instanceId=r,n.object=this,e.push(n)}Ba.length=0}}setColorAt(t,e){null===this.instanceColor&&(this.instanceColor=new Ia(new Float32Array(3*this.instanceMatrix.count),3)),e.toArray(this.instanceColor.array,3*t)}setMatrixAt(t,e){e.toArray(this.instanceMatrix.array,16*t)}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"})}}Oa.prototype.isInstancedMesh=!0;class Ua extends Ve{constructor(t){super(),this.type="LineBasicMaterial",this.color=new Ze(16777215),this.linewidth=1,this.linecap="round",this.linejoin="round",this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.linewidth=t.linewidth,this.linecap=t.linecap,this.linejoin=t.linejoin,this}}Ua.prototype.isLineBasicMaterial=!0;const Ha=new Lt,Ga=new Lt,ka=new se,Va=new re,Wa=new Zt;class ja extends Ce{constructor(t=new xn,e=new Ua){super(),this.type="Line",this.geometry=t,this.material=e,this.updateMorphTargets()}copy(t){return super.copy(t),this.material=t.material,this.geometry=t.geometry,this}computeLineDistances(){const t=this.geometry;if(t.isBufferGeometry)if(null===t.index){const e=t.attributes.position,n=[0];for(let t=1,i=e.count;t<i;t++)Ha.fromBufferAttribute(e,t-1),Ga.fromBufferAttribute(e,t),n[t]=n[t-1],n[t]+=Ha.distanceTo(Ga);t.setAttribute("lineDistance",new hn(n,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");else t.isGeometry&&console.error("THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.");return this}raycast(t,e){const n=this.geometry,i=this.matrixWorld,r=t.params.Line.threshold,s=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),Wa.copy(n.boundingSphere),Wa.applyMatrix4(i),Wa.radius+=r,!1===t.ray.intersectsSphere(Wa))return;ka.copy(i).invert(),Va.copy(t.ray).applyMatrix4(ka);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=new Lt,c=new Lt,h=new Lt,u=new Lt,d=this.isLineSegments?2:1;if(n.isBufferGeometry){const i=n.index,r=n.attributes.position;if(null!==i){for(let n=Math.max(0,s.start),a=Math.min(i.count,s.start+s.count)-1;n<a;n+=d){const s=i.getX(n),a=i.getX(n+1);l.fromBufferAttribute(r,s),c.fromBufferAttribute(r,a);if(Va.distanceSqToSegment(l,c,u,h)>o)continue;u.applyMatrix4(this.matrixWorld);const d=t.ray.origin.distanceTo(u);d<t.near||d>t.far||e.push({distance:d,point:h.clone().applyMatrix4(this.matrixWorld),index:n,face:null,faceIndex:null,object:this})}}else{for(let n=Math.max(0,s.start),i=Math.min(r.count,s.start+s.count)-1;n<i;n+=d){l.fromBufferAttribute(r,n),c.fromBufferAttribute(r,n+1);if(Va.distanceSqToSegment(l,c,u,h)>o)continue;u.applyMatrix4(this.matrixWorld);const i=t.ray.origin.distanceTo(u);i<t.near||i>t.far||e.push({distance:i,point:h.clone().applyMatrix4(this.matrixWorld),index:n,face:null,faceIndex:null,object:this})}}}else n.isGeometry&&console.error("THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}updateMorphTargets(){const t=this.geometry;if(t.isBufferGeometry){const e=t.morphAttributes,n=Object.keys(e);if(n.length>0){const t=e[n[0]];if(void 0!==t){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,n=t.length;e<n;e++){const n=t[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[n]=e}}}}else{const e=t.morphTargets;void 0!==e&&e.length>0&&console.error("THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.")}}}ja.prototype.isLine=!0;const qa=new Lt,Xa=new Lt;class Ja extends ja{constructor(t,e){super(t,e),this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(t.isBufferGeometry)if(null===t.index){const e=t.attributes.position,n=[];for(let t=0,i=e.count;t<i;t+=2)qa.fromBufferAttribute(e,t),Xa.fromBufferAttribute(e,t+1),n[t]=0===t?0:n[t-1],n[t+1]=n[t]+qa.distanceTo(Xa);t.setAttribute("lineDistance",new hn(n,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");else t.isGeometry&&console.error("THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.");return this}}Ja.prototype.isLineSegments=!0;class Ya extends ja{constructor(t,e){super(t,e),this.type="LineLoop"}}Ya.prototype.isLineLoop=!0;class Za extends Ve{constructor(t){super(),this.type="PointsMaterial",this.color=new Ze(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this}}Za.prototype.isPointsMaterial=!0;const Qa=new se,Ka=new re,$a=new Zt,to=new Lt;class eo extends Ce{constructor(t=new xn,e=new Za){super(),this.type="Points",this.geometry=t,this.material=e,this.updateMorphTargets()}copy(t){return super.copy(t),this.material=t.material,this.geometry=t.geometry,this}raycast(t,e){const n=this.geometry,i=this.matrixWorld,r=t.params.Points.threshold,s=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),$a.copy(n.boundingSphere),$a.applyMatrix4(i),$a.radius+=r,!1===t.ray.intersectsSphere($a))return;Qa.copy(i).invert(),Ka.copy(t.ray).applyMatrix4(Qa);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a;if(n.isBufferGeometry){const r=n.index,a=n.attributes.position;if(null!==r){for(let n=Math.max(0,s.start),l=Math.min(r.count,s.start+s.count);n<l;n++){const s=r.getX(n);to.fromBufferAttribute(a,s),no(to,s,o,i,t,e,this)}}else{for(let n=Math.max(0,s.start),r=Math.min(a.count,s.start+s.count);n<r;n++)to.fromBufferAttribute(a,n),no(to,n,o,i,t,e,this)}}else console.error("THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}updateMorphTargets(){const t=this.geometry;if(t.isBufferGeometry){const e=t.morphAttributes,n=Object.keys(e);if(n.length>0){const t=e[n[0]];if(void 0!==t){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,n=t.length;e<n;e++){const n=t[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[n]=e}}}}else{const e=t.morphTargets;void 0!==e&&e.length>0&&console.error("THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.")}}}function no(t,e,n,i,r,s,a){const o=Ka.distanceSqToPoint(t);if(o<n){const n=new Lt;Ka.closestPointToPoint(t,n),n.applyMatrix4(i);const l=r.ray.origin.distanceTo(n);if(l<r.near||l>r.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:n,index:e,face:null,object:a})}}eo.prototype.isPoints=!0;class io extends bt{constructor(t,e,n,i,r,s,a,o,l){super(t,e,n,i,r,s,a,o,l),this.format=void 0!==a?a:T,this.minFilter=void 0!==s?s:g,this.magFilter=void 0!==r?r:g,this.generateMipmaps=!1;const c=this;"requestVideoFrameCallback"in t&&t.requestVideoFrameCallback((function e(){c.needsUpdate=!0,t.requestVideoFrameCallback(e)}))}clone(){return new this.constructor(this.image).copy(this)}update(){const t=this.image;!1==="requestVideoFrameCallback"in t&&t.readyState>=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}io.prototype.isVideoTexture=!0;class ro extends bt{constructor(t,e,n){super({width:t,height:e}),this.format=n,this.magFilter=p,this.minFilter=p,this.generateMipmaps=!1,this.needsUpdate=!0}}ro.prototype.isFramebufferTexture=!0;class so extends bt{constructor(t,e,n,i,r,s,a,o,l,c,h,u){super(null,s,a,o,l,c,i,r,h,u),this.image={width:e,height:n},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}}so.prototype.isCompressedTexture=!0;class ao extends bt{constructor(t,e,n,i,r,s,a,o,l){super(t,e,n,i,r,s,a,o,l),this.needsUpdate=!0}}ao.prototype.isCanvasTexture=!0;class oo extends xn{constructor(t=1,e=8,n=0,i=2*Math.PI){super(),this.type="CircleGeometry",this.parameters={radius:t,segments:e,thetaStart:n,thetaLength:i},e=Math.max(3,e);const r=[],s=[],a=[],o=[],l=new Lt,c=new dt;s.push(0,0,0),a.push(0,0,1),o.push(.5,.5);for(let r=0,h=3;r<=e;r++,h+=3){const u=n+r/e*i;l.x=t*Math.cos(u),l.y=t*Math.sin(u),s.push(l.x,l.y,l.z),a.push(0,0,1),c.x=(s[h]/t+1)/2,c.y=(s[h+1]/t+1)/2,o.push(c.x,c.y)}for(let t=1;t<=e;t++)r.push(t,t+1,0);this.setIndex(r),this.setAttribute("position",new hn(s,3)),this.setAttribute("normal",new hn(a,3)),this.setAttribute("uv",new hn(o,2))}static fromJSON(t){return new oo(t.radius,t.segments,t.thetaStart,t.thetaLength)}}class lo extends xn{constructor(t=1,e=1,n=1,i=8,r=1,s=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:t,radiusBottom:e,height:n,radialSegments:i,heightSegments:r,openEnded:s,thetaStart:a,thetaLength:o};const l=this;i=Math.floor(i),r=Math.floor(r);const c=[],h=[],u=[],d=[];let p=0;const m=[],f=n/2;let g=0;function v(n){const r=p,s=new dt,m=new Lt;let v=0;const y=!0===n?t:e,x=!0===n?1:-1;for(let t=1;t<=i;t++)h.push(0,f*x,0),u.push(0,x,0),d.push(.5,.5),p++;const _=p;for(let t=0;t<=i;t++){const e=t/i*o+a,n=Math.cos(e),r=Math.sin(e);m.x=y*r,m.y=f*x,m.z=y*n,h.push(m.x,m.y,m.z),u.push(0,x,0),s.x=.5*n+.5,s.y=.5*r*x+.5,d.push(s.x,s.y),p++}for(let t=0;t<i;t++){const e=r+t,i=_+t;!0===n?c.push(i,i+1,e):c.push(i+1,i,e),v+=3}l.addGroup(g,v,!0===n?1:2),g+=v}!function(){const s=new Lt,v=new Lt;let y=0;const x=(e-t)/n;for(let l=0;l<=r;l++){const c=[],g=l/r,y=g*(e-t)+t;for(let t=0;t<=i;t++){const e=t/i,r=e*o+a,l=Math.sin(r),m=Math.cos(r);v.x=y*l,v.y=-g*n+f,v.z=y*m,h.push(v.x,v.y,v.z),s.set(l,x,m).normalize(),u.push(s.x,s.y,s.z),d.push(e,1-g),c.push(p++)}m.push(c)}for(let t=0;t<i;t++)for(let e=0;e<r;e++){const n=m[e][t],i=m[e+1][t],r=m[e+1][t+1],s=m[e][t+1];c.push(n,i,s),c.push(i,r,s),y+=6}l.addGroup(g,y,0),g+=y}(),!1===s&&(t>0&&v(!0),e>0&&v(!1)),this.setIndex(c),this.setAttribute("position",new hn(h,3)),this.setAttribute("normal",new hn(u,3)),this.setAttribute("uv",new hn(d,2))}static fromJSON(t){return new lo(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class co extends lo{constructor(t=1,e=1,n=8,i=1,r=!1,s=0,a=2*Math.PI){super(0,t,e,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(t){return new co(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class ho extends xn{constructor(t=[],e=[],n=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:e,radius:n,detail:i};const r=[],s=[];function a(t,e,n,i){const r=i+1,s=[];for(let i=0;i<=r;i++){s[i]=[];const a=t.clone().lerp(n,i/r),o=e.clone().lerp(n,i/r),l=r-i;for(let t=0;t<=l;t++)s[i][t]=0===t&&i===r?a:a.clone().lerp(o,t/l)}for(let t=0;t<r;t++)for(let e=0;e<2*(r-t)-1;e++){const n=Math.floor(e/2);e%2==0?(o(s[t][n+1]),o(s[t+1][n]),o(s[t][n])):(o(s[t][n+1]),o(s[t+1][n+1]),o(s[t+1][n]))}}function o(t){r.push(t.x,t.y,t.z)}function l(e,n){const i=3*e;n.x=t[i+0],n.y=t[i+1],n.z=t[i+2]}function c(t,e,n,i){i<0&&1===t.x&&(s[e]=t.x-1),0===n.x&&0===n.z&&(s[e]=i/2/Math.PI+.5)}function h(t){return Math.atan2(t.z,-t.x)}!function(t){const n=new Lt,i=new Lt,r=new Lt;for(let s=0;s<e.length;s+=3)l(e[s+0],n),l(e[s+1],i),l(e[s+2],r),a(n,i,r,t)}(i),function(t){const e=new Lt;for(let n=0;n<r.length;n+=3)e.x=r[n+0],e.y=r[n+1],e.z=r[n+2],e.normalize().multiplyScalar(t),r[n+0]=e.x,r[n+1]=e.y,r[n+2]=e.z}(n),function(){const t=new Lt;for(let n=0;n<r.length;n+=3){t.x=r[n+0],t.y=r[n+1],t.z=r[n+2];const i=h(t)/2/Math.PI+.5,a=(e=t,Math.atan2(-e.y,Math.sqrt(e.x*e.x+e.z*e.z))/Math.PI+.5);s.push(i,1-a)}var e;(function(){const t=new Lt,e=new Lt,n=new Lt,i=new Lt,a=new dt,o=new dt,l=new dt;for(let u=0,d=0;u<r.length;u+=9,d+=6){t.set(r[u+0],r[u+1],r[u+2]),e.set(r[u+3],r[u+4],r[u+5]),n.set(r[u+6],r[u+7],r[u+8]),a.set(s[d+0],s[d+1]),o.set(s[d+2],s[d+3]),l.set(s[d+4],s[d+5]),i.copy(t).add(e).add(n).divideScalar(3);const p=h(i);c(a,d+0,t,p),c(o,d+2,e,p),c(l,d+4,n,p)}})(),function(){for(let t=0;t<s.length;t+=6){const e=s[t+0],n=s[t+2],i=s[t+4],r=Math.max(e,n,i),a=Math.min(e,n,i);r>.9&&a<.1&&(e<.2&&(s[t+0]+=1),n<.2&&(s[t+2]+=1),i<.2&&(s[t+4]+=1))}}()}(),this.setAttribute("position",new hn(r,3)),this.setAttribute("normal",new hn(r.slice(),3)),this.setAttribute("uv",new hn(s,2)),0===i?this.computeVertexNormals():this.normalizeNormals()}static fromJSON(t){return new ho(t.vertices,t.indices,t.radius,t.details)}}class uo extends ho{constructor(t=1,e=0){const n=(1+Math.sqrt(5))/2,i=1/n;super([-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,-i,-n,0,-i,n,0,i,-n,0,i,n,-i,-n,0,-i,n,0,i,-n,0,i,n,0,-n,0,-i,n,0,-i,-n,0,i,n,0,i],[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],t,e),this.type="DodecahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new uo(t.radius,t.detail)}}const po=new Lt,mo=new Lt,fo=new Lt,go=new Ge;class vo extends xn{constructor(t=null,e=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:t,thresholdAngle:e},null!==t){const n=4,i=Math.pow(10,n),r=Math.cos(nt*e),s=t.getIndex(),a=t.getAttribute("position"),o=s?s.count:a.count,l=[0,0,0],c=["a","b","c"],h=new Array(3),u={},d=[];for(let t=0;t<o;t+=3){s?(l[0]=s.getX(t),l[1]=s.getX(t+1),l[2]=s.getX(t+2)):(l[0]=t,l[1]=t+1,l[2]=t+2);const{a:e,b:n,c:o}=go;if(e.fromBufferAttribute(a,l[0]),n.fromBufferAttribute(a,l[1]),o.fromBufferAttribute(a,l[2]),go.getNormal(fo),h[0]=`${Math.round(e.x*i)},${Math.round(e.y*i)},${Math.round(e.z*i)}`,h[1]=`${Math.round(n.x*i)},${Math.round(n.y*i)},${Math.round(n.z*i)}`,h[2]=`${Math.round(o.x*i)},${Math.round(o.y*i)},${Math.round(o.z*i)}`,h[0]!==h[1]&&h[1]!==h[2]&&h[2]!==h[0])for(let t=0;t<3;t++){const e=(t+1)%3,n=h[t],i=h[e],s=go[c[t]],a=go[c[e]],o=`${n}_${i}`,p=`${i}_${n}`;p in u&&u[p]?(fo.dot(u[p].normal)<=r&&(d.push(s.x,s.y,s.z),d.push(a.x,a.y,a.z)),u[p]=null):o in u||(u[o]={index0:l[t],index1:l[e],normal:fo.clone()})}}for(const t in u)if(u[t]){const{index0:e,index1:n}=u[t];po.fromBufferAttribute(a,e),mo.fromBufferAttribute(a,n),d.push(po.x,po.y,po.z),d.push(mo.x,mo.y,mo.z)}this.setAttribute("position",new hn(d,3))}}}class yo{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(t,e){const n=this.getUtoTmapping(t);return this.getPoint(n,e)}getPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPoint(n/t));return e}getSpacedPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPointAt(n/t));return e}getLength(){const t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const e=[];let n,i=this.getPoint(0),r=0;e.push(0);for(let s=1;s<=t;s++)n=this.getPoint(s/t),r+=n.distanceTo(i),e.push(r),i=n;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e){const n=this.getLengths();let i=0;const r=n.length;let s;s=e||t*n[r-1];let a,o=0,l=r-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),a=n[i]-s,a<0)o=i+1;else{if(!(a>0)){l=i;break}l=i-1}if(i=l,n[i]===s)return i/(r-1);const c=n[i];return(i+(s-c)/(n[i+1]-c))/(r-1)}getTangent(t,e){const n=1e-4;let i=t-n,r=t+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=e||(s.isVector2?new dt:new Lt);return o.copy(a).sub(s).normalize(),o}getTangentAt(t,e){const n=this.getUtoTmapping(t);return this.getTangent(n,e)}computeFrenetFrames(t,e){const n=new Lt,i=[],r=[],s=[],a=new Lt,o=new se;for(let e=0;e<=t;e++){const n=e/t;i[e]=this.getTangentAt(n,new Lt)}r[0]=new Lt,s[0]=new Lt;let l=Number.MAX_VALUE;const c=Math.abs(i[0].x),h=Math.abs(i[0].y),u=Math.abs(i[0].z);c<=l&&(l=c,n.set(1,0,0)),h<=l&&(l=h,n.set(0,1,0)),u<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),s[0].crossVectors(i[0],r[0]);for(let e=1;e<=t;e++){if(r[e]=r[e-1].clone(),s[e]=s[e-1].clone(),a.crossVectors(i[e-1],i[e]),a.length()>Number.EPSILON){a.normalize();const t=Math.acos(st(i[e-1].dot(i[e]),-1,1));r[e].applyMatrix4(o.makeRotationAxis(a,t))}s[e].crossVectors(i[e],r[e])}if(!0===e){let e=Math.acos(st(r[0].dot(r[t]),-1,1));e/=t,i[0].dot(a.crossVectors(r[0],r[t]))>0&&(e=-e);for(let n=1;n<=t;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],e*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.5,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class xo extends yo{constructor(t=0,e=0,n=1,i=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(t,e){const n=e||new dt,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)<Number.EPSILON;for(;r<0;)r+=i;for(;r>i;)r-=i;r<Number.EPSILON&&(r=s?0:i),!0!==this.aClockwise||s||(r===i?r=-i:r-=i);const a=this.aStartAngle+t*r;let o=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(0!==this.aRotation){const t=Math.cos(this.aRotation),e=Math.sin(this.aRotation),n=o-this.aX,i=l-this.aY;o=n*t-i*e+this.aX,l=n*e+i*t+this.aY}return n.set(o,l)}copy(t){return super.copy(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}toJSON(){const t=super.toJSON();return t.aX=this.aX,t.aY=this.aY,t.xRadius=this.xRadius,t.yRadius=this.yRadius,t.aStartAngle=this.aStartAngle,t.aEndAngle=this.aEndAngle,t.aClockwise=this.aClockwise,t.aRotation=this.aRotation,t}fromJSON(t){return super.fromJSON(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}}xo.prototype.isEllipseCurve=!0;class _o extends xo{constructor(t,e,n,i,r,s){super(t,e,n,n,i,r,s),this.type="ArcCurve"}}function bo(){let t=0,e=0,n=0,i=0;function r(r,s,a,o){t=r,e=a,n=-3*r+3*s-2*a-o,i=2*r-2*s+a+o}return{initCatmullRom:function(t,e,n,i,s){r(e,n,s*(n-t),s*(i-e))},initNonuniformCatmullRom:function(t,e,n,i,s,a,o){let l=(e-t)/s-(n-t)/(s+a)+(n-e)/a,c=(n-e)/a-(i-e)/(a+o)+(i-n)/o;l*=a,c*=a,r(e,n,l,c)},calc:function(r){const s=r*r;return t+e*r+n*s+i*(s*r)}}}_o.prototype.isArcCurve=!0;const Mo=new Lt,wo=new bo,So=new bo,To=new bo;class Eo extends yo{constructor(t=[],e=!1,n="centripetal",i=.5){super(),this.type="CatmullRomCurve3",this.points=t,this.closed=e,this.curveType=n,this.tension=i}getPoint(t,e=new Lt){const n=e,i=this.points,r=i.length,s=(r-(this.closed?0:1))*t;let a,o,l=Math.floor(s),c=s-l;this.closed?l+=l>0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===c&&l===r-1&&(l=r-2,c=1),this.closed||l>0?a=i[(l-1)%r]:(Mo.subVectors(i[0],i[1]).add(i[0]),a=Mo);const h=i[l%r],u=i[(l+1)%r];if(this.closed||l+2<r?o=i[(l+2)%r]:(Mo.subVectors(i[r-1],i[r-2]).add(i[r-1]),o=Mo),"centripetal"===this.curveType||"chordal"===this.curveType){const t="chordal"===this.curveType?.5:.25;let e=Math.pow(a.distanceToSquared(h),t),n=Math.pow(h.distanceToSquared(u),t),i=Math.pow(u.distanceToSquared(o),t);n<1e-4&&(n=1),e<1e-4&&(e=n),i<1e-4&&(i=n),wo.initNonuniformCatmullRom(a.x,h.x,u.x,o.x,e,n,i),So.initNonuniformCatmullRom(a.y,h.y,u.y,o.y,e,n,i),To.initNonuniformCatmullRom(a.z,h.z,u.z,o.z,e,n,i)}else"catmullrom"===this.curveType&&(wo.initCatmullRom(a.x,h.x,u.x,o.x,this.tension),So.initCatmullRom(a.y,h.y,u.y,o.y,this.tension),To.initCatmullRom(a.z,h.z,u.z,o.z,this.tension));return n.set(wo.calc(c),So.calc(c),To.calc(c)),n}copy(t){super.copy(t),this.points=[];for(let e=0,n=t.points.length;e<n;e++){const n=t.points[e];this.points.push(n.clone())}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,n=this.points.length;e<n;e++){const n=this.points[e];t.points.push(n.toArray())}return t.closed=this.closed,t.curveType=this.curveType,t.tension=this.tension,t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,n=t.points.length;e<n;e++){const n=t.points[e];this.points.push((new Lt).fromArray(n))}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}}function Ao(t,e,n,i,r){const s=.5*(i-e),a=.5*(r-n),o=t*t;return(2*n-2*i+s+a)*(t*o)+(-3*n+3*i-2*s-a)*o+s*t+n}function Lo(t,e,n,i){return function(t,e){const n=1-t;return n*n*e}(t,e)+function(t,e){return 2*(1-t)*t*e}(t,n)+function(t,e){return t*t*e}(t,i)}function Ro(t,e,n,i,r){return function(t,e){const n=1-t;return n*n*n*e}(t,e)+function(t,e){const n=1-t;return 3*n*n*t*e}(t,n)+function(t,e){return 3*(1-t)*t*t*e}(t,i)+function(t,e){return t*t*t*e}(t,r)}Eo.prototype.isCatmullRomCurve3=!0;class Co extends yo{constructor(t=new dt,e=new dt,n=new dt,i=new dt){super(),this.type="CubicBezierCurve",this.v0=t,this.v1=e,this.v2=n,this.v3=i}getPoint(t,e=new dt){const n=e,i=this.v0,r=this.v1,s=this.v2,a=this.v3;return n.set(Ro(t,i.x,r.x,s.x,a.x),Ro(t,i.y,r.y,s.y,a.y)),n}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}Co.prototype.isCubicBezierCurve=!0;class Po extends yo{constructor(t=new Lt,e=new Lt,n=new Lt,i=new Lt){super(),this.type="CubicBezierCurve3",this.v0=t,this.v1=e,this.v2=n,this.v3=i}getPoint(t,e=new Lt){const n=e,i=this.v0,r=this.v1,s=this.v2,a=this.v3;return n.set(Ro(t,i.x,r.x,s.x,a.x),Ro(t,i.y,r.y,s.y,a.y),Ro(t,i.z,r.z,s.z,a.z)),n}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}Po.prototype.isCubicBezierCurve3=!0;class Do extends yo{constructor(t=new dt,e=new dt){super(),this.type="LineCurve",this.v1=t,this.v2=e}getPoint(t,e=new dt){const n=e;return 1===t?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(t).add(this.v1)),n}getPointAt(t,e){return this.getPoint(t,e)}getTangent(t,e){const n=e||new dt;return n.copy(this.v2).sub(this.v1).normalize(),n}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}Do.prototype.isLineCurve=!0;class Io extends yo{constructor(t=new Lt,e=new Lt){super(),this.type="LineCurve3",this.isLineCurve3=!0,this.v1=t,this.v2=e}getPoint(t,e=new Lt){const n=e;return 1===t?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(t).add(this.v1)),n}getPointAt(t,e){return this.getPoint(t,e)}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class No extends yo{constructor(t=new dt,e=new dt,n=new dt){super(),this.type="QuadraticBezierCurve",this.v0=t,this.v1=e,this.v2=n}getPoint(t,e=new dt){const n=e,i=this.v0,r=this.v1,s=this.v2;return n.set(Lo(t,i.x,r.x,s.x),Lo(t,i.y,r.y,s.y)),n}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}No.prototype.isQuadraticBezierCurve=!0;class zo extends yo{constructor(t=new Lt,e=new Lt,n=new Lt){super(),this.type="QuadraticBezierCurve3",this.v0=t,this.v1=e,this.v2=n}getPoint(t,e=new Lt){const n=e,i=this.v0,r=this.v1,s=this.v2;return n.set(Lo(t,i.x,r.x,s.x),Lo(t,i.y,r.y,s.y),Lo(t,i.z,r.z,s.z)),n}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}zo.prototype.isQuadraticBezierCurve3=!0;class Bo extends yo{constructor(t=[]){super(),this.type="SplineCurve",this.points=t}getPoint(t,e=new dt){const n=e,i=this.points,r=(i.length-1)*t,s=Math.floor(r),a=r-s,o=i[0===s?s:s-1],l=i[s],c=i[s>i.length-2?i.length-1:s+1],h=i[s>i.length-3?i.length-1:s+2];return n.set(Ao(a,o.x,l.x,c.x,h.x),Ao(a,o.y,l.y,c.y,h.y)),n}copy(t){super.copy(t),this.points=[];for(let e=0,n=t.points.length;e<n;e++){const n=t.points[e];this.points.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,n=this.points.length;e<n;e++){const n=this.points[e];t.points.push(n.toArray())}return t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,n=t.points.length;e<n;e++){const n=t.points[e];this.points.push((new dt).fromArray(n))}return this}}Bo.prototype.isSplineCurve=!0;var Fo=Object.freeze({__proto__:null,ArcCurve:_o,CatmullRomCurve3:Eo,CubicBezierCurve:Co,CubicBezierCurve3:Po,EllipseCurve:xo,LineCurve:Do,LineCurve3:Io,QuadraticBezierCurve:No,QuadraticBezierCurve3:zo,SplineCurve:Bo});class Oo extends yo{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(t){this.curves.push(t)}closePath(){const t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);t.equals(e)||this.curves.push(new Do(e,t))}getPoint(t,e){const n=t*this.getLength(),i=this.getCurveLengths();let r=0;for(;r<i.length;){if(i[r]>=n){const t=i[r]-n,s=this.curves[r],a=s.getLength(),o=0===a?0:1-t/a;return s.getPointAt(o,e)}r++}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;n<i;n++)e+=this.curves[n].getLength(),t.push(e);return this.cacheLengths=t,t}getSpacedPoints(t=40){const e=[];for(let n=0;n<=t;n++)e.push(this.getPoint(n/t));return this.autoClose&&e.push(e[0]),e}getPoints(t=12){const e=[];let n;for(let i=0,r=this.curves;i<r.length;i++){const s=r[i],a=s&&s.isEllipseCurve?2*t:s&&(s.isLineCurve||s.isLineCurve3)?1:s&&s.isSplineCurve?t*s.points.length:t,o=s.getPoints(a);for(let t=0;t<o.length;t++){const i=o[t];n&&n.equals(i)||(e.push(i),n=i)}}return this.autoClose&&e.length>1&&!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;e<n;e++){const n=t.curves[e];this.curves.push(n.clone())}return this.autoClose=t.autoClose,this}toJSON(){const t=super.toJSON();t.autoClose=this.autoClose,t.curves=[];for(let e=0,n=this.curves.length;e<n;e++){const n=this.curves[e];t.curves.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.autoClose=t.autoClose,this.curves=[];for(let e=0,n=t.curves.length;e<n;e++){const n=t.curves[e];this.curves.push((new Fo[n.type]).fromJSON(n))}return this}}class Uo extends Oo{constructor(t){super(),this.type="Path",this.currentPoint=new dt,t&&this.setFromPoints(t)}setFromPoints(t){this.moveTo(t[0].x,t[0].y);for(let e=1,n=t.length;e<n;e++)this.lineTo(t[e].x,t[e].y);return this}moveTo(t,e){return this.currentPoint.set(t,e),this}lineTo(t,e){const n=new Do(this.currentPoint.clone(),new dt(t,e));return this.curves.push(n),this.currentPoint.set(t,e),this}quadraticCurveTo(t,e,n,i){const r=new No(this.currentPoint.clone(),new dt(t,e),new dt(n,i));return this.curves.push(r),this.currentPoint.set(n,i),this}bezierCurveTo(t,e,n,i,r,s){const a=new Co(this.currentPoint.clone(),new dt(t,e),new dt(n,i),new dt(r,s));return this.curves.push(a),this.currentPoint.set(r,s),this}splineThru(t){const e=[this.currentPoint.clone()].concat(t),n=new Bo(e);return this.curves.push(n),this.currentPoint.copy(t[t.length-1]),this}arc(t,e,n,i,r,s){const a=this.currentPoint.x,o=this.currentPoint.y;return this.absarc(t+a,e+o,n,i,r,s),this}absarc(t,e,n,i,r,s){return this.absellipse(t,e,n,n,i,r,s),this}ellipse(t,e,n,i,r,s,a,o){const l=this.currentPoint.x,c=this.currentPoint.y;return this.absellipse(t+l,e+c,n,i,r,s,a,o),this}absellipse(t,e,n,i,r,s,a,o){const l=new xo(t,e,n,i,r,s,a,o);if(this.curves.length>0){const t=l.getPoint(0);t.equals(this.currentPoint)||this.lineTo(t.x,t.y)}this.curves.push(l);const c=l.getPoint(1);return this.currentPoint.copy(c),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 Ho extends Uo{constructor(t){super(t),this.uuid=rt(),this.type="Shape",this.holes=[]}getPointsHoles(t){const e=[];for(let n=0,i=this.holes.length;n<i;n++)e[n]=this.holes[n].getPoints(t);return e}extractPoints(t){return{shape:this.getPoints(t),holes:this.getPointsHoles(t)}}copy(t){super.copy(t),this.holes=[];for(let e=0,n=t.holes.length;e<n;e++){const n=t.holes[e];this.holes.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.uuid=this.uuid,t.holes=[];for(let e=0,n=this.holes.length;e<n;e++){const n=this.holes[e];t.holes.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.uuid=t.uuid,this.holes=[];for(let e=0,n=t.holes.length;e<n;e++){const n=t.holes[e];this.holes.push((new Uo).fromJSON(n))}return this}}const Go=function(t,e,n=2){const i=e&&e.length,r=i?e[0]*n:t.length;let s=ko(t,0,r,n,!0);const a=[];if(!s||s.next===s.prev)return a;let o,l,c,h,u,d,p;if(i&&(s=function(t,e,n,i){const r=[];let s,a,o,l,c;for(s=0,a=e.length;s<a;s++)o=e[s]*i,l=s<a-1?e[s+1]*i:t.length,c=ko(t,o,l,i,!1),c===c.next&&(c.steiner=!0),r.push($o(c));for(r.sort(Yo),s=0;s<r.length;s++)Zo(r[s],n),n=Vo(n,n.next);return n}(t,e,s,n)),t.length>80*n){o=c=t[0],l=h=t[1];for(let e=n;e<r;e+=n)u=t[e],d=t[e+1],u<o&&(o=u),d<l&&(l=d),u>c&&(c=u),d>h&&(h=d);p=Math.max(c-o,h-l),p=0!==p?1/p:0}return Wo(s,a,n,o,l,p),a};function ko(t,e,n,i,r){let s,a;if(r===function(t,e,n,i){let r=0;for(let s=e,a=n-i;s<n;s+=i)r+=(t[a]-t[s])*(t[s+1]+t[a+1]),a=s;return r}(t,e,n,i)>0)for(s=e;s<n;s+=i)a=cl(s,t[s],t[s+1],a);else for(s=n-i;s>=e;s-=i)a=cl(s,t[s],t[s+1],a);return a&&il(a,a.next)&&(hl(a),a=a.next),a}function Vo(t,e){if(!t)return t;e||(e=t);let n,i=t;do{if(n=!1,i.steiner||!il(i,i.next)&&0!==nl(i.prev,i,i.next))i=i.next;else{if(hl(i),i=e=i.prev,i===i.next)break;n=!0}}while(n||i!==e);return e}function Wo(t,e,n,i,r,s,a){if(!t)return;!a&&s&&function(t,e,n,i){let r=t;do{null===r.z&&(r.z=Ko(r.x,r.y,e,n,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){let e,n,i,r,s,a,o,l,c=1;do{for(n=t,t=null,s=null,a=0;n;){for(a++,i=n,o=0,e=0;e<c&&(o++,i=i.nextZ,i);e++);for(l=c;o>0||l>0&&i;)0!==o&&(0===l||!i||n.z<=i.z)?(r=n,n=n.nextZ,o--):(r=i,i=i.nextZ,l--),s?s.nextZ=r:t=r,r.prevZ=s,s=r;n=i}s.nextZ=null,c*=2}while(a>1)}(r)}(t,i,r,s);let o,l,c=t;for(;t.prev!==t.next;)if(o=t.prev,l=t.next,s?qo(t,i,r,s):jo(t))e.push(o.i/n),e.push(t.i/n),e.push(l.i/n),hl(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?Wo(t=Xo(Vo(t),e,n),e,n,i,r,s,2):2===a&&Jo(t,e,n,i,r,s):Wo(Vo(t),e,n,i,r,s,1);break}}function jo(t){const e=t.prev,n=t,i=t.next;if(nl(e,n,i)>=0)return!1;let r=t.next.next;for(;r!==t.prev;){if(tl(e.x,e.y,n.x,n.y,i.x,i.y,r.x,r.y)&&nl(r.prev,r,r.next)>=0)return!1;r=r.next}return!0}function qo(t,e,n,i){const r=t.prev,s=t,a=t.next;if(nl(r,s,a)>=0)return!1;const o=r.x<s.x?r.x<a.x?r.x:a.x:s.x<a.x?s.x:a.x,l=r.y<s.y?r.y<a.y?r.y:a.y:s.y<a.y?s.y:a.y,c=r.x>s.x?r.x>a.x?r.x:a.x:s.x>a.x?s.x:a.x,h=r.y>s.y?r.y>a.y?r.y:a.y:s.y>a.y?s.y:a.y,u=Ko(o,l,e,n,i),d=Ko(c,h,e,n,i);let p=t.prevZ,m=t.nextZ;for(;p&&p.z>=u&&m&&m.z<=d;){if(p!==t.prev&&p!==t.next&&tl(r.x,r.y,s.x,s.y,a.x,a.y,p.x,p.y)&&nl(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,m!==t.prev&&m!==t.next&&tl(r.x,r.y,s.x,s.y,a.x,a.y,m.x,m.y)&&nl(m.prev,m,m.next)>=0)return!1;m=m.nextZ}for(;p&&p.z>=u;){if(p!==t.prev&&p!==t.next&&tl(r.x,r.y,s.x,s.y,a.x,a.y,p.x,p.y)&&nl(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;m&&m.z<=d;){if(m!==t.prev&&m!==t.next&&tl(r.x,r.y,s.x,s.y,a.x,a.y,m.x,m.y)&&nl(m.prev,m,m.next)>=0)return!1;m=m.nextZ}return!0}function Xo(t,e,n){let i=t;do{const r=i.prev,s=i.next.next;!il(r,s)&&rl(r,i,i.next,s)&&ol(r,s)&&ol(s,r)&&(e.push(r.i/n),e.push(i.i/n),e.push(s.i/n),hl(i),hl(i.next),i=t=s),i=i.next}while(i!==t);return Vo(i)}function Jo(t,e,n,i,r,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&el(a,t)){let o=ll(a,t);return a=Vo(a,a.next),o=Vo(o,o.next),Wo(a,e,n,i,r,s),void Wo(o,e,n,i,r,s)}t=t.next}a=a.next}while(a!==t)}function Yo(t,e){return t.x-e.x}function Zo(t,e){if(e=function(t,e){let n=e;const i=t.x,r=t.y;let s,a=-1/0;do{if(r<=n.y&&r>=n.next.y&&n.next.y!==n.y){const t=n.x+(r-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(t<=i&&t>a){if(a=t,t===i){if(r===n.y)return n;if(r===n.next.y)return n.next}s=n.x<n.next.x?n:n.next}}n=n.next}while(n!==e);if(!s)return null;if(i===a)return s;const o=s,l=s.x,c=s.y;let h,u=1/0;n=s;do{i>=n.x&&n.x>=l&&i!==n.x&&tl(r<c?i:a,r,l,c,r<c?a:i,r,n.x,n.y)&&(h=Math.abs(r-n.y)/(i-n.x),ol(n,t)&&(h<u||h===u&&(n.x>s.x||n.x===s.x&&Qo(s,n)))&&(s=n,u=h)),n=n.next}while(n!==o);return s}(t,e),e){const n=ll(e,t);Vo(e,e.next),Vo(n,n.next)}}function Qo(t,e){return nl(t.prev,t,e.prev)<0&&nl(e.next,t,t.next)<0}function Ko(t,e,n,i,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-n)*r)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*r)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function $o(t){let e=t,n=t;do{(e.x<n.x||e.x===n.x&&e.y<n.y)&&(n=e),e=e.next}while(e!==t);return n}function tl(t,e,n,i,r,s,a,o){return(r-a)*(e-o)-(t-a)*(s-o)>=0&&(t-a)*(i-o)-(n-a)*(e-o)>=0&&(n-a)*(s-o)-(r-a)*(i-o)>=0}function el(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&rl(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(ol(t,e)&&ol(e,t)&&function(t,e){let n=t,i=!1;const r=(t.x+e.x)/2,s=(t.y+e.y)/2;do{n.y>s!=n.next.y>s&&n.next.y!==n.y&&r<(n.next.x-n.x)*(s-n.y)/(n.next.y-n.y)+n.x&&(i=!i),n=n.next}while(n!==t);return i}(t,e)&&(nl(t.prev,t,e.prev)||nl(t,e.prev,e))||il(t,e)&&nl(t.prev,t,t.next)>0&&nl(e.prev,e,e.next)>0)}function nl(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function il(t,e){return t.x===e.x&&t.y===e.y}function rl(t,e,n,i){const r=al(nl(t,e,n)),s=al(nl(t,e,i)),a=al(nl(n,i,t)),o=al(nl(n,i,e));return r!==s&&a!==o||(!(0!==r||!sl(t,n,e))||(!(0!==s||!sl(t,i,e))||(!(0!==a||!sl(n,t,i))||!(0!==o||!sl(n,e,i)))))}function sl(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function al(t){return t>0?1:t<0?-1:0}function ol(t,e){return nl(t.prev,t,t.next)<0?nl(t,e,t.next)>=0&&nl(t,t.prev,e)>=0:nl(t,e,t.prev)<0||nl(t,t.next,e)<0}function ll(t,e){const n=new ul(t.i,t.x,t.y),i=new ul(e.i,e.x,e.y),r=t.next,s=e.prev;return t.next=e,e.prev=t,n.next=r,r.prev=n,i.next=n,n.prev=i,s.next=i,i.prev=s,i}function cl(t,e,n,i){const r=new ul(t,e,n);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function hl(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function ul(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}class dl{static area(t){const e=t.length;let n=0;for(let i=e-1,r=0;r<e;i=r++)n+=t[i].x*t[r].y-t[r].x*t[i].y;return.5*n}static isClockWise(t){return dl.area(t)<0}static triangulateShape(t,e){const n=[],i=[],r=[];pl(t),ml(n,t);let s=t.length;e.forEach(pl);for(let t=0;t<e.length;t++)i.push(s),s+=e[t].length,ml(n,e[t]);const a=Go(n,i);for(let t=0;t<a.length;t+=3)r.push(a.slice(t,t+3));return r}}function pl(t){const e=t.length;e>2&&t[e-1].equals(t[0])&&t.pop()}function ml(t,e){for(let n=0;n<e.length;n++)t.push(e[n].x),t.push(e[n].y)}class fl extends xn{constructor(t=new Ho([new dt(.5,.5),new dt(-.5,.5),new dt(-.5,-.5),new dt(.5,-.5)]),e={}){super(),this.type="ExtrudeGeometry",this.parameters={shapes:t,options:e},t=Array.isArray(t)?t:[t];const n=this,i=[],r=[];for(let e=0,n=t.length;e<n;e++){s(t[e])}function s(t){const s=[],a=void 0!==e.curveSegments?e.curveSegments:12,o=void 0!==e.steps?e.steps:1;let l=void 0!==e.depth?e.depth:1,c=void 0===e.bevelEnabled||e.bevelEnabled,h=void 0!==e.bevelThickness?e.bevelThickness:.2,u=void 0!==e.bevelSize?e.bevelSize:h-.1,d=void 0!==e.bevelOffset?e.bevelOffset:0,p=void 0!==e.bevelSegments?e.bevelSegments:3;const m=e.extrudePath,f=void 0!==e.UVGenerator?e.UVGenerator:gl;void 0!==e.amount&&(console.warn("THREE.ExtrudeBufferGeometry: amount has been renamed to depth."),l=e.amount);let g,v,y,x,_,b=!1;m&&(g=m.getSpacedPoints(o),b=!0,c=!1,v=m.computeFrenetFrames(o,!1),y=new Lt,x=new Lt,_=new Lt),c||(p=0,h=0,u=0,d=0);const M=t.extractPoints(a);let w=M.shape;const S=M.holes;if(!dl.isClockWise(w)){w=w.reverse();for(let t=0,e=S.length;t<e;t++){const e=S[t];dl.isClockWise(e)&&(S[t]=e.reverse())}}const T=dl.triangulateShape(w,S),E=w;for(let t=0,e=S.length;t<e;t++){const e=S[t];w=w.concat(e)}function A(t,e,n){return e||console.error("THREE.ExtrudeGeometry: vec does not exist"),e.clone().multiplyScalar(n).add(t)}const L=w.length,R=T.length;function C(t,e,n){let i,r,s;const a=t.x-e.x,o=t.y-e.y,l=n.x-t.x,c=n.y-t.y,h=a*a+o*o,u=a*c-o*l;if(Math.abs(u)>Number.EPSILON){const u=Math.sqrt(h),d=Math.sqrt(l*l+c*c),p=e.x-o/u,m=e.y+a/u,f=((n.x-c/d-p)*c-(n.y+l/d-m)*l)/(a*c-o*l);i=p+a*f-t.x,r=m+o*f-t.y;const g=i*i+r*r;if(g<=2)return new dt(i,r);s=Math.sqrt(g/2)}else{let t=!1;a>Number.EPSILON?l>Number.EPSILON&&(t=!0):a<-Number.EPSILON?l<-Number.EPSILON&&(t=!0):Math.sign(o)===Math.sign(c)&&(t=!0),t?(i=-o,r=a,s=Math.sqrt(h)):(i=a,r=o,s=Math.sqrt(h/2))}return new dt(i/s,r/s)}const P=[];for(let t=0,e=E.length,n=e-1,i=t+1;t<e;t++,n++,i++)n===e&&(n=0),i===e&&(i=0),P[t]=C(E[t],E[n],E[i]);const D=[];let I,N=P.concat();for(let t=0,e=S.length;t<e;t++){const e=S[t];I=[];for(let t=0,n=e.length,i=n-1,r=t+1;t<n;t++,i++,r++)i===n&&(i=0),r===n&&(r=0),I[t]=C(e[t],e[i],e[r]);D.push(I),N=N.concat(I)}for(let t=0;t<p;t++){const e=t/p,n=h*Math.cos(e*Math.PI/2),i=u*Math.sin(e*Math.PI/2)+d;for(let t=0,e=E.length;t<e;t++){const e=A(E[t],P[t],i);F(e.x,e.y,-n)}for(let t=0,e=S.length;t<e;t++){const e=S[t];I=D[t];for(let t=0,r=e.length;t<r;t++){const r=A(e[t],I[t],i);F(r.x,r.y,-n)}}}const z=u+d;for(let t=0;t<L;t++){const e=c?A(w[t],N[t],z):w[t];b?(x.copy(v.normals[0]).multiplyScalar(e.x),y.copy(v.binormals[0]).multiplyScalar(e.y),_.copy(g[0]).add(x).add(y),F(_.x,_.y,_.z)):F(e.x,e.y,0)}for(let t=1;t<=o;t++)for(let e=0;e<L;e++){const n=c?A(w[e],N[e],z):w[e];b?(x.copy(v.normals[t]).multiplyScalar(n.x),y.copy(v.binormals[t]).multiplyScalar(n.y),_.copy(g[t]).add(x).add(y),F(_.x,_.y,_.z)):F(n.x,n.y,l/o*t)}for(let t=p-1;t>=0;t--){const e=t/p,n=h*Math.cos(e*Math.PI/2),i=u*Math.sin(e*Math.PI/2)+d;for(let t=0,e=E.length;t<e;t++){const e=A(E[t],P[t],i);F(e.x,e.y,l+n)}for(let t=0,e=S.length;t<e;t++){const e=S[t];I=D[t];for(let t=0,r=e.length;t<r;t++){const r=A(e[t],I[t],i);b?F(r.x,r.y+g[o-1].y,g[o-1].x+n):F(r.x,r.y,l+n)}}}function B(t,e){let n=t.length;for(;--n>=0;){const i=n;let r=n-1;r<0&&(r=t.length-1);for(let t=0,n=o+2*p;t<n;t++){const n=L*t,s=L*(t+1);U(e+i+n,e+r+n,e+r+s,e+i+s)}}}function F(t,e,n){s.push(t),s.push(e),s.push(n)}function O(t,e,r){H(t),H(e),H(r);const s=i.length/3,a=f.generateTopUV(n,i,s-3,s-2,s-1);G(a[0]),G(a[1]),G(a[2])}function U(t,e,r,s){H(t),H(e),H(s),H(e),H(r),H(s);const a=i.length/3,o=f.generateSideWallUV(n,i,a-6,a-3,a-2,a-1);G(o[0]),G(o[1]),G(o[3]),G(o[1]),G(o[2]),G(o[3])}function H(t){i.push(s[3*t+0]),i.push(s[3*t+1]),i.push(s[3*t+2])}function G(t){r.push(t.x),r.push(t.y)}!function(){const t=i.length/3;if(c){let t=0,e=L*t;for(let t=0;t<R;t++){const n=T[t];O(n[2]+e,n[1]+e,n[0]+e)}t=o+2*p,e=L*t;for(let t=0;t<R;t++){const n=T[t];O(n[0]+e,n[1]+e,n[2]+e)}}else{for(let t=0;t<R;t++){const e=T[t];O(e[2],e[1],e[0])}for(let t=0;t<R;t++){const e=T[t];O(e[0]+L*o,e[1]+L*o,e[2]+L*o)}}n.addGroup(t,i.length/3-t,0)}(),function(){const t=i.length/3;let e=0;B(E,e),e+=E.length;for(let t=0,n=S.length;t<n;t++){const n=S[t];B(n,e),e+=n.length}n.addGroup(t,i.length/3-t,1)}()}this.setAttribute("position",new hn(i,3)),this.setAttribute("uv",new hn(r,2)),this.computeVertexNormals()}toJSON(){const t=super.toJSON();return function(t,e,n){if(n.shapes=[],Array.isArray(t))for(let e=0,i=t.length;e<i;e++){const i=t[e];n.shapes.push(i.uuid)}else n.shapes.push(t.uuid);void 0!==e.extrudePath&&(n.options.extrudePath=e.extrudePath.toJSON());return n}(this.parameters.shapes,this.parameters.options,t)}static fromJSON(t,e){const n=[];for(let i=0,r=t.shapes.length;i<r;i++){const r=e[t.shapes[i]];n.push(r)}const i=t.options.extrudePath;return void 0!==i&&(t.options.extrudePath=(new Fo[i.type]).fromJSON(i)),new fl(n,t.options)}}const gl={generateTopUV:function(t,e,n,i,r){const s=e[3*n],a=e[3*n+1],o=e[3*i],l=e[3*i+1],c=e[3*r],h=e[3*r+1];return[new dt(s,a),new dt(o,l),new dt(c,h)]},generateSideWallUV:function(t,e,n,i,r,s){const a=e[3*n],o=e[3*n+1],l=e[3*n+2],c=e[3*i],h=e[3*i+1],u=e[3*i+2],d=e[3*r],p=e[3*r+1],m=e[3*r+2],f=e[3*s],g=e[3*s+1],v=e[3*s+2];return Math.abs(o-h)<Math.abs(a-c)?[new dt(a,1-l),new dt(c,1-u),new dt(d,1-m),new dt(f,1-v)]:[new dt(o,1-l),new dt(h,1-u),new dt(p,1-m),new dt(g,1-v)]}};class vl extends ho{constructor(t=1,e=0){const n=(1+Math.sqrt(5))/2;super([-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],t,e),this.type="IcosahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new vl(t.radius,t.detail)}}class yl extends xn{constructor(t=[new dt(0,.5),new dt(.5,0),new dt(0,-.5)],e=12,n=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:t,segments:e,phiStart:n,phiLength:i},e=Math.floor(e),i=st(i,0,2*Math.PI);const r=[],s=[],a=[],o=[],l=[],c=1/e,h=new Lt,u=new dt,d=new Lt,p=new Lt,m=new Lt;let f=0,g=0;for(let e=0;e<=t.length-1;e++)switch(e){case 0:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,m.copy(d),d.normalize(),o.push(d.x,d.y,d.z);break;case t.length-1:o.push(m.x,m.y,m.z);break;default:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),o.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=e;r++){const d=n+r*c*i,p=Math.sin(d),m=Math.cos(d);for(let n=0;n<=t.length-1;n++){h.x=t[n].x*p,h.y=t[n].y,h.z=t[n].x*m,s.push(h.x,h.y,h.z),u.x=r/e,u.y=n/(t.length-1),a.push(u.x,u.y);const i=o[3*n+0]*p,c=o[3*n+1],d=o[3*n+0]*m;l.push(i,c,d)}}for(let n=0;n<e;n++)for(let e=0;e<t.length-1;e++){const i=e+n*t.length,s=i,a=i+t.length,o=i+t.length+1,l=i+1;r.push(s,a,l),r.push(a,o,l)}this.setIndex(r),this.setAttribute("position",new hn(s,3)),this.setAttribute("uv",new hn(a,2)),this.setAttribute("normal",new hn(l,3))}static fromJSON(t){return new yl(t.points,t.segments,t.phiStart,t.phiLength)}}class xl extends ho{constructor(t=1,e=0){super([1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],t,e),this.type="OctahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new xl(t.radius,t.detail)}}class _l extends xn{constructor(t=.5,e=1,n=8,i=1,r=0,s=2*Math.PI){super(),this.type="RingGeometry",this.parameters={innerRadius:t,outerRadius:e,thetaSegments:n,phiSegments:i,thetaStart:r,thetaLength:s},n=Math.max(3,n);const a=[],o=[],l=[],c=[];let h=t;const u=(e-t)/(i=Math.max(1,i)),d=new Lt,p=new dt;for(let t=0;t<=i;t++){for(let t=0;t<=n;t++){const i=r+t/n*s;d.x=h*Math.cos(i),d.y=h*Math.sin(i),o.push(d.x,d.y,d.z),l.push(0,0,1),p.x=(d.x/e+1)/2,p.y=(d.y/e+1)/2,c.push(p.x,p.y)}h+=u}for(let t=0;t<i;t++){const e=t*(n+1);for(let t=0;t<n;t++){const i=t+e,r=i,s=i+n+1,o=i+n+2,l=i+1;a.push(r,s,l),a.push(s,o,l)}}this.setIndex(a),this.setAttribute("position",new hn(o,3)),this.setAttribute("normal",new hn(l,3)),this.setAttribute("uv",new hn(c,2))}static fromJSON(t){return new _l(t.innerRadius,t.outerRadius,t.thetaSegments,t.phiSegments,t.thetaStart,t.thetaLength)}}class bl extends xn{constructor(t=new Ho([new dt(0,.5),new dt(-.5,-.5),new dt(.5,-.5)]),e=12){super(),this.type="ShapeGeometry",this.parameters={shapes:t,curveSegments:e};const n=[],i=[],r=[],s=[];let a=0,o=0;if(!1===Array.isArray(t))l(t);else for(let e=0;e<t.length;e++)l(t[e]),this.addGroup(a,o,e),a+=o,o=0;function l(t){const a=i.length/3,l=t.extractPoints(e);let c=l.shape;const h=l.holes;!1===dl.isClockWise(c)&&(c=c.reverse());for(let t=0,e=h.length;t<e;t++){const e=h[t];!0===dl.isClockWise(e)&&(h[t]=e.reverse())}const u=dl.triangulateShape(c,h);for(let t=0,e=h.length;t<e;t++){const e=h[t];c=c.concat(e)}for(let t=0,e=c.length;t<e;t++){const e=c[t];i.push(e.x,e.y,0),r.push(0,0,1),s.push(e.x,e.y)}for(let t=0,e=u.length;t<e;t++){const e=u[t],i=e[0]+a,r=e[1]+a,s=e[2]+a;n.push(i,r,s),o+=3}}this.setIndex(n),this.setAttribute("position",new hn(i,3)),this.setAttribute("normal",new hn(r,3)),this.setAttribute("uv",new hn(s,2))}toJSON(){const t=super.toJSON();return function(t,e){if(e.shapes=[],Array.isArray(t))for(let n=0,i=t.length;n<i;n++){const i=t[n];e.shapes.push(i.uuid)}else e.shapes.push(t.uuid);return e}(this.parameters.shapes,t)}static fromJSON(t,e){const n=[];for(let i=0,r=t.shapes.length;i<r;i++){const r=e[t.shapes[i]];n.push(r)}return new bl(n,t.curveSegments)}}class Ml extends xn{constructor(t=1,e=32,n=16,i=0,r=2*Math.PI,s=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:n,phiStart:i,phiLength:r,thetaStart:s,thetaLength:a},e=Math.max(3,Math.floor(e)),n=Math.max(2,Math.floor(n));const o=Math.min(s+a,Math.PI);let l=0;const c=[],h=new Lt,u=new Lt,d=[],p=[],m=[],f=[];for(let d=0;d<=n;d++){const g=[],v=d/n;let y=0;0==d&&0==s?y=.5/e:d==n&&o==Math.PI&&(y=-.5/e);for(let n=0;n<=e;n++){const o=n/e;h.x=-t*Math.cos(i+o*r)*Math.sin(s+v*a),h.y=t*Math.cos(s+v*a),h.z=t*Math.sin(i+o*r)*Math.sin(s+v*a),p.push(h.x,h.y,h.z),u.copy(h).normalize(),m.push(u.x,u.y,u.z),f.push(o+y,1-v),g.push(l++)}c.push(g)}for(let t=0;t<n;t++)for(let i=0;i<e;i++){const e=c[t][i+1],r=c[t][i],a=c[t+1][i],l=c[t+1][i+1];(0!==t||s>0)&&d.push(e,r,l),(t!==n-1||o<Math.PI)&&d.push(r,a,l)}this.setIndex(d),this.setAttribute("position",new hn(p,3)),this.setAttribute("normal",new hn(m,3)),this.setAttribute("uv",new hn(f,2))}static fromJSON(t){return new Ml(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}}class wl extends ho{constructor(t=1,e=0){super([1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],t,e),this.type="TetrahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new wl(t.radius,t.detail)}}class Sl extends xn{constructor(t=1,e=.4,n=8,i=6,r=2*Math.PI){super(),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:n,tubularSegments:i,arc:r},n=Math.floor(n),i=Math.floor(i);const s=[],a=[],o=[],l=[],c=new Lt,h=new Lt,u=new Lt;for(let s=0;s<=n;s++)for(let d=0;d<=i;d++){const p=d/i*r,m=s/n*Math.PI*2;h.x=(t+e*Math.cos(m))*Math.cos(p),h.y=(t+e*Math.cos(m))*Math.sin(p),h.z=e*Math.sin(m),a.push(h.x,h.y,h.z),c.x=t*Math.cos(p),c.y=t*Math.sin(p),u.subVectors(h,c).normalize(),o.push(u.x,u.y,u.z),l.push(d/i),l.push(s/n)}for(let t=1;t<=n;t++)for(let e=1;e<=i;e++){const n=(i+1)*t+e-1,r=(i+1)*(t-1)+e-1,a=(i+1)*(t-1)+e,o=(i+1)*t+e;s.push(n,r,o),s.push(r,a,o)}this.setIndex(s),this.setAttribute("position",new hn(a,3)),this.setAttribute("normal",new hn(o,3)),this.setAttribute("uv",new hn(l,2))}static fromJSON(t){return new Sl(t.radius,t.tube,t.radialSegments,t.tubularSegments,t.arc)}}class Tl extends xn{constructor(t=1,e=.4,n=64,i=8,r=2,s=3){super(),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:e,tubularSegments:n,radialSegments:i,p:r,q:s},n=Math.floor(n),i=Math.floor(i);const a=[],o=[],l=[],c=[],h=new Lt,u=new Lt,d=new Lt,p=new Lt,m=new Lt,f=new Lt,g=new Lt;for(let a=0;a<=n;++a){const y=a/n*r*Math.PI*2;v(y,r,s,t,d),v(y+.01,r,s,t,p),f.subVectors(p,d),g.addVectors(p,d),m.crossVectors(f,g),g.crossVectors(m,f),m.normalize(),g.normalize();for(let t=0;t<=i;++t){const r=t/i*Math.PI*2,s=-e*Math.cos(r),p=e*Math.sin(r);h.x=d.x+(s*g.x+p*m.x),h.y=d.y+(s*g.y+p*m.y),h.z=d.z+(s*g.z+p*m.z),o.push(h.x,h.y,h.z),u.subVectors(h,d).normalize(),l.push(u.x,u.y,u.z),c.push(a/n),c.push(t/i)}}for(let t=1;t<=n;t++)for(let e=1;e<=i;e++){const n=(i+1)*(t-1)+(e-1),r=(i+1)*t+(e-1),s=(i+1)*t+e,o=(i+1)*(t-1)+e;a.push(n,r,o),a.push(r,s,o)}function v(t,e,n,i,r){const s=Math.cos(t),a=Math.sin(t),o=n/e*t,l=Math.cos(o);r.x=i*(2+l)*.5*s,r.y=i*(2+l)*a*.5,r.z=i*Math.sin(o)*.5}this.setIndex(a),this.setAttribute("position",new hn(o,3)),this.setAttribute("normal",new hn(l,3)),this.setAttribute("uv",new hn(c,2))}static fromJSON(t){return new Tl(t.radius,t.tube,t.tubularSegments,t.radialSegments,t.p,t.q)}}class El extends xn{constructor(t=new zo(new Lt(-1,-1,0),new Lt(-1,1,0),new Lt(1,1,0)),e=64,n=1,i=8,r=!1){super(),this.type="TubeGeometry",this.parameters={path:t,tubularSegments:e,radius:n,radialSegments:i,closed:r};const s=t.computeFrenetFrames(e,r);this.tangents=s.tangents,this.normals=s.normals,this.binormals=s.binormals;const a=new Lt,o=new Lt,l=new dt;let c=new Lt;const h=[],u=[],d=[],p=[];function m(r){c=t.getPointAt(r/e,c);const l=s.normals[r],d=s.binormals[r];for(let t=0;t<=i;t++){const e=t/i*Math.PI*2,r=Math.sin(e),s=-Math.cos(e);o.x=s*l.x+r*d.x,o.y=s*l.y+r*d.y,o.z=s*l.z+r*d.z,o.normalize(),u.push(o.x,o.y,o.z),a.x=c.x+n*o.x,a.y=c.y+n*o.y,a.z=c.z+n*o.z,h.push(a.x,a.y,a.z)}}!function(){for(let t=0;t<e;t++)m(t);m(!1===r?e:0),function(){for(let t=0;t<=e;t++)for(let n=0;n<=i;n++)l.x=t/e,l.y=n/i,d.push(l.x,l.y)}(),function(){for(let t=1;t<=e;t++)for(let e=1;e<=i;e++){const n=(i+1)*(t-1)+(e-1),r=(i+1)*t+(e-1),s=(i+1)*t+e,a=(i+1)*(t-1)+e;p.push(n,r,a),p.push(r,s,a)}}()}(),this.setIndex(p),this.setAttribute("position",new hn(h,3)),this.setAttribute("normal",new hn(u,3)),this.setAttribute("uv",new hn(d,2))}toJSON(){const t=super.toJSON();return t.path=this.parameters.path.toJSON(),t}static fromJSON(t){return new El((new Fo[t.path.type]).fromJSON(t.path),t.tubularSegments,t.radius,t.radialSegments,t.closed)}}class Al extends xn{constructor(t=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:t},null!==t){const e=[],n=new Set,i=new Lt,r=new Lt;if(null!==t.index){const s=t.attributes.position,a=t.index;let o=t.groups;0===o.length&&(o=[{start:0,count:a.count,materialIndex:0}]);for(let t=0,l=o.length;t<l;++t){const l=o[t],c=l.start;for(let t=c,o=c+l.count;t<o;t+=3)for(let o=0;o<3;o++){const l=a.getX(t+o),c=a.getX(t+(o+1)%3);i.fromBufferAttribute(s,l),r.fromBufferAttribute(s,c),!0===Ll(i,r,n)&&(e.push(i.x,i.y,i.z),e.push(r.x,r.y,r.z))}}}else{const s=t.attributes.position;for(let t=0,a=s.count/3;t<a;t++)for(let a=0;a<3;a++){const o=3*t+a,l=3*t+(a+1)%3;i.fromBufferAttribute(s,o),r.fromBufferAttribute(s,l),!0===Ll(i,r,n)&&(e.push(i.x,i.y,i.z),e.push(r.x,r.y,r.z))}}this.setAttribute("position",new hn(e,3))}}}function Ll(t,e,n){const i=`${t.x},${t.y},${t.z}-${e.x},${e.y},${e.z}`,r=`${e.x},${e.y},${e.z}-${t.x},${t.y},${t.z}`;return!0!==n.has(i)&&!0!==n.has(r)&&(n.add(i,r),!0)}var Rl=Object.freeze({__proto__:null,BoxGeometry:Un,BoxBufferGeometry:Un,CircleGeometry:oo,CircleBufferGeometry:oo,ConeGeometry:co,ConeBufferGeometry:co,CylinderGeometry:lo,CylinderBufferGeometry:lo,DodecahedronGeometry:uo,DodecahedronBufferGeometry:uo,EdgesGeometry:vo,ExtrudeGeometry:fl,ExtrudeBufferGeometry:fl,IcosahedronGeometry:vl,IcosahedronBufferGeometry:vl,LatheGeometry:yl,LatheBufferGeometry:yl,OctahedronGeometry:xl,OctahedronBufferGeometry:xl,PlaneGeometry:si,PlaneBufferGeometry:si,PolyhedronGeometry:ho,PolyhedronBufferGeometry:ho,RingGeometry:_l,RingBufferGeometry:_l,ShapeGeometry:bl,ShapeBufferGeometry:bl,SphereGeometry:Ml,SphereBufferGeometry:Ml,TetrahedronGeometry:wl,TetrahedronBufferGeometry:wl,TorusGeometry:Sl,TorusBufferGeometry:Sl,TorusKnotGeometry:Tl,TorusKnotBufferGeometry:Tl,TubeGeometry:El,TubeBufferGeometry:El,WireframeGeometry:Al});class Cl extends Ve{constructor(t){super(),this.type="ShadowMaterial",this.color=new Ze(0),this.transparent=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this}}Cl.prototype.isShadowMaterial=!0;class Pl extends Ve{constructor(t){super(),this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new Ze(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 Ze(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new dt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,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.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}}Pl.prototype.isMeshStandardMaterial=!0;class Dl extends Pl{constructor(t){super(),this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new dt(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return st(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.sheenColor=new Ze(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=0,this.attenuationColor=new Ze(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Ze(1,1,1),this.specularColorMap=null,this._sheen=0,this._clearcoat=0,this._transmission=0,this.setValues(t)}get sheen(){return this._sheen}set sheen(t){this._sheen>0!=t>0&&this.version++,this._sheen=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=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.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.ior=t.ior,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}}Dl.prototype.isMeshPhysicalMaterial=!0;class Il extends Ve{constructor(t){super(),this.type="MeshPhongMaterial",this.color=new Ze(16777215),this.specular=new Ze(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ze(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new dt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,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.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.flatShading=t.flatShading,this}}Il.prototype.isMeshPhongMaterial=!0;class Nl extends Ve{constructor(t){super(),this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Ze(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ze(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new dt(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.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}}Nl.prototype.isMeshToonMaterial=!0;class zl extends Ve{constructor(t){super(),this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new dt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!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}}zl.prototype.isMeshNormalMaterial=!0;class Bl extends Ve{constructor(t){super(),this.type="MeshLambertMaterial",this.color=new Ze(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ze(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",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.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,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}}Bl.prototype.isMeshLambertMaterial=!0;class Fl extends Ve{constructor(t){super(),this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Ze(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new dt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,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.flatShading=t.flatShading,this}}Fl.prototype.isMeshMatcapMaterial=!0;class Ol extends Ua{constructor(t){super(),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}}Ol.prototype.isLineDashedMaterial=!0;var Ul=Object.freeze({__proto__:null,ShadowMaterial:Cl,SpriteMaterial:ia,RawShaderMaterial:gi,ShaderMaterial:Vn,PointsMaterial:Za,MeshPhysicalMaterial:Dl,MeshStandardMaterial:Pl,MeshPhongMaterial:Il,MeshToonMaterial:Nl,MeshNormalMaterial:zl,MeshLambertMaterial:Bl,MeshDepthMaterial:Bs,MeshDistanceMaterial:Fs,MeshBasicMaterial:Qe,MeshMatcapMaterial:Fl,LineDashedMaterial:Ol,LineBasicMaterial:Ua,Material:Ve});const Hl={arraySlice:function(t,e,n){return Hl.isTypedArray(t)?new t.constructor(t.subarray(e,void 0!==n?n:t.length)):t.slice(e,n)},convertArray:function(t,e,n){return!t||!n&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)},isTypedArray:function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)},getKeyframeOrder:function(t){const e=t.length,n=new Array(e);for(let t=0;t!==e;++t)n[t]=t;return n.sort((function(e,n){return t[e]-t[n]})),n},sortedArray:function(t,e,n){const i=t.length,r=new t.constructor(i);for(let s=0,a=0;a!==i;++s){const i=n[s]*e;for(let n=0;n!==e;++n)r[a++]=t[i+n]}return r},flattenJSON:function(t,e,n,i){let r=1,s=t[0];for(;void 0!==s&&void 0===s[i];)s=t[r++];if(void 0===s)return;let a=s[i];if(void 0!==a)if(Array.isArray(a))do{a=s[i],void 0!==a&&(e.push(s.time),n.push.apply(n,a)),s=t[r++]}while(void 0!==s);else if(void 0!==a.toArray)do{a=s[i],void 0!==a&&(e.push(s.time),a.toArray(n,n.length)),s=t[r++]}while(void 0!==s);else do{a=s[i],void 0!==a&&(e.push(s.time),n.push(a)),s=t[r++]}while(void 0!==s)},subclip:function(t,e,n,i,r=30){const s=t.clone();s.name=e;const a=[];for(let t=0;t<s.tracks.length;++t){const e=s.tracks[t],o=e.getValueSize(),l=[],c=[];for(let t=0;t<e.times.length;++t){const s=e.times[t]*r;if(!(s<n||s>=i)){l.push(e.times[t]);for(let n=0;n<o;++n)c.push(e.values[t*o+n])}}0!==l.length&&(e.times=Hl.convertArray(l,e.times.constructor),e.values=Hl.convertArray(c,e.values.constructor),a.push(e))}s.tracks=a;let o=1/0;for(let t=0;t<s.tracks.length;++t)o>s.tracks[t].times[0]&&(o=s.tracks[t].times[0]);for(let t=0;t<s.tracks.length;++t)s.tracks[t].shift(-1*o);return s.resetDuration(),s},makeClipAdditive:function(t,e=0,n=t,i=30){i<=0&&(i=30);const r=n.tracks.length,s=e/i;for(let e=0;e<r;++e){const i=n.tracks[e],r=i.ValueTypeName;if("bool"===r||"string"===r)continue;const a=t.tracks.find((function(t){return t.name===i.name&&t.ValueTypeName===r}));if(void 0===a)continue;let o=0;const l=i.getValueSize();i.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(o=l/3);let c=0;const h=a.getValueSize();a.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(c=h/3);const u=i.times.length-1;let d;if(s<=i.times[0]){const t=o,e=l-o;d=Hl.arraySlice(i.values,t,e)}else if(s>=i.times[u]){const t=u*l+o,e=t+l-o;d=Hl.arraySlice(i.values,t,e)}else{const t=i.createInterpolant(),e=o,n=l-o;t.evaluate(s),d=Hl.arraySlice(t.resultBuffer,e,n)}if("quaternion"===r){(new At).fromArray(d).normalize().conjugate().toArray(d)}const p=a.times.length;for(let t=0;t<p;++t){const e=t*h+c;if("quaternion"===r)At.multiplyQuaternionsFlat(a.values,e,d,0,a.values,e);else{const t=h-2*c;for(let n=0;n<t;++n)a.values[e+n]-=d[n]}}}return t.blendMode=q,t}};class Gl{constructor(t,e,n,i){this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=void 0!==i?i:new e.constructor(n),this.sampleValues=e,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(t){const e=this.parameterPositions;let n=this._cachedIndex,i=e[n],r=e[n-1];t:{e:{let s;n:{i:if(!(t<i)){for(let s=n+2;;){if(void 0===i){if(t<r)break i;return n=e.length,this._cachedIndex=n,this.afterEnd_(n-1,t,r)}if(n===s)break;if(r=i,i=e[++n],t<i)break e}s=e.length;break n}if(t>=r)break t;{const a=e[1];t<a&&(n=2,r=a);for(let s=n-2;;){if(void 0===r)return this._cachedIndex=0,this.beforeStart_(0,t,i);if(n===s)break;if(i=r,r=e[--n-1],t>=r)break e}s=n,n=0}}for(;n<s;){const i=n+s>>>1;t<e[i]?s=i:n=i+1}if(i=e[n],r=e[n-1],void 0===r)return this._cachedIndex=0,this.beforeStart_(0,t,i);if(void 0===i)return n=e.length,this._cachedIndex=n,this.afterEnd_(n-1,r,t)}this._cachedIndex=n,this.intervalChanged_(n,r,i)}return this.interpolate_(n,r,t,i)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(t){const e=this.resultBuffer,n=this.sampleValues,i=this.valueSize,r=t*i;for(let t=0;t!==i;++t)e[t]=n[r+t];return e}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}}Gl.prototype.beforeStart_=Gl.prototype.copySampleValue_,Gl.prototype.afterEnd_=Gl.prototype.copySampleValue_;class kl extends Gl{constructor(t,e,n,i){super(t,e,n,i),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:k,endingEnd:k}}intervalChanged_(t,e,n){const i=this.parameterPositions;let r=t-2,s=t+1,a=i[r],o=i[s];if(void 0===a)switch(this.getSettings_().endingStart){case V:r=t,a=2*e-n;break;case W:r=i.length-2,a=e+i[r]-i[r+1];break;default:r=t,a=n}if(void 0===o)switch(this.getSettings_().endingEnd){case V:s=t,o=2*n-e;break;case W:s=1,o=n+i[1]-i[0];break;default:s=t-1,o=e}const l=.5*(n-e),c=this.valueSize;this._weightPrev=l/(e-a),this._weightNext=l/(o-n),this._offsetPrev=r*c,this._offsetNext=s*c}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=t*a,l=o-a,c=this._offsetPrev,h=this._offsetNext,u=this._weightPrev,d=this._weightNext,p=(n-e)/(i-e),m=p*p,f=m*p,g=-u*f+2*u*m-u*p,v=(1+u)*f+(-1.5-2*u)*m+(-.5+u)*p+1,y=(-1-d)*f+(1.5+d)*m+.5*p,x=d*f-d*m;for(let t=0;t!==a;++t)r[t]=g*s[c+t]+v*s[l+t]+y*s[o+t]+x*s[h+t];return r}}class Vl extends Gl{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=t*a,l=o-a,c=(n-e)/(i-e),h=1-c;for(let t=0;t!==a;++t)r[t]=s[l+t]*h+s[o+t]*c;return r}}class Wl extends Gl{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t){return this.copySampleValue_(t-1)}}class jl{constructor(t,e,n,i){if(void 0===t)throw new Error("THREE.KeyframeTrack: track name is undefined");if(void 0===e||0===e.length)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+t);this.name=t,this.times=Hl.convertArray(e,this.TimeBufferType),this.values=Hl.convertArray(n,this.ValueBufferType),this.setInterpolation(i||this.DefaultInterpolation)}static toJSON(t){const e=t.constructor;let n;if(e.toJSON!==this.toJSON)n=e.toJSON(t);else{n={name:t.name,times:Hl.convertArray(t.times,Array),values:Hl.convertArray(t.values,Array)};const e=t.getInterpolation();e!==t.DefaultInterpolation&&(n.interpolation=e)}return n.type=t.ValueTypeName,n}InterpolantFactoryMethodDiscrete(t){return new Wl(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodLinear(t){return new Vl(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodSmooth(t){return new kl(this.times,this.values,this.getValueSize(),t)}setInterpolation(t){let e;switch(t){case U:e=this.InterpolantFactoryMethodDiscrete;break;case H:e=this.InterpolantFactoryMethodLinear;break;case G:e=this.InterpolantFactoryMethodSmooth}if(void 0===e){const e="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(void 0===this.createInterpolant){if(t===this.DefaultInterpolation)throw new Error(e);this.setInterpolation(this.DefaultInterpolation)}return console.warn("THREE.KeyframeTrack:",e),this}return this.createInterpolant=e,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return U;case this.InterpolantFactoryMethodLinear:return H;case this.InterpolantFactoryMethodSmooth:return G}}getValueSize(){return this.values.length/this.times.length}shift(t){if(0!==t){const e=this.times;for(let n=0,i=e.length;n!==i;++n)e[n]+=t}return this}scale(t){if(1!==t){const e=this.times;for(let n=0,i=e.length;n!==i;++n)e[n]*=t}return this}trim(t,e){const n=this.times,i=n.length;let r=0,s=i-1;for(;r!==i&&n[r]<t;)++r;for(;-1!==s&&n[s]>e;)--s;if(++s,0!==r||s!==i){r>=s&&(s=Math.max(s,1),r=s-1);const t=this.getValueSize();this.times=Hl.arraySlice(n,r,s),this.values=Hl.arraySlice(this.values,r*t,s*t)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);const n=this.times,i=this.values,r=n.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),t=!1);let s=null;for(let e=0;e!==r;e++){const i=n[e];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,e,i),t=!1;break}if(null!==s&&s>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,e,i,s),t=!1;break}s=i}if(void 0!==i&&Hl.isTypedArray(i))for(let e=0,n=i.length;e!==n;++e){const n=i[e];if(isNaN(n)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,e,n),t=!1;break}}return t}optimize(){const t=Hl.arraySlice(this.times),e=Hl.arraySlice(this.values),n=this.getValueSize(),i=this.getInterpolation()===G,r=t.length-1;let s=1;for(let a=1;a<r;++a){let r=!1;const o=t[a];if(o!==t[a+1]&&(1!==a||o!==t[0]))if(i)r=!0;else{const t=a*n,i=t-n,s=t+n;for(let a=0;a!==n;++a){const n=e[t+a];if(n!==e[i+a]||n!==e[s+a]){r=!0;break}}}if(r){if(a!==s){t[s]=t[a];const i=a*n,r=s*n;for(let t=0;t!==n;++t)e[r+t]=e[i+t]}++s}}if(r>0){t[s]=t[r];for(let t=r*n,i=s*n,a=0;a!==n;++a)e[i+a]=e[t+a];++s}return s!==t.length?(this.times=Hl.arraySlice(t,0,s),this.values=Hl.arraySlice(e,0,s*n)):(this.times=t,this.values=e),this}clone(){const t=Hl.arraySlice(this.times,0),e=Hl.arraySlice(this.values,0),n=new(0,this.constructor)(this.name,t,e);return n.createInterpolant=this.createInterpolant,n}}jl.prototype.TimeBufferType=Float32Array,jl.prototype.ValueBufferType=Float32Array,jl.prototype.DefaultInterpolation=H;class ql extends jl{}ql.prototype.ValueTypeName="bool",ql.prototype.ValueBufferType=Array,ql.prototype.DefaultInterpolation=U,ql.prototype.InterpolantFactoryMethodLinear=void 0,ql.prototype.InterpolantFactoryMethodSmooth=void 0;class Xl extends jl{}Xl.prototype.ValueTypeName="color";class Jl extends jl{}Jl.prototype.ValueTypeName="number";class Yl extends Gl{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(n-e)/(i-e);let l=t*a;for(let t=l+a;l!==t;l+=4)At.slerpFlat(r,0,s,l-a,s,l,o);return r}}class Zl extends jl{InterpolantFactoryMethodLinear(t){return new Yl(this.times,this.values,this.getValueSize(),t)}}Zl.prototype.ValueTypeName="quaternion",Zl.prototype.DefaultInterpolation=H,Zl.prototype.InterpolantFactoryMethodSmooth=void 0;class Ql extends jl{}Ql.prototype.ValueTypeName="string",Ql.prototype.ValueBufferType=Array,Ql.prototype.DefaultInterpolation=U,Ql.prototype.InterpolantFactoryMethodLinear=void 0,Ql.prototype.InterpolantFactoryMethodSmooth=void 0;class Kl extends jl{}Kl.prototype.ValueTypeName="vector";class $l{constructor(t,e=-1,n,i=2500){this.name=t,this.tracks=n,this.duration=e,this.blendMode=i,this.uuid=rt(),this.duration<0&&this.resetDuration()}static parse(t){const e=[],n=t.tracks,i=1/(t.fps||1);for(let t=0,r=n.length;t!==r;++t)e.push(tc(n[t]).scale(i));const r=new this(t.name,t.duration,e,t.blendMode);return r.uuid=t.uuid,r}static toJSON(t){const e=[],n=t.tracks,i={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode};for(let t=0,i=n.length;t!==i;++t)e.push(jl.toJSON(n[t]));return i}static CreateFromMorphTargetSequence(t,e,n,i){const r=e.length,s=[];for(let t=0;t<r;t++){let a=[],o=[];a.push((t+r-1)%r,t,(t+1)%r),o.push(0,1,0);const l=Hl.getKeyframeOrder(a);a=Hl.sortedArray(a,1,l),o=Hl.sortedArray(o,1,l),i||0!==a[0]||(a.push(r),o.push(o[0])),s.push(new Jl(".morphTargetInfluences["+e[t].name+"]",a,o).scale(1/n))}return new this(t,-1,s)}static findByName(t,e){let n=t;if(!Array.isArray(t)){const e=t;n=e.geometry&&e.geometry.animations||e.animations}for(let t=0;t<n.length;t++)if(n[t].name===e)return n[t];return null}static CreateClipsFromMorphTargetSequences(t,e,n){const i={},r=/^([\w-]*?)([\d]+)$/;for(let e=0,n=t.length;e<n;e++){const n=t[e],s=n.name.match(r);if(s&&s.length>1){const t=s[1];let e=i[t];e||(i[t]=e=[]),e.push(n)}}const s=[];for(const t in i)s.push(this.CreateFromMorphTargetSequence(t,i[t],e,n));return s}static parseAnimation(t,e){if(!t)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(t,e,n,i,r){if(0!==n.length){const s=[],a=[];Hl.flattenJSON(n,s,a,i),0!==s.length&&r.push(new t(e,s,a))}},i=[],r=t.name||"default",s=t.fps||30,a=t.blendMode;let o=t.length||-1;const l=t.hierarchy||[];for(let t=0;t<l.length;t++){const r=l[t].keys;if(r&&0!==r.length)if(r[0].morphTargets){const t={};let e;for(e=0;e<r.length;e++)if(r[e].morphTargets)for(let n=0;n<r[e].morphTargets.length;n++)t[r[e].morphTargets[n]]=-1;for(const n in t){const t=[],s=[];for(let i=0;i!==r[e].morphTargets.length;++i){const i=r[e];t.push(i.time),s.push(i.morphTarget===n?1:0)}i.push(new Jl(".morphTargetInfluence["+n+"]",t,s))}o=t.length*(s||1)}else{const s=".bones["+e[t].name+"]";n(Kl,s+".position",r,"pos",i),n(Zl,s+".quaternion",r,"rot",i),n(Kl,s+".scale",r,"scl",i)}}if(0===i.length)return null;return new this(r,o,i,a)}resetDuration(){let t=0;for(let e=0,n=this.tracks.length;e!==n;++e){const n=this.tracks[e];t=Math.max(t,n.times[n.times.length-1])}return this.duration=t,this}trim(){for(let t=0;t<this.tracks.length;t++)this.tracks[t].trim(0,this.duration);return this}validate(){let t=!0;for(let e=0;e<this.tracks.length;e++)t=t&&this.tracks[e].validate();return t}optimize(){for(let t=0;t<this.tracks.length;t++)this.tracks[t].optimize();return this}clone(){const t=[];for(let e=0;e<this.tracks.length;e++)t.push(this.tracks[e].clone());return new this.constructor(this.name,this.duration,t,this.blendMode)}toJSON(){return this.constructor.toJSON(this)}}function tc(t){if(void 0===t.type)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const e=function(t){switch(t.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return Jl;case"vector":case"vector2":case"vector3":case"vector4":return Kl;case"color":return Xl;case"quaternion":return Zl;case"bool":case"boolean":return ql;case"string":return Ql}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+t)}(t.type);if(void 0===t.times){const e=[],n=[];Hl.flattenJSON(t.keys,e,n,"value"),t.times=e,t.values=n}return void 0!==e.parse?e.parse(t):new e(t.name,t.times,t.values,t.interpolation)}const ec={enabled:!1,files:{},add:function(t,e){!1!==this.enabled&&(this.files[t]=e)},get:function(t){if(!1!==this.enabled)return this.files[t]},remove:function(t){delete this.files[t]},clear:function(){this.files={}}};class nc{constructor(t,e,n){const i=this;let r,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=n,this.itemStart=function(t){o++,!1===s&&void 0!==i.onStart&&i.onStart(t,a,o),s=!0},this.itemEnd=function(t){a++,void 0!==i.onProgress&&i.onProgress(t,a,o),a===o&&(s=!1,void 0!==i.onLoad&&i.onLoad())},this.itemError=function(t){void 0!==i.onError&&i.onError(t)},this.resolveURL=function(t){return r?r(t):t},this.setURLModifier=function(t){return r=t,this},this.addHandler=function(t,e){return l.push(t,e),this},this.removeHandler=function(t){const e=l.indexOf(t);return-1!==e&&l.splice(e,2),this},this.getHandler=function(t){for(let e=0,n=l.length;e<n;e+=2){const n=l[e],i=l[e+1];if(n.global&&(n.lastIndex=0),n.test(t))return i}return null}}}const ic=new nc;class rc{constructor(t){this.manager=void 0!==t?t:ic,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(t,e){const n=this;return new Promise((function(i,r){n.load(t,i,e,r)}))}parse(){}setCrossOrigin(t){return this.crossOrigin=t,this}setWithCredentials(t){return this.withCredentials=t,this}setPath(t){return this.path=t,this}setResourcePath(t){return this.resourcePath=t,this}setRequestHeader(t){return this.requestHeader=t,this}}const sc={};class ac extends rc{constructor(t){super(t)}load(t,e,n,i){void 0===t&&(t=""),void 0!==this.path&&(t=this.path+t),t=this.manager.resolveURL(t);const r=ec.get(t);if(void 0!==r)return this.manager.itemStart(t),setTimeout((()=>{e&&e(r),this.manager.itemEnd(t)}),0),r;if(void 0!==sc[t])return void sc[t].push({onLoad:e,onProgress:n,onError:i});sc[t]=[],sc[t].push({onLoad:e,onProgress:n,onError:i});const s=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"});fetch(s).then((e=>{if(200===e.status||0===e.status){if(0===e.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===e.body.getReader)return e;const n=sc[t],i=e.body.getReader(),r=e.headers.get("Content-Length"),s=r?parseInt(r):0,a=0!==s;let o=0;const l=new ReadableStream({start(t){!function e(){i.read().then((({done:i,value:r})=>{if(i)t.close();else{o+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:s});for(let t=0,e=n.length;t<e;t++){const e=n[t];e.onProgress&&e.onProgress(i)}t.enqueue(r),e()}}))}()}});return new Response(l)}throw Error(`fetch for "${e.url}" responded with ${e.status}: ${e.statusText}`)})).then((t=>{switch(this.responseType){case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"document":return t.text().then((t=>(new DOMParser).parseFromString(t,this.mimeType)));case"json":return t.json();default:return t.text()}})).then((e=>{ec.add(t,e);const n=sc[t];delete sc[t];for(let t=0,i=n.length;t<i;t++){const i=n[t];i.onLoad&&i.onLoad(e)}})).catch((e=>{const n=sc[t];if(void 0===n)throw this.manager.itemError(t),e;delete sc[t];for(let t=0,i=n.length;t<i;t++){const i=n[t];i.onError&&i.onError(e)}this.manager.itemError(t)})).finally((()=>{this.manager.itemEnd(t)})),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}}class oc extends rc{constructor(t){super(t)}load(t,e,n,i){void 0!==this.path&&(t=this.path+t),t=this.manager.resolveURL(t);const r=this,s=ec.get(t);if(void 0!==s)return r.manager.itemStart(t),setTimeout((function(){e&&e(s),r.manager.itemEnd(t)}),0),s;const a=vt("img");function o(){c(),ec.add(t,this),e&&e(this),r.manager.itemEnd(t)}function l(e){c(),i&&i(e),r.manager.itemError(t),r.manager.itemEnd(t)}function c(){a.removeEventListener("load",o,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",o,!1),a.addEventListener("error",l,!1),"data:"!==t.substr(0,5)&&void 0!==this.crossOrigin&&(a.crossOrigin=this.crossOrigin),r.manager.itemStart(t),a.src=t,a}}class lc extends rc{constructor(t){super(t)}load(t,e,n,i){const r=new Jn,s=new oc(this.manager);s.setCrossOrigin(this.crossOrigin),s.setPath(this.path);let a=0;function o(n){s.load(t[n],(function(t){r.images[n]=t,a++,6===a&&(r.needsUpdate=!0,e&&e(r))}),void 0,i)}for(let e=0;e<t.length;++e)o(e);return r}}class cc extends rc{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new Ra,a=new ac(this.manager);return a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setPath(this.path),a.setWithCredentials(r.withCredentials),a.load(t,(function(t){const n=r.parse(t);n&&(void 0!==n.image?s.image=n.image:void 0!==n.data&&(s.image.width=n.width,s.image.height=n.height,s.image.data=n.data),s.wrapS=void 0!==n.wrapS?n.wrapS:u,s.wrapT=void 0!==n.wrapT?n.wrapT:u,s.magFilter=void 0!==n.magFilter?n.magFilter:g,s.minFilter=void 0!==n.minFilter?n.minFilter:g,s.anisotropy=void 0!==n.anisotropy?n.anisotropy:1,void 0!==n.encoding&&(s.encoding=n.encoding),void 0!==n.flipY&&(s.flipY=n.flipY),void 0!==n.format&&(s.format=n.format),void 0!==n.type&&(s.type=n.type),void 0!==n.mipmaps&&(s.mipmaps=n.mipmaps,s.minFilter=y),1===n.mipmapCount&&(s.minFilter=g),void 0!==n.generateMipmaps&&(s.generateMipmaps=n.generateMipmaps),s.needsUpdate=!0,e&&e(s,n))}),n,i),s}}class hc extends rc{constructor(t){super(t)}load(t,e,n,i){const r=new bt,s=new oc(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(t,(function(t){r.image=t,r.needsUpdate=!0,void 0!==e&&e(r)}),n,i),r}}class uc extends Ce{constructor(t,e=1){super(),this.type="Light",this.color=new Ze(t),this.intensity=e}dispose(){}copy(t){return super.copy(t),this.color.copy(t.color),this.intensity=t.intensity,this}toJSON(t){const e=super.toJSON(t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),void 0!==this.shadow&&(e.object.shadow=this.shadow.toJSON()),e}}uc.prototype.isLight=!0;class dc extends uc{constructor(t,e,n){super(t,n),this.type="HemisphereLight",this.position.copy(Ce.DefaultUp),this.updateMatrix(),this.groundColor=new Ze(e)}copy(t){return uc.prototype.copy.call(this,t),this.groundColor.copy(t.groundColor),this}}dc.prototype.isHemisphereLight=!0;const pc=new se,mc=new Lt,fc=new Lt;class gc{constructor(t){this.camera=t,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new dt(512,512),this.map=null,this.mapPass=null,this.matrix=new se,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new ni,this._frameExtents=new dt(1,1),this._viewportCount=1,this._viewports=[new wt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(t){const e=this.camera,n=this.matrix;mc.setFromMatrixPosition(t.matrixWorld),e.position.copy(mc),fc.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(fc),e.updateMatrixWorld(),pc.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._frustum.setFromProjectionMatrix(pc),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(e.projectionMatrix),n.multiply(e.matrixWorldInverse)}getViewport(t){return this._viewports[t]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(t){return this.camera=t.camera.clone(),this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this}clone(){return(new this.constructor).copy(this)}toJSON(){const t={};return 0!==this.bias&&(t.bias=this.bias),0!==this.normalBias&&(t.normalBias=this.normalBias),1!==this.radius&&(t.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(t.mapSize=this.mapSize.toArray()),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}}class vc extends gc{constructor(){super(new jn(50,1,.5,500)),this.focus=1}updateMatrices(t){const e=this.camera,n=2*it*t.angle*this.focus,i=this.mapSize.width/this.mapSize.height,r=t.distance||e.far;n===e.fov&&i===e.aspect&&r===e.far||(e.fov=n,e.aspect=i,e.far=r,e.updateProjectionMatrix()),super.updateMatrices(t)}copy(t){return super.copy(t),this.focus=t.focus,this}}vc.prototype.isSpotLightShadow=!0;class yc extends uc{constructor(t,e,n=0,i=Math.PI/3,r=0,s=1){super(t,e),this.type="SpotLight",this.position.copy(Ce.DefaultUp),this.updateMatrix(),this.target=new Ce,this.distance=n,this.angle=i,this.penumbra=r,this.decay=s,this.shadow=new vc}get power(){return this.intensity*Math.PI}set power(t){this.intensity=t/Math.PI}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}yc.prototype.isSpotLight=!0;const xc=new se,_c=new Lt,bc=new Lt;class Mc extends gc{constructor(){super(new jn(90,1,.5,500)),this._frameExtents=new dt(4,2),this._viewportCount=6,this._viewports=[new wt(2,1,1,1),new wt(0,1,1,1),new wt(3,1,1,1),new wt(1,1,1,1),new wt(3,0,1,1),new wt(1,0,1,1)],this._cubeDirections=[new Lt(1,0,0),new Lt(-1,0,0),new Lt(0,0,1),new Lt(0,0,-1),new Lt(0,1,0),new Lt(0,-1,0)],this._cubeUps=[new Lt(0,1,0),new Lt(0,1,0),new Lt(0,1,0),new Lt(0,1,0),new Lt(0,0,1),new Lt(0,0,-1)]}updateMatrices(t,e=0){const n=this.camera,i=this.matrix,r=t.distance||n.far;r!==n.far&&(n.far=r,n.updateProjectionMatrix()),_c.setFromMatrixPosition(t.matrixWorld),n.position.copy(_c),bc.copy(n.position),bc.add(this._cubeDirections[e]),n.up.copy(this._cubeUps[e]),n.lookAt(bc),n.updateMatrixWorld(),i.makeTranslation(-_c.x,-_c.y,-_c.z),xc.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(xc)}}Mc.prototype.isPointLightShadow=!0;class wc extends uc{constructor(t,e,n=0,i=1){super(t,e),this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new Mc}get power(){return 4*this.intensity*Math.PI}set power(t){this.intensity=t/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}wc.prototype.isPointLight=!0;class Sc extends gc{constructor(){super(new fi(-5,5,5,-5,.5,500))}}Sc.prototype.isDirectionalLightShadow=!0;class Tc extends uc{constructor(t,e){super(t,e),this.type="DirectionalLight",this.position.copy(Ce.DefaultUp),this.updateMatrix(),this.target=new Ce,this.shadow=new Sc}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}Tc.prototype.isDirectionalLight=!0;class Ec extends uc{constructor(t,e){super(t,e),this.type="AmbientLight"}}Ec.prototype.isAmbientLight=!0;class Ac extends uc{constructor(t,e,n=10,i=10){super(t,e),this.type="RectAreaLight",this.width=n,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(t){this.intensity=t/(this.width*this.height*Math.PI)}copy(t){return super.copy(t),this.width=t.width,this.height=t.height,this}toJSON(t){const e=super.toJSON(t);return e.object.width=this.width,e.object.height=this.height,e}}Ac.prototype.isRectAreaLight=!0;class Lc{constructor(){this.coefficients=[];for(let t=0;t<9;t++)this.coefficients.push(new Lt)}set(t){for(let e=0;e<9;e++)this.coefficients[e].copy(t[e]);return this}zero(){for(let t=0;t<9;t++)this.coefficients[t].set(0,0,0);return this}getAt(t,e){const n=t.x,i=t.y,r=t.z,s=this.coefficients;return e.copy(s[0]).multiplyScalar(.282095),e.addScaledVector(s[1],.488603*i),e.addScaledVector(s[2],.488603*r),e.addScaledVector(s[3],.488603*n),e.addScaledVector(s[4],n*i*1.092548),e.addScaledVector(s[5],i*r*1.092548),e.addScaledVector(s[6],.315392*(3*r*r-1)),e.addScaledVector(s[7],n*r*1.092548),e.addScaledVector(s[8],.546274*(n*n-i*i)),e}getIrradianceAt(t,e){const n=t.x,i=t.y,r=t.z,s=this.coefficients;return e.copy(s[0]).multiplyScalar(.886227),e.addScaledVector(s[1],1.023328*i),e.addScaledVector(s[2],1.023328*r),e.addScaledVector(s[3],1.023328*n),e.addScaledVector(s[4],.858086*n*i),e.addScaledVector(s[5],.858086*i*r),e.addScaledVector(s[6],.743125*r*r-.247708),e.addScaledVector(s[7],.858086*n*r),e.addScaledVector(s[8],.429043*(n*n-i*i)),e}add(t){for(let e=0;e<9;e++)this.coefficients[e].add(t.coefficients[e]);return this}addScaledSH(t,e){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(t.coefficients[n],e);return this}scale(t){for(let e=0;e<9;e++)this.coefficients[e].multiplyScalar(t);return this}lerp(t,e){for(let n=0;n<9;n++)this.coefficients[n].lerp(t.coefficients[n],e);return this}equals(t){for(let e=0;e<9;e++)if(!this.coefficients[e].equals(t.coefficients[e]))return!1;return!0}copy(t){return this.set(t.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(t,e=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].fromArray(t,e+3*i);return this}toArray(t=[],e=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].toArray(t,e+3*i);return t}static getBasisAt(t,e){const n=t.x,i=t.y,r=t.z;e[0]=.282095,e[1]=.488603*i,e[2]=.488603*r,e[3]=.488603*n,e[4]=1.092548*n*i,e[5]=1.092548*i*r,e[6]=.315392*(3*r*r-1),e[7]=1.092548*n*r,e[8]=.546274*(n*n-i*i)}}Lc.prototype.isSphericalHarmonics3=!0;class Rc extends uc{constructor(t=new Lc,e=1){super(void 0,e),this.sh=t}copy(t){return super.copy(t),this.sh.copy(t.sh),this}fromJSON(t){return this.intensity=t.intensity,this.sh.fromArray(t.sh),this}toJSON(t){const e=super.toJSON(t);return e.object.sh=this.sh.toArray(),e}}Rc.prototype.isLightProbe=!0;class Cc extends rc{constructor(t){super(t),this.textures={}}load(t,e,n,i){const r=this,s=new ac(r.manager);s.setPath(r.path),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(t,(function(n){try{e(r.parse(JSON.parse(n)))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}parse(t){const e=this.textures;function n(t){return void 0===e[t]&&console.warn("THREE.MaterialLoader: Undefined texture",t),e[t]}const i=new Ul[t.type];if(void 0!==t.uuid&&(i.uuid=t.uuid),void 0!==t.name&&(i.name=t.name),void 0!==t.color&&void 0!==i.color&&i.color.setHex(t.color),void 0!==t.roughness&&(i.roughness=t.roughness),void 0!==t.metalness&&(i.metalness=t.metalness),void 0!==t.sheen&&(i.sheen=t.sheen),void 0!==t.sheenColor&&(i.sheenColor=(new Ze).setHex(t.sheenColor)),void 0!==t.sheenRoughness&&(i.sheenRoughness=t.sheenRoughness),void 0!==t.emissive&&void 0!==i.emissive&&i.emissive.setHex(t.emissive),void 0!==t.specular&&void 0!==i.specular&&i.specular.setHex(t.specular),void 0!==t.specularIntensity&&(i.specularIntensity=t.specularIntensity),void 0!==t.specularColor&&void 0!==i.specularColor&&i.specularColor.setHex(t.specularColor),void 0!==t.shininess&&(i.shininess=t.shininess),void 0!==t.clearcoat&&(i.clearcoat=t.clearcoat),void 0!==t.clearcoatRoughness&&(i.clearcoatRoughness=t.clearcoatRoughness),void 0!==t.transmission&&(i.transmission=t.transmission),void 0!==t.thickness&&(i.thickness=t.thickness),void 0!==t.attenuationDistance&&(i.attenuationDistance=t.attenuationDistance),void 0!==t.attenuationColor&&void 0!==i.attenuationColor&&i.attenuationColor.setHex(t.attenuationColor),void 0!==t.fog&&(i.fog=t.fog),void 0!==t.flatShading&&(i.flatShading=t.flatShading),void 0!==t.blending&&(i.blending=t.blending),void 0!==t.combine&&(i.combine=t.combine),void 0!==t.side&&(i.side=t.side),void 0!==t.shadowSide&&(i.shadowSide=t.shadowSide),void 0!==t.opacity&&(i.opacity=t.opacity),void 0!==t.format&&(i.format=t.format),void 0!==t.transparent&&(i.transparent=t.transparent),void 0!==t.alphaTest&&(i.alphaTest=t.alphaTest),void 0!==t.depthTest&&(i.depthTest=t.depthTest),void 0!==t.depthWrite&&(i.depthWrite=t.depthWrite),void 0!==t.colorWrite&&(i.colorWrite=t.colorWrite),void 0!==t.stencilWrite&&(i.stencilWrite=t.stencilWrite),void 0!==t.stencilWriteMask&&(i.stencilWriteMask=t.stencilWriteMask),void 0!==t.stencilFunc&&(i.stencilFunc=t.stencilFunc),void 0!==t.stencilRef&&(i.stencilRef=t.stencilRef),void 0!==t.stencilFuncMask&&(i.stencilFuncMask=t.stencilFuncMask),void 0!==t.stencilFail&&(i.stencilFail=t.stencilFail),void 0!==t.stencilZFail&&(i.stencilZFail=t.stencilZFail),void 0!==t.stencilZPass&&(i.stencilZPass=t.stencilZPass),void 0!==t.wireframe&&(i.wireframe=t.wireframe),void 0!==t.wireframeLinewidth&&(i.wireframeLinewidth=t.wireframeLinewidth),void 0!==t.wireframeLinecap&&(i.wireframeLinecap=t.wireframeLinecap),void 0!==t.wireframeLinejoin&&(i.wireframeLinejoin=t.wireframeLinejoin),void 0!==t.rotation&&(i.rotation=t.rotation),1!==t.linewidth&&(i.linewidth=t.linewidth),void 0!==t.dashSize&&(i.dashSize=t.dashSize),void 0!==t.gapSize&&(i.gapSize=t.gapSize),void 0!==t.scale&&(i.scale=t.scale),void 0!==t.polygonOffset&&(i.polygonOffset=t.polygonOffset),void 0!==t.polygonOffsetFactor&&(i.polygonOffsetFactor=t.polygonOffsetFactor),void 0!==t.polygonOffsetUnits&&(i.polygonOffsetUnits=t.polygonOffsetUnits),void 0!==t.dithering&&(i.dithering=t.dithering),void 0!==t.alphaToCoverage&&(i.alphaToCoverage=t.alphaToCoverage),void 0!==t.premultipliedAlpha&&(i.premultipliedAlpha=t.premultipliedAlpha),void 0!==t.visible&&(i.visible=t.visible),void 0!==t.toneMapped&&(i.toneMapped=t.toneMapped),void 0!==t.userData&&(i.userData=t.userData),void 0!==t.vertexColors&&("number"==typeof t.vertexColors?i.vertexColors=t.vertexColors>0:i.vertexColors=t.vertexColors),void 0!==t.uniforms)for(const e in t.uniforms){const r=t.uniforms[e];switch(i.uniforms[e]={},r.type){case"t":i.uniforms[e].value=n(r.value);break;case"c":i.uniforms[e].value=(new Ze).setHex(r.value);break;case"v2":i.uniforms[e].value=(new dt).fromArray(r.value);break;case"v3":i.uniforms[e].value=(new Lt).fromArray(r.value);break;case"v4":i.uniforms[e].value=(new wt).fromArray(r.value);break;case"m3":i.uniforms[e].value=(new pt).fromArray(r.value);break;case"m4":i.uniforms[e].value=(new se).fromArray(r.value);break;default:i.uniforms[e].value=r.value}}if(void 0!==t.defines&&(i.defines=t.defines),void 0!==t.vertexShader&&(i.vertexShader=t.vertexShader),void 0!==t.fragmentShader&&(i.fragmentShader=t.fragmentShader),void 0!==t.extensions)for(const e in t.extensions)i.extensions[e]=t.extensions[e];if(void 0!==t.shading&&(i.flatShading=1===t.shading),void 0!==t.size&&(i.size=t.size),void 0!==t.sizeAttenuation&&(i.sizeAttenuation=t.sizeAttenuation),void 0!==t.map&&(i.map=n(t.map)),void 0!==t.matcap&&(i.matcap=n(t.matcap)),void 0!==t.alphaMap&&(i.alphaMap=n(t.alphaMap)),void 0!==t.bumpMap&&(i.bumpMap=n(t.bumpMap)),void 0!==t.bumpScale&&(i.bumpScale=t.bumpScale),void 0!==t.normalMap&&(i.normalMap=n(t.normalMap)),void 0!==t.normalMapType&&(i.normalMapType=t.normalMapType),void 0!==t.normalScale){let e=t.normalScale;!1===Array.isArray(e)&&(e=[e,e]),i.normalScale=(new dt).fromArray(e)}return void 0!==t.displacementMap&&(i.displacementMap=n(t.displacementMap)),void 0!==t.displacementScale&&(i.displacementScale=t.displacementScale),void 0!==t.displacementBias&&(i.displacementBias=t.displacementBias),void 0!==t.roughnessMap&&(i.roughnessMap=n(t.roughnessMap)),void 0!==t.metalnessMap&&(i.metalnessMap=n(t.metalnessMap)),void 0!==t.emissiveMap&&(i.emissiveMap=n(t.emissiveMap)),void 0!==t.emissiveIntensity&&(i.emissiveIntensity=t.emissiveIntensity),void 0!==t.specularMap&&(i.specularMap=n(t.specularMap)),void 0!==t.specularIntensityMap&&(i.specularIntensityMap=n(t.specularIntensityMap)),void 0!==t.specularColorMap&&(i.specularColorMap=n(t.specularColorMap)),void 0!==t.envMap&&(i.envMap=n(t.envMap)),void 0!==t.envMapIntensity&&(i.envMapIntensity=t.envMapIntensity),void 0!==t.reflectivity&&(i.reflectivity=t.reflectivity),void 0!==t.refractionRatio&&(i.refractionRatio=t.refractionRatio),void 0!==t.lightMap&&(i.lightMap=n(t.lightMap)),void 0!==t.lightMapIntensity&&(i.lightMapIntensity=t.lightMapIntensity),void 0!==t.aoMap&&(i.aoMap=n(t.aoMap)),void 0!==t.aoMapIntensity&&(i.aoMapIntensity=t.aoMapIntensity),void 0!==t.gradientMap&&(i.gradientMap=n(t.gradientMap)),void 0!==t.clearcoatMap&&(i.clearcoatMap=n(t.clearcoatMap)),void 0!==t.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=n(t.clearcoatRoughnessMap)),void 0!==t.clearcoatNormalMap&&(i.clearcoatNormalMap=n(t.clearcoatNormalMap)),void 0!==t.clearcoatNormalScale&&(i.clearcoatNormalScale=(new dt).fromArray(t.clearcoatNormalScale)),void 0!==t.transmissionMap&&(i.transmissionMap=n(t.transmissionMap)),void 0!==t.thicknessMap&&(i.thicknessMap=n(t.thicknessMap)),void 0!==t.sheenColorMap&&(i.sheenColorMap=n(t.sheenColorMap)),void 0!==t.sheenRoughnessMap&&(i.sheenRoughnessMap=n(t.sheenRoughnessMap)),i}setTextures(t){return this.textures=t,this}}class Pc{static decodeText(t){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(t);let e="";for(let n=0,i=t.length;n<i;n++)e+=String.fromCharCode(t[n]);try{return decodeURIComponent(escape(e))}catch(t){return e}}static extractUrlBase(t){const e=t.lastIndexOf("/");return-1===e?"./":t.substr(0,e+1)}static resolveURL(t,e){return"string"!=typeof t||""===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 Dc extends xn{constructor(){super(),this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(t){return super.copy(t),this.instanceCount=t.instanceCount,this}clone(){return(new this.constructor).copy(this)}toJSON(){const t=super.toJSON(this);return t.instanceCount=this.instanceCount,t.isInstancedBufferGeometry=!0,t}}Dc.prototype.isInstancedBufferGeometry=!0;class Ic extends rc{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new ac(r.manager);s.setPath(r.path),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(t,(function(n){try{e(r.parse(JSON.parse(n)))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}parse(t){const e={},n={};function i(t,i){if(void 0!==e[i])return e[i];const r=t.interleavedBuffers[i],s=function(t,e){if(void 0!==n[e])return n[e];const i=t.arrayBuffers[e],r=new Uint32Array(i).buffer;return n[e]=r,r}(t,r.buffer),a=gt(r.type,s),o=new ta(a,r.stride);return o.uuid=r.uuid,e[i]=o,o}const r=t.isInstancedBufferGeometry?new Dc:new xn,s=t.data.index;if(void 0!==s){const t=gt(s.type,s.array);r.setIndex(new tn(t,1))}const a=t.data.attributes;for(const e in a){const n=a[e];let s;if(n.isInterleavedBufferAttribute){const e=i(t.data,n.data);s=new na(e,n.itemSize,n.offset,n.normalized)}else{const t=gt(n.type,n.array);s=new(n.isInstancedBufferAttribute?Ia:tn)(t,n.itemSize,n.normalized)}void 0!==n.name&&(s.name=n.name),void 0!==n.usage&&s.setUsage(n.usage),void 0!==n.updateRange&&(s.updateRange.offset=n.updateRange.offset,s.updateRange.count=n.updateRange.count),r.setAttribute(e,s)}const o=t.data.morphAttributes;if(o)for(const e in o){const n=o[e],s=[];for(let e=0,r=n.length;e<r;e++){const r=n[e];let a;if(r.isInterleavedBufferAttribute){const e=i(t.data,r.data);a=new na(e,r.itemSize,r.offset,r.normalized)}else{const t=gt(r.type,r.array);a=new tn(t,r.itemSize,r.normalized)}void 0!==r.name&&(a.name=r.name),s.push(a)}r.morphAttributes[e]=s}t.data.morphTargetsRelative&&(r.morphTargetsRelative=!0);const l=t.data.groups||t.data.drawcalls||t.data.offsets;if(void 0!==l)for(let t=0,e=l.length;t!==e;++t){const e=l[t];r.addGroup(e.start,e.count,e.materialIndex)}const c=t.data.boundingSphere;if(void 0!==c){const t=new Lt;void 0!==c.center&&t.fromArray(c.center),r.boundingSphere=new Zt(t,c.radius)}return t.name&&(r.name=t.name),t.userData&&(r.userData=t.userData),r}}const Nc={UVMapping:i,CubeReflectionMapping:r,CubeRefractionMapping:s,EquirectangularReflectionMapping:a,EquirectangularRefractionMapping:o,CubeUVReflectionMapping:l,CubeUVRefractionMapping:c},zc={RepeatWrapping:h,ClampToEdgeWrapping:u,MirroredRepeatWrapping:d},Bc={NearestFilter:p,NearestMipmapNearestFilter:m,NearestMipmapLinearFilter:f,LinearFilter:g,LinearMipmapNearestFilter:v,LinearMipmapLinearFilter:y};class Fc extends rc{constructor(t){super(t),"undefined"==typeof createImageBitmap&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),"undefined"==typeof fetch&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"}}setOptions(t){return this.options=t,this}load(t,e,n,i){void 0===t&&(t=""),void 0!==this.path&&(t=this.path+t),t=this.manager.resolveURL(t);const r=this,s=ec.get(t);if(void 0!==s)return r.manager.itemStart(t),setTimeout((function(){e&&e(s),r.manager.itemEnd(t)}),0),s;const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader,fetch(t,a).then((function(t){return t.blob()})).then((function(t){return createImageBitmap(t,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(n){ec.add(t,n),e&&e(n),r.manager.itemEnd(t)})).catch((function(e){i&&i(e),r.manager.itemError(t),r.manager.itemEnd(t)})),r.manager.itemStart(t)}}let Oc;Fc.prototype.isImageBitmapLoader=!0;const Uc={getContext:function(){return void 0===Oc&&(Oc=new(window.AudioContext||window.webkitAudioContext)),Oc},setContext:function(t){Oc=t}};class Hc extends rc{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new ac(this.manager);s.setResponseType("arraybuffer"),s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(t,(function(n){try{const t=n.slice(0);Uc.getContext().decodeAudioData(t,(function(t){e(t)}))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}}class Gc extends Rc{constructor(t,e,n=1){super(void 0,n);const i=(new Ze).set(t),r=(new Ze).set(e),s=new Lt(i.r,i.g,i.b),a=new Lt(r.r,r.g,r.b),o=Math.sqrt(Math.PI),l=o*Math.sqrt(.75);this.sh.coefficients[0].copy(s).add(a).multiplyScalar(o),this.sh.coefficients[1].copy(s).sub(a).multiplyScalar(l)}}Gc.prototype.isHemisphereLightProbe=!0;class kc extends Rc{constructor(t,e=1){super(void 0,e);const n=(new Ze).set(t);this.sh.coefficients[0].set(n.r,n.g,n.b).multiplyScalar(2*Math.sqrt(Math.PI))}}kc.prototype.isAmbientLightProbe=!0;const Vc=new se,Wc=new se,jc=new se;class qc{constructor(t=!0){this.autoStart=t,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Xc(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let t=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const e=Xc();t=(e-this.oldTime)/1e3,this.oldTime=e,this.elapsedTime+=t}return t}}function Xc(){return("undefined"==typeof performance?Date:performance).now()}const Jc=new Lt,Yc=new At,Zc=new Lt,Qc=new Lt;class Kc extends Ce{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(!0===this.isPlaying)return void console.warn("THREE.Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void console.warn("THREE.Audio: this Audio has no playback control.");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(!1!==this.hasPlaybackControl)return!0===this.isPlaying&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,!0===this.loop&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this;console.warn("THREE.Audio: this Audio has no playback control.")}stop(){if(!1!==this.hasPlaybackControl)return this._progress=0,this.source.stop(),this.source.onended=null,this.isPlaying=!1,this;console.warn("THREE.Audio: this Audio has no playback control.")}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let t=1,e=this.filters.length;t<e;t++)this.filters[t-1].connect(this.filters[t]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this._connected=!0,this}disconnect(){if(this.filters.length>0){this.source.disconnect(this.filters[0]);for(let t=1,e=this.filters.length;t<e;t++)this.filters[t-1].disconnect(this.filters[t]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this._connected=!1,this}getFilters(){return this.filters}setFilters(t){return t||(t=[]),!0===this._connected?(this.disconnect(),this.filters=t.slice(),this.connect()):this.filters=t.slice(),this}setDetune(t){if(this.detune=t,void 0!==this.source.detune)return!0===this.isPlaying&&this.source.detune.setTargetAtTime(this.detune,this.context.currentTime,.01),this}getDetune(){return this.detune}getFilter(){return this.getFilters()[0]}setFilter(t){return this.setFilters(t?[t]:[])}setPlaybackRate(t){if(!1!==this.hasPlaybackControl)return this.playbackRate=t,!0===this.isPlaying&&this.source.playbackRate.setTargetAtTime(this.playbackRate,this.context.currentTime,.01),this;console.warn("THREE.Audio: this Audio has no playback control.")}getPlaybackRate(){return this.playbackRate}onEnded(){this.isPlaying=!1}getLoop(){return!1===this.hasPlaybackControl?(console.warn("THREE.Audio: this Audio has no playback control."),!1):this.loop}setLoop(t){if(!1!==this.hasPlaybackControl)return this.loop=t,!0===this.isPlaying&&(this.source.loop=this.loop),this;console.warn("THREE.Audio: this Audio has no playback control.")}setLoopStart(t){return this.loopStart=t,this}setLoopEnd(t){return this.loopEnd=t,this}getVolume(){return this.gain.gain.value}setVolume(t){return this.gain.gain.setTargetAtTime(t,this.context.currentTime,.01),this}}const $c=new Lt,th=new At,eh=new Lt,nh=new Lt;class ih{constructor(t,e=2048){this.analyser=t.context.createAnalyser(),this.analyser.fftSize=e,this.data=new Uint8Array(this.analyser.frequencyBinCount),t.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let t=0;const e=this.getFrequencyData();for(let n=0;n<e.length;n++)t+=e[n];return t/e.length}}class rh{constructor(t,e,n){let i,r,s;switch(this.binding=t,this.valueSize=n,e){case"quaternion":i=this._slerp,r=this._slerpAdditive,s=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(6*n),this._workIndex=5;break;case"string":case"bool":i=this._select,r=this._select,s=this._setAdditiveIdentityOther,this.buffer=new Array(5*n);break;default:i=this._lerp,r=this._lerpAdditive,s=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(5*n)}this._mixBufferRegion=i,this._mixBufferRegionAdditive=r,this._setIdentity=s,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(t,e){const n=this.buffer,i=this.valueSize,r=t*i+i;let s=this.cumulativeWeight;if(0===s){for(let t=0;t!==i;++t)n[r+t]=n[t];s=e}else{s+=e;const t=e/s;this._mixBufferRegion(n,r,0,t,i)}this.cumulativeWeight=s}accumulateAdditive(t){const e=this.buffer,n=this.valueSize,i=n*this._addIndex;0===this.cumulativeWeightAdditive&&this._setIdentity(),this._mixBufferRegionAdditive(e,i,0,t,n),this.cumulativeWeightAdditive+=t}apply(t){const e=this.valueSize,n=this.buffer,i=t*e+e,r=this.cumulativeWeight,s=this.cumulativeWeightAdditive,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,r<1){const t=e*this._origIndex;this._mixBufferRegion(n,i,t,1-r,e)}s>0&&this._mixBufferRegionAdditive(n,i,this._addIndex*e,1,e);for(let t=e,r=e+e;t!==r;++t)if(n[t]!==n[t+e]){a.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 t=n,r=i;t!==r;++t)e[t]=e[i+t%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const t=3*this.valueSize;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){const t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let n=t;n<e;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){const t=this._origIndex*this.valueSize,e=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[e+n]=this.buffer[t+n]}_select(t,e,n,i,r){if(i>=.5)for(let i=0;i!==r;++i)t[e+i]=t[n+i]}_slerp(t,e,n,i){At.slerpFlat(t,e,t,e,t,n,i)}_slerpAdditive(t,e,n,i,r){const s=this._workIndex*r;At.multiplyQuaternionsFlat(t,s,t,e,t,n),At.slerpFlat(t,e,t,e,t,s,i)}_lerp(t,e,n,i,r){const s=1-i;for(let a=0;a!==r;++a){const r=e+a;t[r]=t[r]*s+t[n+a]*i}}_lerpAdditive(t,e,n,i,r){for(let s=0;s!==r;++s){const r=e+s;t[r]=t[r]+t[n+s]*i}}}const sh="\\[\\]\\.:\\/",ah=new RegExp("[\\[\\]\\.:\\/]","g"),oh="[^\\[\\]\\.:\\/]",lh="[^"+sh.replace("\\.","")+"]",ch=/((?:WC+[\/:])*)/.source.replace("WC",oh),hh=/(WCOD+)?/.source.replace("WCOD",lh),uh=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",oh),dh=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",oh),ph=new RegExp("^"+ch+hh+uh+dh+"$"),mh=["material","materials","bones"];class fh{constructor(t,e,n){this.path=e,this.parsedPath=n||fh.parseTrackName(e),this.node=fh.findNode(t,this.parsedPath.nodeName)||t,this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,n){return t&&t.isAnimationObjectGroup?new fh.Composite(t,e,n):new fh(t,e,n)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(ah,"")}static parseTrackName(t){const e=ph.exec(t);if(!e)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(void 0!==i&&-1!==i){const t=n.nodeName.substring(i+1);-1!==mh.indexOf(t)&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=t)}if(null===n.propertyName||0===n.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return n}static findNode(t,e){if(!e||""===e||"."===e||-1===e||e===t.name||e===t.uuid)return t;if(t.skeleton){const n=t.skeleton.getBoneByName(e);if(void 0!==n)return n}if(t.children){const n=function(t){for(let i=0;i<t.length;i++){const r=t[i];if(r.name===e||r.uuid===e)return r;const s=n(r.children);if(s)return s}return null},i=n(t.children);if(i)return i}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(t,e){t[e]=this.targetObject[this.propertyName]}_getValue_array(t,e){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)t[e++]=n[i]}_getValue_arrayElement(t,e){t[e]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(t,e){this.resolvedProperty.toArray(t,e)}_setValue_direct(t,e){this.targetObject[this.propertyName]=t[e]}_setValue_direct_setNeedsUpdate(t,e){this.targetObject[this.propertyName]=t[e],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(t,e){this.targetObject[this.propertyName]=t[e],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(t,e){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=t[e++]}_setValue_array_setNeedsUpdate(t,e){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=t[e++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(t,e){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=t[e++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(t,e){this.resolvedProperty[this.propertyIndex]=t[e]}_setValue_arrayElement_setNeedsUpdate(t,e){this.resolvedProperty[this.propertyIndex]=t[e],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(t,e){this.resolvedProperty[this.propertyIndex]=t[e],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(t,e){this.resolvedProperty.fromArray(t,e)}_setValue_fromArray_setNeedsUpdate(t,e){this.resolvedProperty.fromArray(t,e),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(t,e){this.resolvedProperty.fromArray(t,e),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(t,e){this.bind(),this.getValue(t,e)}_setValue_unbound(t,e){this.bind(),this.setValue(t,e)}bind(){let t=this.node;const e=this.parsedPath,n=e.objectName,i=e.propertyName;let r=e.propertyIndex;if(t||(t=fh.findNode(this.rootNode,e.nodeName)||this.rootNode,this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t)return void console.error("THREE.PropertyBinding: Trying to update node for track: "+this.path+" but it wasn't found.");if(n){let i=e.objectIndex;switch(n){case"materials":if(!t.material)return void console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);if(!t.material.materials)return void console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);t=t.material.materials;break;case"bones":if(!t.skeleton)return void console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);t=t.skeleton.bones;for(let e=0;e<t.length;e++)if(t[e].name===i){i=e;break}break;default:if(void 0===t[n])return void console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);t=t[n]}if(void 0!==i){if(void 0===t[i])return void console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,t);t=t[i]}}const s=t[i];if(void 0===s){const n=e.nodeName;return void console.error("THREE.PropertyBinding: Trying to update property for track: "+n+"."+i+" but it wasn't found.",t)}let a=this.Versioning.None;this.targetObject=t,void 0!==t.needsUpdate?a=this.Versioning.NeedsUpdate:void 0!==t.matrixWorldNeedsUpdate&&(a=this.Versioning.MatrixWorldNeedsUpdate);let o=this.BindingType.Direct;if(void 0!==r){if("morphTargetInfluences"===i){if(!t.geometry)return void console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);if(!t.geometry.isBufferGeometry)return void console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.",this);if(!t.geometry.morphAttributes)return void console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);void 0!==t.morphTargetDictionary[r]&&(r=t.morphTargetDictionary[r])}o=this.BindingType.ArrayElement,this.resolvedProperty=s,this.propertyIndex=r}else void 0!==s.fromArray&&void 0!==s.toArray?(o=this.BindingType.HasFromToArray,this.resolvedProperty=s):Array.isArray(s)?(o=this.BindingType.EntireArray,this.resolvedProperty=s):this.propertyName=i;this.getValue=this.GetterByBindingType[o],this.setValue=this.SetterByBindingTypeAndVersioning[o][a]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}fh.Composite=class{constructor(t,e,n){const i=n||fh.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];void 0!==i&&i.getValue(t,e)}setValue(t,e){const n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,r=n.length;i!==r;++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()}},fh.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},fh.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},fh.prototype.GetterByBindingType=[fh.prototype._getValue_direct,fh.prototype._getValue_array,fh.prototype._getValue_arrayElement,fh.prototype._getValue_toArray],fh.prototype.SetterByBindingTypeAndVersioning=[[fh.prototype._setValue_direct,fh.prototype._setValue_direct_setNeedsUpdate,fh.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[fh.prototype._setValue_array,fh.prototype._setValue_array_setNeedsUpdate,fh.prototype._setValue_array_setMatrixWorldNeedsUpdate],[fh.prototype._setValue_arrayElement,fh.prototype._setValue_arrayElement_setNeedsUpdate,fh.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[fh.prototype._setValue_fromArray,fh.prototype._setValue_fromArray_setNeedsUpdate,fh.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class gh{constructor(){this.uuid=rt(),this._objects=Array.prototype.slice.call(arguments),this.nCachedObjects_=0;const t={};this._indicesByUUID=t;for(let e=0,n=arguments.length;e!==n;++e)t[arguments[e].uuid]=e;this._paths=[],this._parsedPaths=[],this._bindings=[],this._bindingsIndicesByPath={};const e=this;this.stats={objects:{get total(){return e._objects.length},get inUse(){return this.total-e.nCachedObjects_}},get bindingsPerObject(){return e._bindings.length}}}add(){const t=this._objects,e=this._indicesByUUID,n=this._paths,i=this._parsedPaths,r=this._bindings,s=r.length;let a,o=t.length,l=this.nCachedObjects_;for(let c=0,h=arguments.length;c!==h;++c){const h=arguments[c],u=h.uuid;let d=e[u];if(void 0===d){d=o++,e[u]=d,t.push(h);for(let t=0,e=s;t!==e;++t)r[t].push(new fh(h,n[t],i[t]))}else if(d<l){a=t[d];const o=--l,c=t[o];e[c.uuid]=d,t[d]=c,e[u]=o,t[o]=h;for(let t=0,e=s;t!==e;++t){const e=r[t],s=e[o];let a=e[d];e[d]=s,void 0===a&&(a=new fh(h,n[t],i[t])),e[o]=a}}else t[d]!==a&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=l}remove(){const t=this._objects,e=this._indicesByUUID,n=this._bindings,i=n.length;let r=this.nCachedObjects_;for(let s=0,a=arguments.length;s!==a;++s){const a=arguments[s],o=a.uuid,l=e[o];if(void 0!==l&&l>=r){const s=r++,c=t[s];e[c.uuid]=l,t[l]=c,e[o]=s,t[s]=a;for(let t=0,e=i;t!==e;++t){const e=n[t],i=e[s],r=e[l];e[l]=i,e[s]=r}}}this.nCachedObjects_=r}uncache(){const t=this._objects,e=this._indicesByUUID,n=this._bindings,i=n.length;let r=this.nCachedObjects_,s=t.length;for(let a=0,o=arguments.length;a!==o;++a){const o=arguments[a].uuid,l=e[o];if(void 0!==l)if(delete e[o],l<r){const a=--r,o=t[a],c=--s,h=t[c];e[o.uuid]=l,t[l]=o,e[h.uuid]=a,t[a]=h,t.pop();for(let t=0,e=i;t!==e;++t){const e=n[t],i=e[a],r=e[c];e[l]=i,e[a]=r,e.pop()}}else{const r=--s,a=t[r];r>0&&(e[a.uuid]=l),t[l]=a,t.pop();for(let t=0,e=i;t!==e;++t){const e=n[t];e[l]=e[r],e.pop()}}}this.nCachedObjects_=r}subscribe_(t,e){const n=this._bindingsIndicesByPath;let i=n[t];const r=this._bindings;if(void 0!==i)return r[i];const s=this._paths,a=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,h=new Array(l);i=r.length,n[t]=i,s.push(t),a.push(e),r.push(h);for(let n=c,i=o.length;n!==i;++n){const i=o[n];h[n]=new fh(i,t,e)}return h}unsubscribe_(t){const e=this._bindingsIndicesByPath,n=e[t];if(void 0!==n){const i=this._paths,r=this._parsedPaths,s=this._bindings,a=s.length-1,o=s[a];e[t[a]]=n,s[n]=o,s.pop(),r[n]=r[a],r.pop(),i[n]=i[a],i.pop()}}}gh.prototype.isAnimationObjectGroup=!0;class vh{constructor(t,e,n=null,i=e.blendMode){this._mixer=t,this._clip=e,this._localRoot=n,this.blendMode=i;const r=e.tracks,s=r.length,a=new Array(s),o={endingStart:k,endingEnd:k};for(let t=0;t!==s;++t){const e=r[t].createInterpolant(null);a[t]=e,e.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(s),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,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&&0!==this.timeScale&&null===this._startTime&&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){if(t.fadeOut(e),this.fadeIn(e),n){const n=this._clip.duration,i=t._clip.duration,r=i/n,s=n/i;t.warp(1,r,e),this.warp(s,1,e)}return this}crossFadeTo(t,e,n){return t.crossFadeFrom(this,e,n)}stopFading(){const t=this._weightInterpolant;return null!==t&&(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,r=i.time,s=this.timeScale;let a=this._timeScaleInterpolant;null===a&&(a=i._lendControlInterpolant(),this._timeScaleInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=r,o[1]=r+n,l[0]=t/s,l[1]=e/s,this}stopWarping(){const t=this._timeScaleInterpolant;return null!==t&&(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)return void this._updateWeight(t);const r=this._startTime;if(null!==r){const i=(t-r)*n;if(i<0||0===n)return;this._startTime=null,e=n*i}e*=this._updateTimeScale(t);const s=this._updateTime(e),a=this._updateWeight(t);if(a>0){const t=this._interpolants,e=this._propertyBindings;if(this.blendMode===q)for(let n=0,i=t.length;n!==i;++n)t[n].evaluate(s),e[n].accumulateAdditive(a);else for(let n=0,r=t.length;n!==r;++n)t[n].evaluate(s),e[n].accumulate(i,a)}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;const n=this._weightInterpolant;if(null!==n){const i=n.evaluate(t)[0];e*=i,t>n.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;const n=this._timeScaleInterpolant;if(null!==n){e*=n.evaluate(t)[0],t>n.parameterPositions[1]&&(this.stopWarping(),0===e?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,r=this._loopCount;const s=2202===n;if(0===t)return-1===r?i:s&&1==(1&r)?e-i:i;if(2200===n){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(i>=e)i=e;else{if(!(i<0)){this.time=i;break t}i=0}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(-1===r&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,s)):this._setEndings(0===this.repetitions,!0,s)),i>=e||i<0){const n=Math.floor(i/e);i-=e*n,r+=Math.abs(n);const a=this.repetitions-r;if(a<=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(1===a){const e=t<0;this._setEndings(e,!e,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:n})}}else this.time=i;if(s&&1==(1&r))return e-i}return i}_setEndings(t,e,n){const i=this._interpolantSettings;n?(i.endingStart=V,i.endingEnd=V):(i.endingStart=t?this.zeroSlopeAtStart?V:k:W,i.endingEnd=e?this.zeroSlopeAtEnd?V:k:W)}_scheduleFading(t,e,n){const i=this._mixer,r=i.time;let s=this._weightInterpolant;null===s&&(s=i._lendControlInterpolant(),this._weightInterpolant=s);const a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=e,a[1]=r+t,o[1]=n,this}}class yh extends ${constructor(t){super(),this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(t,e){const n=t._localRoot||this._root,i=t._clip.tracks,r=i.length,s=t._propertyBindings,a=t._interpolants,o=n.uuid,l=this._bindingsByRootAndName;let c=l[o];void 0===c&&(c={},l[o]=c);for(let t=0;t!==r;++t){const r=i[t],l=r.name;let h=c[l];if(void 0!==h)s[t]=h;else{if(h=s[t],void 0!==h){null===h._cacheIndex&&(++h.referenceCount,this._addInactiveBinding(h,o,l));continue}const i=e&&e._propertyBindings[t].binding.parsedPath;h=new rh(fh.create(n,l,i),r.ValueTypeName,r.getValueSize()),++h.referenceCount,this._addInactiveBinding(h,o,l),s[t]=h}a[t].resultBuffer=h.buffer}}_activateAction(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){const e=(t._localRoot||this._root).uuid,n=t._clip.uuid,i=this._actionsByClip[n];this._bindAction(t,i&&i.knownActions[0]),this._addInactiveAction(t,n,e)}const e=t._propertyBindings;for(let t=0,n=e.length;t!==n;++t){const n=e[t];0==n.useCount++&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(t)}}_deactivateAction(t){if(this._isActiveAction(t)){const e=t._propertyBindings;for(let t=0,n=e.length;t!==n;++t){const n=e[t];0==--n.useCount&&(n.restoreOriginalState(),this._takeBackBinding(n))}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 null!==e&&e<this._nActiveActions}_addInactiveAction(t,e,n){const i=this._actions,r=this._actionsByClip;let s=r[e];if(void 0===s)s={knownActions:[t],actionByRoot:{}},t._byClipCacheIndex=0,r[e]=s;else{const e=s.knownActions;t._byClipCacheIndex=e.length,e.push(t)}t._cacheIndex=i.length,i.push(t),s.actionByRoot[n]=t}_removeInactiveAction(t){const e=this._actions,n=e[e.length-1],i=t._cacheIndex;n._cacheIndex=i,e[i]=n,e.pop(),t._cacheIndex=null;const r=t._clip.uuid,s=this._actionsByClip,a=s[r],o=a.knownActions,l=o[o.length-1],c=t._byClipCacheIndex;l._byClipCacheIndex=c,o[c]=l,o.pop(),t._byClipCacheIndex=null;delete a.actionByRoot[(t._localRoot||this._root).uuid],0===o.length&&delete s[r],this._removeInactiveBindingsForAction(t)}_removeInactiveBindingsForAction(t){const e=t._propertyBindings;for(let t=0,n=e.length;t!==n;++t){const n=e[t];0==--n.referenceCount&&this._removeInactiveBinding(n)}}_lendAction(t){const e=this._actions,n=t._cacheIndex,i=this._nActiveActions++,r=e[i];t._cacheIndex=i,e[i]=t,r._cacheIndex=n,e[n]=r}_takeBackAction(t){const e=this._actions,n=t._cacheIndex,i=--this._nActiveActions,r=e[i];t._cacheIndex=i,e[i]=t,r._cacheIndex=n,e[n]=r}_addInactiveBinding(t,e,n){const i=this._bindingsByRootAndName,r=this._bindings;let s=i[e];void 0===s&&(s={},i[e]=s),s[n]=t,t._cacheIndex=r.length,r.push(t)}_removeInactiveBinding(t){const e=this._bindings,n=t.binding,i=n.rootNode.uuid,r=n.path,s=this._bindingsByRootAndName,a=s[i],o=e[e.length-1],l=t._cacheIndex;o._cacheIndex=l,e[l]=o,e.pop(),delete a[r],0===Object.keys(a).length&&delete s[i]}_lendBinding(t){const e=this._bindings,n=t._cacheIndex,i=this._nActiveBindings++,r=e[i];t._cacheIndex=i,e[i]=t,r._cacheIndex=n,e[n]=r}_takeBackBinding(t){const e=this._bindings,n=t._cacheIndex,i=--this._nActiveBindings,r=e[i];t._cacheIndex=i,e[i]=t,r._cacheIndex=n,e[n]=r}_lendControlInterpolant(){const t=this._controlInterpolants,e=this._nActiveControlInterpolants++;let n=t[e];return void 0===n&&(n=new Vl(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer),n.__cacheIndex=e,t[e]=n),n}_takeBackControlInterpolant(t){const e=this._controlInterpolants,n=t.__cacheIndex,i=--this._nActiveControlInterpolants,r=e[i];t.__cacheIndex=i,e[i]=t,r.__cacheIndex=n,e[n]=r}clipAction(t,e,n){const i=e||this._root,r=i.uuid;let s="string"==typeof t?$l.findByName(i,t):t;const a=null!==s?s.uuid:t,o=this._actionsByClip[a];let l=null;if(void 0===n&&(n=null!==s?s.blendMode:j),void 0!==o){const t=o.actionByRoot[r];if(void 0!==t&&t.blendMode===n)return t;l=o.knownActions[0],null===s&&(s=l._clip)}if(null===s)return null;const c=new vh(this,s,e,n);return this._bindAction(c,l),this._addInactiveAction(c,a,r),c}existingAction(t,e){const n=e||this._root,i=n.uuid,r="string"==typeof t?$l.findByName(n,t):t,s=r?r.uuid:t,a=this._actionsByClip[s];return void 0!==a&&a.actionByRoot[i]||null}stopAllAction(){const t=this._actions;for(let e=this._nActiveActions-1;e>=0;--e)t[e].stop();return this}update(t){t*=this.timeScale;const e=this._actions,n=this._nActiveActions,i=this.time+=t,r=Math.sign(t),s=this._accuIndex^=1;for(let a=0;a!==n;++a){e[a]._update(i,t,r,s)}const a=this._bindings,o=this._nActiveBindings;for(let t=0;t!==o;++t)a[t].apply(s);return this}setTime(t){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(t)}getRoot(){return this._root}uncacheClip(t){const e=this._actions,n=t.uuid,i=this._actionsByClip,r=i[n];if(void 0!==r){const t=r.knownActions;for(let n=0,i=t.length;n!==i;++n){const i=t[n];this._deactivateAction(i);const r=i._cacheIndex,s=e[e.length-1];i._cacheIndex=null,i._byClipCacheIndex=null,s._cacheIndex=r,e[r]=s,e.pop(),this._removeInactiveBindingsForAction(i)}delete i[n]}}uncacheRoot(t){const e=t.uuid,n=this._actionsByClip;for(const t in n){const i=n[t].actionByRoot[e];void 0!==i&&(this._deactivateAction(i),this._removeInactiveAction(i))}const i=this._bindingsByRootAndName[e];if(void 0!==i)for(const t in i){const e=i[t];e.restoreOriginalState(),this._removeInactiveBinding(e)}}uncacheAction(t,e){const n=this.existingAction(t,e);null!==n&&(this._deactivateAction(n),this._removeInactiveAction(n))}}yh.prototype._controlInterpolantsResultBuffer=new Float32Array(1);class xh{constructor(t){"string"==typeof t&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),t=arguments[1]),this.value=t}clone(){return new xh(void 0===this.value.clone?this.value:this.value.clone())}}class _h extends ta{constructor(t,e,n=1){super(t,e),this.meshPerAttribute=n}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}clone(t){const e=super.clone(t);return e.meshPerAttribute=this.meshPerAttribute,e}toJSON(t){const e=super.toJSON(t);return e.isInstancedInterleavedBuffer=!0,e.meshPerAttribute=this.meshPerAttribute,e}}_h.prototype.isInstancedInterleavedBuffer=!0;class bh{constructor(t,e,n,i,r){this.buffer=t,this.type=e,this.itemSize=n,this.elementSize=i,this.count=r,this.version=0}set needsUpdate(t){!0===t&&this.version++}setBuffer(t){return this.buffer=t,this}setType(t,e){return this.type=t,this.elementSize=e,this}setItemSize(t){return this.itemSize=t,this}setCount(t){return this.count=t,this}}bh.prototype.isGLBufferAttribute=!0;function Mh(t,e){return t.distance-e.distance}function wh(t,e,n,i){if(t.layers.test(e.layers)&&t.raycast(e,n),!0===i){const i=t.children;for(let t=0,r=i.length;t<r;t++)wh(i[t],e,n,!0)}}const Sh=new dt;class Th{constructor(t=new dt(1/0,1/0),e=new dt(-1/0,-1/0)){this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromPoints(t){this.makeEmpty();for(let e=0,n=t.length;e<n;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const n=Sh.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(n),this.max.copy(t).add(n),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y}getCenter(t){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}containsPoint(t){return!(t.x<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 Sh.copy(t).clamp(this.min,this.max).sub(t).length()}intersect(t){return this.min.max(t.min),this.max.min(t.max),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)}}Th.prototype.isBox2=!0;const Eh=new Lt,Ah=new Lt;class Lh{constructor(t=new Lt,e=new Lt){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){Eh.subVectors(t,this.start),Ah.subVectors(this.end,this.start);const n=Ah.dot(Ah);let i=Ah.dot(Eh)/n;return e&&(i=st(i,0,1)),i}closestPointToPoint(t,e,n){const i=this.closestPointToPointParameter(t,e);return this.delta(n).multiplyScalar(i).add(this.start)}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 Rh=new Lt;const Ch=new Lt,Ph=new se,Dh=new se;class Ih extends Ja{constructor(t){const e=Nh(t),n=new xn,i=[],r=[],s=new Ze(0,0,1),a=new Ze(0,1,0);for(let t=0;t<e.length;t++){const n=e[t];n.parent&&n.parent.isBone&&(i.push(0,0,0),i.push(0,0,0),r.push(s.r,s.g,s.b),r.push(a.r,a.g,a.b))}n.setAttribute("position",new hn(i,3)),n.setAttribute("color",new hn(r,3));super(n,new Ua({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0})),this.type="SkeletonHelper",this.isSkeletonHelper=!0,this.root=t,this.bones=e,this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1}updateMatrixWorld(t){const e=this.bones,n=this.geometry,i=n.getAttribute("position");Dh.copy(this.root.matrixWorld).invert();for(let t=0,n=0;t<e.length;t++){const r=e[t];r.parent&&r.parent.isBone&&(Ph.multiplyMatrices(Dh,r.matrixWorld),Ch.setFromMatrixPosition(Ph),i.setXYZ(n,Ch.x,Ch.y,Ch.z),Ph.multiplyMatrices(Dh,r.parent.matrixWorld),Ch.setFromMatrixPosition(Ph),i.setXYZ(n+1,Ch.x,Ch.y,Ch.z),n+=2)}n.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(t)}}function Nh(t){const e=[];t&&t.isBone&&e.push(t);for(let n=0;n<t.children.length;n++)e.push.apply(e,Nh(t.children[n]));return e}const zh=new Lt,Bh=new Ze,Fh=new Ze;class Oh extends Ja{constructor(t=10,e=10,n=4473924,i=8947848){n=new Ze(n),i=new Ze(i);const r=e/2,s=t/e,a=t/2,o=[],l=[];for(let t=0,c=0,h=-a;t<=e;t++,h+=s){o.push(-a,0,h,a,0,h),o.push(h,0,-a,h,0,a);const e=t===r?n:i;e.toArray(l,c),c+=3,e.toArray(l,c),c+=3,e.toArray(l,c),c+=3,e.toArray(l,c),c+=3}const c=new xn;c.setAttribute("position",new hn(o,3)),c.setAttribute("color",new hn(l,3));super(c,new Ua({vertexColors:!0,toneMapped:!1})),this.type="GridHelper"}}const Uh=new Lt,Hh=new Lt,Gh=new Lt;const kh=new Lt,Vh=new Wn;function Wh(t,e,n,i,r,s,a){kh.set(r,s,a).unproject(i);const o=e[t];if(void 0!==o){const t=n.getAttribute("position");for(let e=0,n=o.length;e<n;e++)t.setXYZ(o[e],kh.x,kh.y,kh.z)}}const jh=new Pt;class qh extends Ja{constructor(t,e=16776960){const n=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]),i=new Float32Array(24),r=new xn;r.setIndex(new tn(n,1)),r.setAttribute("position",new tn(i,3)),super(r,new Ua({color:e,toneMapped:!1})),this.object=t,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(t){if(void 0!==t&&console.warn("THREE.BoxHelper: .update() has no longer arguments."),void 0!==this.object&&jh.setFromObject(this.object),jh.isEmpty())return;const e=jh.min,n=jh.max,i=this.geometry.attributes.position,r=i.array;r[0]=n.x,r[1]=n.y,r[2]=n.z,r[3]=e.x,r[4]=n.y,r[5]=n.z,r[6]=e.x,r[7]=e.y,r[8]=n.z,r[9]=n.x,r[10]=e.y,r[11]=n.z,r[12]=n.x,r[13]=n.y,r[14]=e.z,r[15]=e.x,r[16]=n.y,r[17]=e.z,r[18]=e.x,r[19]=e.y,r[20]=e.z,r[21]=n.x,r[22]=e.y,r[23]=e.z,i.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(t){return this.object=t,this.update(),this}copy(t){return Ja.prototype.copy.call(this,t),this.object=t.object,this}}const Xh=new Lt;let Jh,Yh;class Zh extends Ja{constructor(t=1){const e=[0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t],n=new xn;n.setAttribute("position",new hn(e,3)),n.setAttribute("color",new hn([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(n,new Ua({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(t,e,n){const i=new Ze,r=this.geometry.attributes.color.array;return i.set(t),i.toArray(r,0),i.toArray(r,3),i.set(e),i.toArray(r,6),i.toArray(r,9),i.set(n),i.toArray(r,12),i.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}const Qh=new Float32Array(1),Kh=new Int32Array(Qh.buffer);yo.create=function(t,e){return console.log("THREE.Curve.create() has been deprecated"),t.prototype=Object.create(yo.prototype),t.prototype.constructor=t,t.prototype.getPoint=e,t},Uo.prototype.fromPoints=function(t){return console.warn("THREE.Path: .fromPoints() has been renamed to .setFromPoints()."),this.setFromPoints(t)},Oh.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")},Ih.prototype.update=function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.")},rc.prototype.extractUrlBase=function(t){return console.warn("THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead."),Pc.extractUrlBase(t)},rc.Handlers={add:function(){console.error("THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.")},get:function(){console.error("THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.")}},Th.prototype.center=function(t){return console.warn("THREE.Box2: .center() has been renamed to .getCenter()."),this.getCenter(t)},Th.prototype.empty=function(){return console.warn("THREE.Box2: .empty() has been renamed to .isEmpty()."),this.isEmpty()},Th.prototype.isIntersectionBox=function(t){return console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox()."),this.intersectsBox(t)},Th.prototype.size=function(t){return console.warn("THREE.Box2: .size() has been renamed to .getSize()."),this.getSize(t)},Pt.prototype.center=function(t){return console.warn("THREE.Box3: .center() has been renamed to .getCenter()."),this.getCenter(t)},Pt.prototype.empty=function(){return console.warn("THREE.Box3: .empty() has been renamed to .isEmpty()."),this.isEmpty()},Pt.prototype.isIntersectionBox=function(t){return console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox()."),this.intersectsBox(t)},Pt.prototype.isIntersectionSphere=function(t){return console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere()."),this.intersectsSphere(t)},Pt.prototype.size=function(t){return console.warn("THREE.Box3: .size() has been renamed to .getSize()."),this.getSize(t)},Zt.prototype.empty=function(){return console.warn("THREE.Sphere: .empty() has been renamed to .isEmpty()."),this.isEmpty()},ni.prototype.setFromMatrix=function(t){return console.warn("THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix()."),this.setFromProjectionMatrix(t)},Lh.prototype.center=function(t){return console.warn("THREE.Line3: .center() has been renamed to .getCenter()."),this.getCenter(t)},pt.prototype.flattenToArrayOffset=function(t,e){return console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead."),this.toArray(t,e)},pt.prototype.multiplyVector3=function(t){return console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead."),t.applyMatrix3(this)},pt.prototype.multiplyVector3Array=function(){console.error("THREE.Matrix3: .multiplyVector3Array() has been removed.")},pt.prototype.applyToBufferAttribute=function(t){return console.warn("THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead."),t.applyMatrix3(this)},pt.prototype.applyToVector3Array=function(){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")},pt.prototype.getInverse=function(t){return console.warn("THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead."),this.copy(t).invert()},se.prototype.extractPosition=function(t){return console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(t)},se.prototype.flattenToArrayOffset=function(t,e){return console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead."),this.toArray(t,e)},se.prototype.getPosition=function(){return console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead."),(new Lt).setFromMatrixColumn(this,3)},se.prototype.setRotationFromQuaternion=function(t){return console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion()."),this.makeRotationFromQuaternion(t)},se.prototype.multiplyToArray=function(){console.warn("THREE.Matrix4: .multiplyToArray() has been removed.")},se.prototype.multiplyVector3=function(t){return console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead."),t.applyMatrix4(this)},se.prototype.multiplyVector4=function(t){return console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead."),t.applyMatrix4(this)},se.prototype.multiplyVector3Array=function(){console.error("THREE.Matrix4: .multiplyVector3Array() has been removed.")},se.prototype.rotateAxis=function(t){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead."),t.transformDirection(this)},se.prototype.crossVector=function(t){return console.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead."),t.applyMatrix4(this)},se.prototype.translate=function(){console.error("THREE.Matrix4: .translate() has been removed.")},se.prototype.rotateX=function(){console.error("THREE.Matrix4: .rotateX() has been removed.")},se.prototype.rotateY=function(){console.error("THREE.Matrix4: .rotateY() has been removed.")},se.prototype.rotateZ=function(){console.error("THREE.Matrix4: .rotateZ() has been removed.")},se.prototype.rotateByAxis=function(){console.error("THREE.Matrix4: .rotateByAxis() has been removed.")},se.prototype.applyToBufferAttribute=function(t){return console.warn("THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead."),t.applyMatrix4(this)},se.prototype.applyToVector3Array=function(){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.")},se.prototype.makeFrustum=function(t,e,n,i,r,s){return console.warn("THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead."),this.makePerspective(t,e,i,n,r,s)},se.prototype.getInverse=function(t){return console.warn("THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead."),this.copy(t).invert()},$n.prototype.isIntersectionLine=function(t){return console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine()."),this.intersectsLine(t)},At.prototype.multiplyVector3=function(t){return console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead."),t.applyQuaternion(this)},At.prototype.inverse=function(){return console.warn("THREE.Quaternion: .inverse() has been renamed to invert()."),this.invert()},re.prototype.isIntersectionBox=function(t){return console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox()."),this.intersectsBox(t)},re.prototype.isIntersectionPlane=function(t){return console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane()."),this.intersectsPlane(t)},re.prototype.isIntersectionSphere=function(t){return console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere()."),this.intersectsSphere(t)},Ge.prototype.area=function(){return console.warn("THREE.Triangle: .area() has been renamed to .getArea()."),this.getArea()},Ge.prototype.barycoordFromPoint=function(t,e){return console.warn("THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord()."),this.getBarycoord(t,e)},Ge.prototype.midpoint=function(t){return console.warn("THREE.Triangle: .midpoint() has been renamed to .getMidpoint()."),this.getMidpoint(t)},Ge.prototypenormal=function(t){return console.warn("THREE.Triangle: .normal() has been renamed to .getNormal()."),this.getNormal(t)},Ge.prototype.plane=function(t){return console.warn("THREE.Triangle: .plane() has been renamed to .getPlane()."),this.getPlane(t)},Ge.barycoordFromPoint=function(t,e,n,i,r){return console.warn("THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord()."),Ge.getBarycoord(t,e,n,i,r)},Ge.normal=function(t,e,n,i){return console.warn("THREE.Triangle: .normal() has been renamed to .getNormal()."),Ge.getNormal(t,e,n,i)},Ho.prototype.extractAllPoints=function(t){return console.warn("THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead."),this.extractPoints(t)},Ho.prototype.extrude=function(t){return console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead."),new fl(this,t)},Ho.prototype.makeGeometry=function(t){return console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead."),new bl(this,t)},dt.prototype.fromAttribute=function(t,e,n){return console.warn("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute()."),this.fromBufferAttribute(t,e,n)},dt.prototype.distanceToManhattan=function(t){return console.warn("THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo()."),this.manhattanDistanceTo(t)},dt.prototype.lengthManhattan=function(){return console.warn("THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength()."),this.manhattanLength()},Lt.prototype.setEulerFromRotationMatrix=function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},Lt.prototype.setEulerFromQuaternion=function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")},Lt.prototype.getPositionFromMatrix=function(t){return console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition()."),this.setFromMatrixPosition(t)},Lt.prototype.getScaleFromMatrix=function(t){return console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale()."),this.setFromMatrixScale(t)},Lt.prototype.getColumnFromMatrix=function(t,e){return console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn()."),this.setFromMatrixColumn(e,t)},Lt.prototype.applyProjection=function(t){return console.warn("THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead."),this.applyMatrix4(t)},Lt.prototype.fromAttribute=function(t,e,n){return console.warn("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute()."),this.fromBufferAttribute(t,e,n)},Lt.prototype.distanceToManhattan=function(t){return console.warn("THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo()."),this.manhattanDistanceTo(t)},Lt.prototype.lengthManhattan=function(){return console.warn("THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength()."),this.manhattanLength()},wt.prototype.fromAttribute=function(t,e,n){return console.warn("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute()."),this.fromBufferAttribute(t,e,n)},wt.prototype.lengthManhattan=function(){return console.warn("THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength()."),this.manhattanLength()},Ce.prototype.getChildByName=function(t){return console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName()."),this.getObjectByName(t)},Ce.prototype.renderDepth=function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},Ce.prototype.translate=function(t,e){return console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead."),this.translateOnAxis(e,t)},Ce.prototype.getWorldRotation=function(){console.error("THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.")},Ce.prototype.applyMatrix=function(t){return console.warn("THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4()."),this.applyMatrix4(t)},Object.defineProperties(Ce.prototype,{eulerOrder:{get:function(){return console.warn("THREE.Object3D: .eulerOrder is now .rotation.order."),this.rotation.order},set:function(t){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order."),this.rotation.order=t}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}}),Fn.prototype.setDrawMode=function(){console.error("THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.")},Object.defineProperties(Fn.prototype,{drawMode:{get:function(){return console.error("THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode."),0},set:function(){console.error("THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.")}}}),Aa.prototype.initBones=function(){console.error("THREE.SkinnedMesh: initBones() has been removed.")},jn.prototype.setLens=function(t,e){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup."),void 0!==e&&(this.filmGauge=e),this.setFocalLength(t)},Object.defineProperties(uc.prototype,{onlyShadow:{set:function(){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(t){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov."),this.shadow.camera.fov=t}},shadowCameraLeft:{set:function(t){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left."),this.shadow.camera.left=t}},shadowCameraRight:{set:function(t){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right."),this.shadow.camera.right=t}},shadowCameraTop:{set:function(t){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top."),this.shadow.camera.top=t}},shadowCameraBottom:{set:function(t){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom."),this.shadow.camera.bottom=t}},shadowCameraNear:{set:function(t){console.warn("THREE.Light: .shadowCameraNear is now .shadow.camera.near."),this.shadow.camera.near=t}},shadowCameraFar:{set:function(t){console.warn("THREE.Light: .shadowCameraFar is now .shadow.camera.far."),this.shadow.camera.far=t}},shadowCameraVisible:{set:function(){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.")}},shadowBias:{set:function(t){console.warn("THREE.Light: .shadowBias is now .shadow.bias."),this.shadow.bias=t}},shadowDarkness:{set:function(){console.warn("THREE.Light: .shadowDarkness has been removed.")}},shadowMapWidth:{set:function(t){console.warn("THREE.Light: .shadowMapWidth is now .shadow.mapSize.width."),this.shadow.mapSize.width=t}},shadowMapHeight:{set:function(t){console.warn("THREE.Light: .shadowMapHeight is now .shadow.mapSize.height."),this.shadow.mapSize.height=t}}}),Object.defineProperties(tn.prototype,{length:{get:function(){return console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead."),this.array.length}},dynamic:{get:function(){return console.warn("THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead."),this.usage===Q},set:function(){console.warn("THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead."),this.setUsage(Q)}}}),tn.prototype.setDynamic=function(t){return console.warn("THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead."),this.setUsage(!0===t?Q:Z),this},tn.prototype.copyIndicesArray=function(){console.error("THREE.BufferAttribute: .copyIndicesArray() has been removed.")},tn.prototype.setArray=function(){console.error("THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers")},xn.prototype.addIndex=function(t){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex()."),this.setIndex(t)},xn.prototype.addAttribute=function(t,e){return console.warn("THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute()."),e&&e.isBufferAttribute||e&&e.isInterleavedBufferAttribute?"index"===t?(console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),this.setIndex(e),this):this.setAttribute(t,e):(console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),this.setAttribute(t,new tn(arguments[1],arguments[2])))},xn.prototype.addDrawCall=function(t,e,n){void 0!==n&&console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset."),console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup()."),this.addGroup(t,e)},xn.prototype.clearDrawCalls=function(){console.warn("THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups()."),this.clearGroups()},xn.prototype.computeOffsets=function(){console.warn("THREE.BufferGeometry: .computeOffsets() has been removed.")},xn.prototype.removeAttribute=function(t){return console.warn("THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute()."),this.deleteAttribute(t)},xn.prototype.applyMatrix=function(t){return console.warn("THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4()."),this.applyMatrix4(t)},Object.defineProperties(xn.prototype,{drawcalls:{get:function(){return console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups."),this.groups}},offsets:{get:function(){return console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups."),this.groups}}}),ta.prototype.setDynamic=function(t){return console.warn("THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead."),this.setUsage(!0===t?Q:Z),this},ta.prototype.setArray=function(){console.error("THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers")},fl.prototype.getArrays=function(){console.error("THREE.ExtrudeGeometry: .getArrays() has been removed.")},fl.prototype.addShapeList=function(){console.error("THREE.ExtrudeGeometry: .addShapeList() has been removed.")},fl.prototype.addShape=function(){console.error("THREE.ExtrudeGeometry: .addShape() has been removed.")},$s.prototype.dispose=function(){console.error("THREE.Scene: .dispose() has been removed.")},xh.prototype.onUpdate=function(){return console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead."),this},Object.defineProperties(Ve.prototype,{wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.")},set:function(){console.warn("THREE.Material: .wrapAround has been removed.")}},overdraw:{get:function(){console.warn("THREE.Material: .overdraw has been removed.")},set:function(){console.warn("THREE.Material: .overdraw has been removed.")}},wrapRGB:{get:function(){return console.warn("THREE.Material: .wrapRGB has been removed."),new Ze}},shading:{get:function(){console.error("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.")},set:function(t){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===t}},stencilMask:{get:function(){return console.warn("THREE."+this.type+": .stencilMask has been removed. Use .stencilFuncMask instead."),this.stencilFuncMask},set:function(t){console.warn("THREE."+this.type+": .stencilMask has been removed. Use .stencilFuncMask instead."),this.stencilFuncMask=t}},vertexTangents:{get:function(){console.warn("THREE."+this.type+": .vertexTangents has been removed.")},set:function(){console.warn("THREE."+this.type+": .vertexTangents has been removed.")}}}),Object.defineProperties(Vn.prototype,{derivatives:{get:function(){return console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives."),this.extensions.derivatives},set:function(t){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives."),this.extensions.derivatives=t}}}),Ys.prototype.clearTarget=function(t,e,n,i){console.warn("THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead."),this.setRenderTarget(t),this.clear(e,n,i)},Ys.prototype.animate=function(t){console.warn("THREE.WebGLRenderer: .animate() is now .setAnimationLoop()."),this.setAnimationLoop(t)},Ys.prototype.getCurrentRenderTarget=function(){return console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget()."),this.getRenderTarget()},Ys.prototype.getMaxAnisotropy=function(){return console.warn("THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy()."),this.capabilities.getMaxAnisotropy()},Ys.prototype.getPrecision=function(){return console.warn("THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision."),this.capabilities.precision},Ys.prototype.resetGLState=function(){return console.warn("THREE.WebGLRenderer: .resetGLState() is now .state.reset()."),this.state.reset()},Ys.prototype.supportsFloatTextures=function(){return console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' )."),this.extensions.get("OES_texture_float")},Ys.prototype.supportsHalfFloatTextures=function(){return console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' )."),this.extensions.get("OES_texture_half_float")},Ys.prototype.supportsStandardDerivatives=function(){return console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' )."),this.extensions.get("OES_standard_derivatives")},Ys.prototype.supportsCompressedTextureS3TC=function(){return console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' )."),this.extensions.get("WEBGL_compressed_texture_s3tc")},Ys.prototype.supportsCompressedTexturePVRTC=function(){return console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' )."),this.extensions.get("WEBGL_compressed_texture_pvrtc")},Ys.prototype.supportsBlendMinMax=function(){return console.warn("THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( 'EXT_blend_minmax' )."),this.extensions.get("EXT_blend_minmax")},Ys.prototype.supportsVertexTextures=function(){return console.warn("THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures."),this.capabilities.vertexTextures},Ys.prototype.supportsInstancedArrays=function(){return console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' )."),this.extensions.get("ANGLE_instanced_arrays")},Ys.prototype.enableScissorTest=function(t){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest()."),this.setScissorTest(t)},Ys.prototype.initMaterial=function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},Ys.prototype.addPrePlugin=function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")},Ys.prototype.addPostPlugin=function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},Ys.prototype.updateShadowMap=function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")},Ys.prototype.setFaceCulling=function(){console.warn("THREE.WebGLRenderer: .setFaceCulling() has been removed.")},Ys.prototype.allocTextureUnit=function(){console.warn("THREE.WebGLRenderer: .allocTextureUnit() has been removed.")},Ys.prototype.setTexture=function(){console.warn("THREE.WebGLRenderer: .setTexture() has been removed.")},Ys.prototype.setTexture2D=function(){console.warn("THREE.WebGLRenderer: .setTexture2D() has been removed.")},Ys.prototype.setTextureCube=function(){console.warn("THREE.WebGLRenderer: .setTextureCube() has been removed.")},Ys.prototype.getActiveMipMapLevel=function(){return console.warn("THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel()."),this.getActiveMipmapLevel()},Object.defineProperties(Ys.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(t){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled."),this.shadowMap.enabled=t}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(t){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type."),this.shadowMap.type=t}},shadowMapCullFace:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.")}},context:{get:function(){return console.warn("THREE.WebGLRenderer: .context has been removed. Use .getContext() instead."),this.getContext()}},vr:{get:function(){return console.warn("THREE.WebGLRenderer: .vr has been renamed to .xr"),this.xr}},gammaInput:{get:function(){return console.warn("THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead."),!1},set:function(){console.warn("THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.")}},gammaOutput:{get:function(){return console.warn("THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead."),!1},set:function(t){console.warn("THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead."),this.outputEncoding=!0===t?J:X}},toneMappingWhitePoint:{get:function(){return console.warn("THREE.WebGLRenderer: .toneMappingWhitePoint has been removed."),1},set:function(){console.warn("THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.")}},gammaFactor:{get:function(){return console.warn("THREE.WebGLRenderer: .gammaFactor has been removed."),2},set:function(){console.warn("THREE.WebGLRenderer: .gammaFactor has been removed.")}}}),Object.defineProperties(Os.prototype,{cullFace:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.")}},renderReverseSided:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.")}},renderSingleSided:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.")}}}),Object.defineProperties(St.prototype,{wrapS:{get:function(){return console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS."),this.texture.wrapS},set:function(t){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS."),this.texture.wrapS=t}},wrapT:{get:function(){return console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT."),this.texture.wrapT},set:function(t){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT."),this.texture.wrapT=t}},magFilter:{get:function(){return console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter."),this.texture.magFilter},set:function(t){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter."),this.texture.magFilter=t}},minFilter:{get:function(){return console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter."),this.texture.minFilter},set:function(t){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter."),this.texture.minFilter=t}},anisotropy:{get:function(){return console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy."),this.texture.anisotropy},set:function(t){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy."),this.texture.anisotropy=t}},offset:{get:function(){return console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset."),this.texture.offset},set:function(t){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset."),this.texture.offset=t}},repeat:{get:function(){return console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat."),this.texture.repeat},set:function(t){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat."),this.texture.repeat=t}},format:{get:function(){return console.warn("THREE.WebGLRenderTarget: .format is now .texture.format."),this.texture.format},set:function(t){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format."),this.texture.format=t}},type:{get:function(){return console.warn("THREE.WebGLRenderTarget: .type is now .texture.type."),this.texture.type},set:function(t){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type."),this.texture.type=t}},generateMipmaps:{get:function(){return console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps."),this.texture.generateMipmaps},set:function(t){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps."),this.texture.generateMipmaps=t}}}),Kc.prototype.load=function(t){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");const e=this;return(new Hc).load(t,(function(t){e.setBuffer(t)})),this},ih.prototype.getData=function(){return console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData()."),this.getFrequencyData()},Xn.prototype.updateCubeMap=function(t,e){return console.warn("THREE.CubeCamera: .updateCubeMap() is now .update()."),this.update(t,e)},Xn.prototype.clear=function(t,e,n,i){return console.warn("THREE.CubeCamera: .clear() is now .renderTarget.clear()."),this.renderTarget.clear(t,e,n,i)},xt.crossOrigin=void 0,xt.loadTexture=function(t,e,n,i){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");const r=new hc;r.setCrossOrigin(this.crossOrigin);const s=r.load(t,n,void 0,i);return e&&(s.mapping=e),s},xt.loadTextureCube=function(t,e,n,i){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");const r=new lc;r.setCrossOrigin(this.crossOrigin);const s=r.load(t,n,void 0,i);return e&&(s.mapping=e),s},xt.loadCompressedTexture=function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")},xt.loadCompressedTextureCube=function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")};const $h={createMultiMaterialObject:function(){console.error("THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js")},detach:function(){console.error("THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js")},attach:function(){console.error("THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js")}};"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:e}})),"undefined"!=typeof window&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=e),t.ACESFilmicToneMapping=4,t.AddEquation=n,t.AddOperation=2,t.AdditiveAnimationBlendMode=q,t.AdditiveBlending=2,t.AlphaFormat=1021,t.AlwaysDepth=1,t.AlwaysStencilFunc=519,t.AmbientLight=Ec,t.AmbientLightProbe=kc,t.AnimationClip=$l,t.AnimationLoader=class extends rc{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new ac(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(t,(function(n){try{e(r.parse(JSON.parse(n)))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}parse(t){const e=[];for(let n=0;n<t.length;n++){const i=$l.parse(t[n]);e.push(i)}return e}},t.AnimationMixer=yh,t.AnimationObjectGroup=gh,t.AnimationUtils=Hl,t.ArcCurve=_o,t.ArrayCamera=ks,t.ArrowHelper=class extends Ce{constructor(t=new Lt(0,0,1),e=new Lt(0,0,0),n=1,i=16776960,r=.2*n,s=.2*r){super(),this.type="ArrowHelper",void 0===Jh&&(Jh=new xn,Jh.setAttribute("position",new hn([0,0,0,0,1,0],3)),Yh=new lo(0,.5,1,5,1),Yh.translate(0,-.5,0)),this.position.copy(e),this.line=new ja(Jh,new Ua({color:i,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new Fn(Yh,new Qe({color:i,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(t),this.setLength(n,r,s)}setDirection(t){if(t.y>.99999)this.quaternion.set(0,0,0,1);else if(t.y<-.99999)this.quaternion.set(1,0,0,0);else{Xh.set(t.z,0,-t.x).normalize();const e=Math.acos(t.y);this.quaternion.setFromAxisAngle(Xh,e)}}setLength(t,e=.2*t,n=.2*e){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}},t.Audio=Kc,t.AudioAnalyser=ih,t.AudioContext=Uc,t.AudioListener=class extends Ce{constructor(){super(),this.type="AudioListener",this.context=Uc.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new qc}getInput(){return this.gain}removeFilter(){return null!==this.filter&&(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 null!==this.filter?(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);const e=this.context.listener,n=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Jc,Yc,Zc),Qc.set(0,0,-1).applyQuaternion(Yc),e.positionX){const t=this.context.currentTime+this.timeDelta;e.positionX.linearRampToValueAtTime(Jc.x,t),e.positionY.linearRampToValueAtTime(Jc.y,t),e.positionZ.linearRampToValueAtTime(Jc.z,t),e.forwardX.linearRampToValueAtTime(Qc.x,t),e.forwardY.linearRampToValueAtTime(Qc.y,t),e.forwardZ.linearRampToValueAtTime(Qc.z,t),e.upX.linearRampToValueAtTime(n.x,t),e.upY.linearRampToValueAtTime(n.y,t),e.upZ.linearRampToValueAtTime(n.z,t)}else e.setPosition(Jc.x,Jc.y,Jc.z),e.setOrientation(Qc.x,Qc.y,Qc.z,n.x,n.y,n.z)}},t.AudioLoader=Hc,t.AxesHelper=Zh,t.AxisHelper=function(t){return console.warn("THREE.AxisHelper has been renamed to THREE.AxesHelper."),new Zh(t)},t.BackSide=1,t.BasicDepthPacking=3200,t.BasicShadowMap=0,t.BinaryTextureLoader=function(t){return console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader."),new cc(t)},t.Bone=La,t.BooleanKeyframeTrack=ql,t.BoundingBoxHelper=function(t,e){return console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead."),new qh(t,e)},t.Box2=Th,t.Box3=Pt,t.Box3Helper=class extends Ja{constructor(t,e=16776960){const n=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]),i=new xn;i.setIndex(new tn(n,1)),i.setAttribute("position",new hn([1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],3)),super(i,new Ua({color:e,toneMapped:!1})),this.box=t,this.type="Box3Helper",this.geometry.computeBoundingSphere()}updateMatrixWorld(t){const e=this.box;e.isEmpty()||(e.getCenter(this.position),e.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(t))}},t.BoxBufferGeometry=Un,t.BoxGeometry=Un,t.BoxHelper=qh,t.BufferAttribute=tn,t.BufferGeometry=xn,t.BufferGeometryLoader=Ic,t.ByteType=1010,t.Cache=ec,t.Camera=Wn,t.CameraHelper=class extends Ja{constructor(t){const e=new xn,n=new Ua({color:16777215,vertexColors:!0,toneMapped:!1}),i=[],r=[],s={},a=new Ze(16755200),o=new Ze(16711680),l=new Ze(43775),c=new Ze(16777215),h=new Ze(3355443);function u(t,e,n){d(t,n),d(e,n)}function d(t,e){i.push(0,0,0),r.push(e.r,e.g,e.b),void 0===s[t]&&(s[t]=[]),s[t].push(i.length/3-1)}u("n1","n2",a),u("n2","n4",a),u("n4","n3",a),u("n3","n1",a),u("f1","f2",a),u("f2","f4",a),u("f4","f3",a),u("f3","f1",a),u("n1","f1",a),u("n2","f2",a),u("n3","f3",a),u("n4","f4",a),u("p","n1",o),u("p","n2",o),u("p","n3",o),u("p","n4",o),u("u1","u2",l),u("u2","u3",l),u("u3","u1",l),u("c","t",c),u("p","c",h),u("cn1","cn2",h),u("cn3","cn4",h),u("cf1","cf2",h),u("cf3","cf4",h),e.setAttribute("position",new hn(i,3)),e.setAttribute("color",new hn(r,3)),super(e,n),this.type="CameraHelper",this.camera=t,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=s,this.update()}update(){const t=this.geometry,e=this.pointMap;Vh.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),Wh("c",e,t,Vh,0,0,-1),Wh("t",e,t,Vh,0,0,1),Wh("n1",e,t,Vh,-1,-1,-1),Wh("n2",e,t,Vh,1,-1,-1),Wh("n3",e,t,Vh,-1,1,-1),Wh("n4",e,t,Vh,1,1,-1),Wh("f1",e,t,Vh,-1,-1,1),Wh("f2",e,t,Vh,1,-1,1),Wh("f3",e,t,Vh,-1,1,1),Wh("f4",e,t,Vh,1,1,1),Wh("u1",e,t,Vh,.7,1.1,-1),Wh("u2",e,t,Vh,-.7,1.1,-1),Wh("u3",e,t,Vh,0,2,-1),Wh("cf1",e,t,Vh,-1,0,1),Wh("cf2",e,t,Vh,1,0,1),Wh("cf3",e,t,Vh,0,-1,1),Wh("cf4",e,t,Vh,0,1,1),Wh("cn1",e,t,Vh,-1,0,-1),Wh("cn2",e,t,Vh,1,0,-1),Wh("cn3",e,t,Vh,0,-1,-1),Wh("cn4",e,t,Vh,0,1,-1),t.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}},t.CanvasRenderer=function(){console.error("THREE.CanvasRenderer has been removed")},t.CanvasTexture=ao,t.CatmullRomCurve3=Eo,t.CineonToneMapping=3,t.CircleBufferGeometry=oo,t.CircleGeometry=oo,t.ClampToEdgeWrapping=u,t.Clock=qc,t.Color=Ze,t.ColorKeyframeTrack=Xl,t.CompressedTexture=so,t.CompressedTextureLoader=class extends rc{constructor(t){super(t)}load(t,e,n,i){const r=this,s=[],a=new so,o=new ac(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(r.withCredentials);let l=0;function c(c){o.load(t[c],(function(t){const n=r.parse(t,!0);s[c]={width:n.width,height:n.height,format:n.format,mipmaps:n.mipmaps},l+=1,6===l&&(1===n.mipmapCount&&(a.minFilter=g),a.image=s,a.format=n.format,a.needsUpdate=!0,e&&e(a))}),n,i)}if(Array.isArray(t))for(let e=0,n=t.length;e<n;++e)c(e);else o.load(t,(function(t){const n=r.parse(t,!0);if(n.isCubemap){const t=n.mipmaps.length/n.mipmapCount;for(let e=0;e<t;e++){s[e]={mipmaps:[]};for(let t=0;t<n.mipmapCount;t++)s[e].mipmaps.push(n.mipmaps[e*n.mipmapCount+t]),s[e].format=n.format,s[e].width=n.width,s[e].height=n.height}a.image=s}else a.image.width=n.width,a.image.height=n.height,a.mipmaps=n.mipmaps;1===n.mipmapCount&&(a.minFilter=g),a.format=n.format,a.needsUpdate=!0,e&&e(a)}),n,i);return a}},t.ConeBufferGeometry=co,t.ConeGeometry=co,t.CubeCamera=Xn,t.CubeReflectionMapping=r,t.CubeRefractionMapping=s,t.CubeTexture=Jn,t.CubeTextureLoader=lc,t.CubeUVReflectionMapping=l,t.CubeUVRefractionMapping=c,t.CubicBezierCurve=Co,t.CubicBezierCurve3=Po,t.CubicInterpolant=kl,t.CullFaceBack=1,t.CullFaceFront=2,t.CullFaceFrontBack=3,t.CullFaceNone=0,t.Curve=yo,t.CurvePath=Oo,t.CustomBlending=5,t.CustomToneMapping=5,t.CylinderBufferGeometry=lo,t.CylinderGeometry=lo,t.Cylindrical=class{constructor(t=1,e=0,n=0){return this.radius=t,this.theta=e,this.y=n,this}set(t,e,n){return this.radius=t,this.theta=e,this.y=n,this}copy(t){return this.radius=t.radius,this.theta=t.theta,this.y=t.y,this}setFromVector3(t){return this.setFromCartesianCoords(t.x,t.y,t.z)}setFromCartesianCoords(t,e,n){return this.radius=Math.sqrt(t*t+n*n),this.theta=Math.atan2(t,n),this.y=e,this}clone(){return(new this.constructor).copy(this)}},t.DataTexture=Ra,t.DataTexture2DArray=Wi,t.DataTexture3D=Zi,t.DataTextureLoader=cc,t.DataUtils=class{static toHalfFloat(t){t>65504&&(console.warn("THREE.DataUtils.toHalfFloat(): value exceeds 65504."),t=65504),Qh[0]=t;const e=Kh[0];let n=e>>16&32768,i=e>>12&2047;const r=e>>23&255;return r<103?n:r>142?(n|=31744,n|=(255==r?0:1)&&8388607&e,n):r<113?(i|=2048,n|=(i>>114-r)+(i>>113-r&1),n):(n|=r-112<<10|i>>1,n+=1&i,n)}},t.DecrementStencilOp=7683,t.DecrementWrapStencilOp=34056,t.DefaultLoadingManager=ic,t.DepthFormat=A,t.DepthStencilFormat=L,t.DepthTexture=qs,t.DirectionalLight=Tc,t.DirectionalLightHelper=class extends Ce{constructor(t,e,n){super(),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.color=n,void 0===e&&(e=1);let i=new xn;i.setAttribute("position",new hn([-e,e,0,e,e,0,e,-e,0,-e,-e,0,-e,e,0],3));const r=new Ua({fog:!1,toneMapped:!1});this.lightPlane=new ja(i,r),this.add(this.lightPlane),i=new xn,i.setAttribute("position",new hn([0,0,0,0,0,1],3)),this.targetLine=new ja(i,r),this.add(this.targetLine),this.update()}dispose(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose()}update(){Uh.setFromMatrixPosition(this.light.matrixWorld),Hh.setFromMatrixPosition(this.light.target.matrixWorld),Gh.subVectors(Hh,Uh),this.lightPlane.lookAt(Hh),void 0!==this.color?(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)):(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color)),this.targetLine.lookAt(Hh),this.targetLine.scale.z=Gh.length()}},t.DiscreteInterpolant=Wl,t.DodecahedronBufferGeometry=uo,t.DodecahedronGeometry=uo,t.DoubleSide=2,t.DstAlphaFactor=206,t.DstColorFactor=208,t.DynamicBufferAttribute=function(t,e){return console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead."),new tn(t,e).setUsage(Q)},t.DynamicCopyUsage=35050,t.DynamicDrawUsage=Q,t.DynamicReadUsage=35049,t.EdgesGeometry=vo,t.EdgesHelper=function(t,e){return console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead."),new Ja(new vo(t.geometry),new Ua({color:void 0!==e?e:16777215}))},t.EllipseCurve=xo,t.EqualDepth=4,t.EqualStencilFunc=514,t.EquirectangularReflectionMapping=a,t.EquirectangularRefractionMapping=o,t.Euler=fe,t.EventDispatcher=$,t.ExtrudeBufferGeometry=fl,t.ExtrudeGeometry=fl,t.FaceColors=1,t.FileLoader=ac,t.FlatShading=1,t.Float16BufferAttribute=cn,t.Float32Attribute=function(t,e){return console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead."),new hn(t,e)},t.Float32BufferAttribute=hn,t.Float64Attribute=function(t,e){return console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead."),new un(t,e)},t.Float64BufferAttribute=un,t.FloatType=M,t.Fog=Ks,t.FogExp2=Qs,t.Font=function(){console.error("THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js")},t.FontLoader=function(){console.error("THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js")},t.FramebufferTexture=ro,t.FrontSide=0,t.Frustum=ni,t.GLBufferAttribute=bh,t.GLSL1="100",t.GLSL3=K,t.GreaterDepth=6,t.GreaterEqualDepth=5,t.GreaterEqualStencilFunc=518,t.GreaterStencilFunc=516,t.GridHelper=Oh,t.Group=Vs,t.HalfFloatType=w,t.HemisphereLight=dc,t.HemisphereLightHelper=class extends Ce{constructor(t,e,n){super(),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.color=n;const i=new xl(e);i.rotateY(.5*Math.PI),this.material=new Qe({wireframe:!0,fog:!1,toneMapped:!1}),void 0===this.color&&(this.material.vertexColors=!0);const r=i.getAttribute("position"),s=new Float32Array(3*r.count);i.setAttribute("color",new tn(s,3)),this.add(new Fn(i,this.material)),this.update()}dispose(){this.children[0].geometry.dispose(),this.children[0].material.dispose()}update(){const t=this.children[0];if(void 0!==this.color)this.material.color.set(this.color);else{const e=t.geometry.getAttribute("color");Bh.copy(this.light.color),Fh.copy(this.light.groundColor);for(let t=0,n=e.count;t<n;t++){const i=t<n/2?Bh:Fh;e.setXYZ(t,i.r,i.g,i.b)}e.needsUpdate=!0}t.lookAt(zh.setFromMatrixPosition(this.light.matrixWorld).negate())}},t.HemisphereLightProbe=Gc,t.IcosahedronBufferGeometry=vl,t.IcosahedronGeometry=vl,t.ImageBitmapLoader=Fc,t.ImageLoader=oc,t.ImageUtils=xt,t.ImmediateRenderObject=function(){console.error("THREE.ImmediateRenderObject has been removed.")},t.IncrementStencilOp=7682,t.IncrementWrapStencilOp=34055,t.InstancedBufferAttribute=Ia,t.InstancedBufferGeometry=Dc,t.InstancedInterleavedBuffer=_h,t.InstancedMesh=Oa,t.Int16Attribute=function(t,e){return console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead."),new sn(t,e)},t.Int16BufferAttribute=sn,t.Int32Attribute=function(t,e){return console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead."),new on(t,e)},t.Int32BufferAttribute=on,t.Int8Attribute=function(t,e){return console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead."),new en(t,e)},t.Int8BufferAttribute=en,t.IntType=1013,t.InterleavedBuffer=ta,t.InterleavedBufferAttribute=na,t.Interpolant=Gl,t.InterpolateDiscrete=U,t.InterpolateLinear=H,t.InterpolateSmooth=G,t.InvertStencilOp=5386,t.JSONLoader=function(){console.error("THREE.JSONLoader has been removed.")},t.KeepStencilOp=Y,t.KeyframeTrack=jl,t.LOD=ba,t.LatheBufferGeometry=yl,t.LatheGeometry=yl,t.Layers=ge,t.LensFlare=function(){console.error("THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js")},t.LessDepth=2,t.LessEqualDepth=3,t.LessEqualStencilFunc=515,t.LessStencilFunc=513,t.Light=uc,t.LightProbe=Rc,t.Line=ja,t.Line3=Lh,t.LineBasicMaterial=Ua,t.LineCurve=Do,t.LineCurve3=Io,t.LineDashedMaterial=Ol,t.LineLoop=Ya,t.LinePieces=1,t.LineSegments=Ja,t.LineStrip=0,t.LinearEncoding=X,t.LinearFilter=g,t.LinearInterpolant=Vl,t.LinearMipMapLinearFilter=1008,t.LinearMipMapNearestFilter=1007,t.LinearMipmapLinearFilter=y,t.LinearMipmapNearestFilter=v,t.LinearToneMapping=1,t.Loader=rc,t.LoaderUtils=Pc,t.LoadingManager=nc,t.LoopOnce=2200,t.LoopPingPong=2202,t.LoopRepeat=2201,t.LuminanceAlphaFormat=1025,t.LuminanceFormat=1024,t.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},t.Material=Ve,t.MaterialLoader=Cc,t.Math=ut,t.MathUtils=ut,t.Matrix3=pt,t.Matrix4=se,t.MaxEquation=104,t.Mesh=Fn,t.MeshBasicMaterial=Qe,t.MeshDepthMaterial=Bs,t.MeshDistanceMaterial=Fs,t.MeshFaceMaterial=function(t){return console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead."),t},t.MeshLambertMaterial=Bl,t.MeshMatcapMaterial=Fl,t.MeshNormalMaterial=zl,t.MeshPhongMaterial=Il,t.MeshPhysicalMaterial=Dl,t.MeshStandardMaterial=Pl,t.MeshToonMaterial=Nl,t.MinEquation=103,t.MirroredRepeatWrapping=d,t.MixOperation=1,t.MultiMaterial=function(t=[]){return console.warn("THREE.MultiMaterial has been removed. Use an Array instead."),t.isMultiMaterial=!0,t.materials=t,t.clone=function(){return t.slice()},t},t.MultiplyBlending=4,t.MultiplyOperation=0,t.NearestFilter=p,t.NearestMipMapLinearFilter=1005,t.NearestMipMapNearestFilter=1004,t.NearestMipmapLinearFilter=f,t.NearestMipmapNearestFilter=m,t.NeverDepth=0,t.NeverStencilFunc=512,t.NoBlending=0,t.NoColors=0,t.NoToneMapping=0,t.NormalAnimationBlendMode=j,t.NormalBlending=1,t.NotEqualDepth=7,t.NotEqualStencilFunc=517,t.NumberKeyframeTrack=Jl,t.Object3D=Ce,t.ObjectLoader=class extends rc{constructor(t){super(t)}load(t,e,n,i){const r=this,s=""===this.path?Pc.extractUrlBase(t):this.path;this.resourcePath=this.resourcePath||s;const a=new ac(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(t,(function(n){let s=null;try{s=JSON.parse(n)}catch(e){return void 0!==i&&i(e),void console.error("THREE:ObjectLoader: Can't parse "+t+".",e.message)}const a=s.metadata;void 0!==a&&void 0!==a.type&&"geometry"!==a.type.toLowerCase()?r.parse(s,e):console.error("THREE.ObjectLoader: Can't load "+t)}),n,i)}async loadAsync(t,e){const n=""===this.path?Pc.extractUrlBase(t):this.path;this.resourcePath=this.resourcePath||n;const i=new ac(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials);const r=await i.loadAsync(t,e),s=JSON.parse(r),a=s.metadata;if(void 0===a||void 0===a.type||"geometry"===a.type.toLowerCase())throw new Error("THREE.ObjectLoader: Can't load "+t);return await this.parseAsync(s)}parse(t,e){const n=this.parseAnimations(t.animations),i=this.parseShapes(t.shapes),r=this.parseGeometries(t.geometries,i),s=this.parseImages(t.images,(function(){void 0!==e&&e(l)})),a=this.parseTextures(t.textures,s),o=this.parseMaterials(t.materials,a),l=this.parseObject(t.object,r,o,a,n),c=this.parseSkeletons(t.skeletons,l);if(this.bindSkeletons(l,c),void 0!==e){let t=!1;for(const e in s)if(s[e]instanceof HTMLImageElement){t=!0;break}!1===t&&e(l)}return l}async parseAsync(t){const e=this.parseAnimations(t.animations),n=this.parseShapes(t.shapes),i=this.parseGeometries(t.geometries,n),r=await this.parseImagesAsync(t.images),s=this.parseTextures(t.textures,r),a=this.parseMaterials(t.materials,s),o=this.parseObject(t.object,i,a,s,e),l=this.parseSkeletons(t.skeletons,o);return this.bindSkeletons(o,l),o}parseShapes(t){const e={};if(void 0!==t)for(let n=0,i=t.length;n<i;n++){const i=(new Ho).fromJSON(t[n]);e[i.uuid]=i}return e}parseSkeletons(t,e){const n={},i={};if(e.traverse((function(t){t.isBone&&(i[t.uuid]=t)})),void 0!==t)for(let e=0,r=t.length;e<r;e++){const r=(new Da).fromJSON(t[e],i);n[r.uuid]=r}return n}parseGeometries(t,e){const n={};if(void 0!==t){const i=new Ic;for(let r=0,s=t.length;r<s;r++){let s;const a=t[r];switch(a.type){case"BufferGeometry":case"InstancedBufferGeometry":s=i.parse(a);break;case"Geometry":console.error("THREE.ObjectLoader: The legacy Geometry type is no longer supported.");break;default:a.type in Rl?s=Rl[a.type].fromJSON(a,e):console.warn(`THREE.ObjectLoader: Unsupported geometry type "${a.type}"`)}s.uuid=a.uuid,void 0!==a.name&&(s.name=a.name),!0===s.isBufferGeometry&&void 0!==a.userData&&(s.userData=a.userData),n[a.uuid]=s}}return n}parseMaterials(t,e){const n={},i={};if(void 0!==t){const r=new Cc;r.setTextures(e);for(let e=0,s=t.length;e<s;e++){const s=t[e];if("MultiMaterial"===s.type){const t=[];for(let e=0;e<s.materials.length;e++){const i=s.materials[e];void 0===n[i.uuid]&&(n[i.uuid]=r.parse(i)),t.push(n[i.uuid])}i[s.uuid]=t}else void 0===n[s.uuid]&&(n[s.uuid]=r.parse(s)),i[s.uuid]=n[s.uuid]}}return i}parseAnimations(t){const e={};if(void 0!==t)for(let n=0;n<t.length;n++){const i=t[n],r=$l.parse(i);e[r.uuid]=r}return e}parseImages(t,e){const n=this,i={};let r;function s(t){if("string"==typeof t){const e=t;return function(t){return n.manager.itemStart(t),r.load(t,(function(){n.manager.itemEnd(t)}),void 0,(function(){n.manager.itemError(t),n.manager.itemEnd(t)}))}(/^(\/\/)|([a-z]+:(\/\/)?)/i.test(e)?e:n.resourcePath+e)}return t.data?{data:gt(t.type,t.data),width:t.width,height:t.height}:null}if(void 0!==t&&t.length>0){const n=new nc(e);r=new oc(n),r.setCrossOrigin(this.crossOrigin);for(let e=0,n=t.length;e<n;e++){const n=t[e],r=n.url;if(Array.isArray(r)){i[n.uuid]=[];for(let t=0,e=r.length;t<e;t++){const e=s(r[t]);null!==e&&(e instanceof HTMLImageElement?i[n.uuid].push(e):i[n.uuid].push(new Ra(e.data,e.width,e.height)))}}else{const t=s(n.url);null!==t&&(i[n.uuid]=t)}}}return i}async parseImagesAsync(t){const e=this,n={};let i;async function r(t){if("string"==typeof t){const n=t,r=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(n)?n:e.resourcePath+n;return await i.loadAsync(r)}return t.data?{data:gt(t.type,t.data),width:t.width,height:t.height}:null}if(void 0!==t&&t.length>0){i=new oc(this.manager),i.setCrossOrigin(this.crossOrigin);for(let e=0,i=t.length;e<i;e++){const i=t[e],s=i.url;if(Array.isArray(s)){n[i.uuid]=[];for(let t=0,e=s.length;t<e;t++){const e=s[t],a=await r(e);null!==a&&(a instanceof HTMLImageElement?n[i.uuid].push(a):n[i.uuid].push(new Ra(a.data,a.width,a.height)))}}else{const t=await r(i.url);null!==t&&(n[i.uuid]=t)}}}return n}parseTextures(t,e){function n(t,e){return"number"==typeof t?t:(console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",t),e[t])}const i={};if(void 0!==t)for(let r=0,s=t.length;r<s;r++){const s=t[r];let a;void 0===s.image&&console.warn('THREE.ObjectLoader: No "image" specified for',s.uuid),void 0===e[s.image]&&console.warn("THREE.ObjectLoader: Undefined image",s.image);const o=e[s.image];Array.isArray(o)?(a=new Jn(o),6===o.length&&(a.needsUpdate=!0)):(a=o&&o.data?new Ra(o.data,o.width,o.height):new bt(o),o&&(a.needsUpdate=!0)),a.uuid=s.uuid,void 0!==s.name&&(a.name=s.name),void 0!==s.mapping&&(a.mapping=n(s.mapping,Nc)),void 0!==s.offset&&a.offset.fromArray(s.offset),void 0!==s.repeat&&a.repeat.fromArray(s.repeat),void 0!==s.center&&a.center.fromArray(s.center),void 0!==s.rotation&&(a.rotation=s.rotation),void 0!==s.wrap&&(a.wrapS=n(s.wrap[0],zc),a.wrapT=n(s.wrap[1],zc)),void 0!==s.format&&(a.format=s.format),void 0!==s.type&&(a.type=s.type),void 0!==s.encoding&&(a.encoding=s.encoding),void 0!==s.minFilter&&(a.minFilter=n(s.minFilter,Bc)),void 0!==s.magFilter&&(a.magFilter=n(s.magFilter,Bc)),void 0!==s.anisotropy&&(a.anisotropy=s.anisotropy),void 0!==s.flipY&&(a.flipY=s.flipY),void 0!==s.premultiplyAlpha&&(a.premultiplyAlpha=s.premultiplyAlpha),void 0!==s.unpackAlignment&&(a.unpackAlignment=s.unpackAlignment),void 0!==s.userData&&(a.userData=s.userData),i[s.uuid]=a}return i}parseObject(t,e,n,i,r){let s,a,o;function l(t){return void 0===e[t]&&console.warn("THREE.ObjectLoader: Undefined geometry",t),e[t]}function c(t){if(void 0!==t){if(Array.isArray(t)){const e=[];for(let i=0,r=t.length;i<r;i++){const r=t[i];void 0===n[r]&&console.warn("THREE.ObjectLoader: Undefined material",r),e.push(n[r])}return e}return void 0===n[t]&&console.warn("THREE.ObjectLoader: Undefined material",t),n[t]}}function h(t){return void 0===i[t]&&console.warn("THREE.ObjectLoader: Undefined texture",t),i[t]}switch(t.type){case"Scene":s=new $s,void 0!==t.background&&(Number.isInteger(t.background)?s.background=new Ze(t.background):s.background=h(t.background)),void 0!==t.environment&&(s.environment=h(t.environment)),void 0!==t.fog&&("Fog"===t.fog.type?s.fog=new Ks(t.fog.color,t.fog.near,t.fog.far):"FogExp2"===t.fog.type&&(s.fog=new Qs(t.fog.color,t.fog.density)));break;case"PerspectiveCamera":s=new jn(t.fov,t.aspect,t.near,t.far),void 0!==t.focus&&(s.focus=t.focus),void 0!==t.zoom&&(s.zoom=t.zoom),void 0!==t.filmGauge&&(s.filmGauge=t.filmGauge),void 0!==t.filmOffset&&(s.filmOffset=t.filmOffset),void 0!==t.view&&(s.view=Object.assign({},t.view));break;case"OrthographicCamera":s=new fi(t.left,t.right,t.top,t.bottom,t.near,t.far),void 0!==t.zoom&&(s.zoom=t.zoom),void 0!==t.view&&(s.view=Object.assign({},t.view));break;case"AmbientLight":s=new Ec(t.color,t.intensity);break;case"DirectionalLight":s=new Tc(t.color,t.intensity);break;case"PointLight":s=new wc(t.color,t.intensity,t.distance,t.decay);break;case"RectAreaLight":s=new Ac(t.color,t.intensity,t.width,t.height);break;case"SpotLight":s=new yc(t.color,t.intensity,t.distance,t.angle,t.penumbra,t.decay);break;case"HemisphereLight":s=new dc(t.color,t.groundColor,t.intensity);break;case"LightProbe":s=(new Rc).fromJSON(t);break;case"SkinnedMesh":a=l(t.geometry),o=c(t.material),s=new Aa(a,o),void 0!==t.bindMode&&(s.bindMode=t.bindMode),void 0!==t.bindMatrix&&s.bindMatrix.fromArray(t.bindMatrix),void 0!==t.skeleton&&(s.skeleton=t.skeleton);break;case"Mesh":a=l(t.geometry),o=c(t.material),s=new Fn(a,o);break;case"InstancedMesh":a=l(t.geometry),o=c(t.material);const e=t.count,n=t.instanceMatrix,i=t.instanceColor;s=new Oa(a,o,e),s.instanceMatrix=new Ia(new Float32Array(n.array),16),void 0!==i&&(s.instanceColor=new Ia(new Float32Array(i.array),i.itemSize));break;case"LOD":s=new ba;break;case"Line":s=new ja(l(t.geometry),c(t.material));break;case"LineLoop":s=new Ya(l(t.geometry),c(t.material));break;case"LineSegments":s=new Ja(l(t.geometry),c(t.material));break;case"PointCloud":case"Points":s=new eo(l(t.geometry),c(t.material));break;case"Sprite":s=new va(c(t.material));break;case"Group":s=new Vs;break;case"Bone":s=new La;break;default:s=new Ce}if(s.uuid=t.uuid,void 0!==t.name&&(s.name=t.name),void 0!==t.matrix?(s.matrix.fromArray(t.matrix),void 0!==t.matrixAutoUpdate&&(s.matrixAutoUpdate=t.matrixAutoUpdate),s.matrixAutoUpdate&&s.matrix.decompose(s.position,s.quaternion,s.scale)):(void 0!==t.position&&s.position.fromArray(t.position),void 0!==t.rotation&&s.rotation.fromArray(t.rotation),void 0!==t.quaternion&&s.quaternion.fromArray(t.quaternion),void 0!==t.scale&&s.scale.fromArray(t.scale)),void 0!==t.castShadow&&(s.castShadow=t.castShadow),void 0!==t.receiveShadow&&(s.receiveShadow=t.receiveShadow),t.shadow&&(void 0!==t.shadow.bias&&(s.shadow.bias=t.shadow.bias),void 0!==t.shadow.normalBias&&(s.shadow.normalBias=t.shadow.normalBias),void 0!==t.shadow.radius&&(s.shadow.radius=t.shadow.radius),void 0!==t.shadow.mapSize&&s.shadow.mapSize.fromArray(t.shadow.mapSize),void 0!==t.shadow.camera&&(s.shadow.camera=this.parseObject(t.shadow.camera))),void 0!==t.visible&&(s.visible=t.visible),void 0!==t.frustumCulled&&(s.frustumCulled=t.frustumCulled),void 0!==t.renderOrder&&(s.renderOrder=t.renderOrder),void 0!==t.userData&&(s.userData=t.userData),void 0!==t.layers&&(s.layers.mask=t.layers),void 0!==t.children){const a=t.children;for(let t=0;t<a.length;t++)s.add(this.parseObject(a[t],e,n,i,r))}if(void 0!==t.animations){const e=t.animations;for(let t=0;t<e.length;t++){const n=e[t];s.animations.push(r[n])}}if("LOD"===t.type){void 0!==t.autoUpdate&&(s.autoUpdate=t.autoUpdate);const e=t.levels;for(let t=0;t<e.length;t++){const n=e[t],i=s.getObjectByProperty("uuid",n.object);void 0!==i&&s.addLevel(i,n.distance)}}return s}bindSkeletons(t,e){0!==Object.keys(e).length&&t.traverse((function(t){if(!0===t.isSkinnedMesh&&void 0!==t.skeleton){const n=e[t.skeleton];void 0===n?console.warn("THREE.ObjectLoader: No skeleton found with UUID:",t.skeleton):t.bind(n,t.bindMatrix)}}))}setTexturePath(t){return console.warn("THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath()."),this.setResourcePath(t)}},t.ObjectSpaceNormalMap=1,t.OctahedronBufferGeometry=xl,t.OctahedronGeometry=xl,t.OneFactor=201,t.OneMinusDstAlphaFactor=207,t.OneMinusDstColorFactor=209,t.OneMinusSrcAlphaFactor=205,t.OneMinusSrcColorFactor=203,t.OrthographicCamera=fi,t.PCFShadowMap=1,t.PCFSoftShadowMap=2,t.PMREMGenerator=Pi,t.ParametricGeometry=function(){return console.error("THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js"),new xn},t.Particle=function(t){return console.warn("THREE.Particle has been renamed to THREE.Sprite."),new va(t)},t.ParticleBasicMaterial=function(t){return console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial."),new Za(t)},t.ParticleSystem=function(t,e){return console.warn("THREE.ParticleSystem has been renamed to THREE.Points."),new eo(t,e)},t.ParticleSystemMaterial=function(t){return console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial."),new Za(t)},t.Path=Uo,t.PerspectiveCamera=jn,t.Plane=$n,t.PlaneBufferGeometry=si,t.PlaneGeometry=si,t.PlaneHelper=class extends ja{constructor(t,e=1,n=16776960){const i=n,r=new xn;r.setAttribute("position",new hn([1,-1,1,-1,1,1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,0,0,1,0,0,0],3)),r.computeBoundingSphere(),super(r,new Ua({color:i,toneMapped:!1})),this.type="PlaneHelper",this.plane=t,this.size=e;const s=new xn;s.setAttribute("position",new hn([1,1,1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,1],3)),s.computeBoundingSphere(),this.add(new Fn(s,new Qe({color:i,opacity:.2,transparent:!0,depthWrite:!1,toneMapped:!1})))}updateMatrixWorld(t){let e=-this.plane.constant;Math.abs(e)<1e-8&&(e=1e-8),this.scale.set(.5*this.size,.5*this.size,e),this.children[0].material.side=e<0?1:0,this.lookAt(this.plane.normal),super.updateMatrixWorld(t)}},t.PointCloud=function(t,e){return console.warn("THREE.PointCloud has been renamed to THREE.Points."),new eo(t,e)},t.PointCloudMaterial=function(t){return console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial."),new Za(t)},t.PointLight=wc,t.PointLightHelper=class extends Fn{constructor(t,e,n){super(new Ml(e,4,2),new Qe({wireframe:!0,fog:!1,toneMapped:!1})),this.light=t,this.light.updateMatrixWorld(),this.color=n,this.type="PointLightHelper",this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1,this.update()}dispose(){this.geometry.dispose(),this.material.dispose()}update(){void 0!==this.color?this.material.color.set(this.color):this.material.color.copy(this.light.color)}},t.Points=eo,t.PointsMaterial=Za,t.PolarGridHelper=class extends Ja{constructor(t=10,e=16,n=8,i=64,r=4473924,s=8947848){r=new Ze(r),s=new Ze(s);const a=[],o=[];for(let n=0;n<=e;n++){const i=n/e*(2*Math.PI),l=Math.sin(i)*t,c=Math.cos(i)*t;a.push(0,0,0),a.push(l,0,c);const h=1&n?r:s;o.push(h.r,h.g,h.b),o.push(h.r,h.g,h.b)}for(let e=0;e<=n;e++){const l=1&e?r:s,c=t-t/n*e;for(let t=0;t<i;t++){let e=t/i*(2*Math.PI),n=Math.sin(e)*c,r=Math.cos(e)*c;a.push(n,0,r),o.push(l.r,l.g,l.b),e=(t+1)/i*(2*Math.PI),n=Math.sin(e)*c,r=Math.cos(e)*c,a.push(n,0,r),o.push(l.r,l.g,l.b)}}const l=new xn;l.setAttribute("position",new hn(a,3)),l.setAttribute("color",new hn(o,3));super(l,new Ua({vertexColors:!0,toneMapped:!1})),this.type="PolarGridHelper"}},t.PolyhedronBufferGeometry=ho,t.PolyhedronGeometry=ho,t.PositionalAudio=class extends Kc{constructor(t){super(t),this.panner=this.context.createPanner(),this.panner.panningModel="HRTF",this.panner.connect(this.gain)}getOutput(){return this.panner}getRefDistance(){return this.panner.refDistance}setRefDistance(t){return this.panner.refDistance=t,this}getRolloffFactor(){return this.panner.rolloffFactor}setRolloffFactor(t){return this.panner.rolloffFactor=t,this}getDistanceModel(){return this.panner.distanceModel}setDistanceModel(t){return this.panner.distanceModel=t,this}getMaxDistance(){return this.panner.maxDistance}setMaxDistance(t){return this.panner.maxDistance=t,this}setDirectionalCone(t,e,n){return this.panner.coneInnerAngle=t,this.panner.coneOuterAngle=e,this.panner.coneOuterGain=n,this}updateMatrixWorld(t){if(super.updateMatrixWorld(t),!0===this.hasPlaybackControl&&!1===this.isPlaying)return;this.matrixWorld.decompose($c,th,eh),nh.set(0,0,1).applyQuaternion(th);const e=this.panner;if(e.positionX){const t=this.context.currentTime+this.listener.timeDelta;e.positionX.linearRampToValueAtTime($c.x,t),e.positionY.linearRampToValueAtTime($c.y,t),e.positionZ.linearRampToValueAtTime($c.z,t),e.orientationX.linearRampToValueAtTime(nh.x,t),e.orientationY.linearRampToValueAtTime(nh.y,t),e.orientationZ.linearRampToValueAtTime(nh.z,t)}else e.setPosition($c.x,$c.y,$c.z),e.setOrientation(nh.x,nh.y,nh.z)}},t.PropertyBinding=fh,t.PropertyMixer=rh,t.QuadraticBezierCurve=No,t.QuadraticBezierCurve3=zo,t.Quaternion=At,t.QuaternionKeyframeTrack=Zl,t.QuaternionLinearInterpolant=Yl,t.REVISION=e,t.RGBADepthPacking=3201,t.RGBAFormat=E,t.RGBAIntegerFormat=1033,t.RGBA_ASTC_10x10_Format=37819,t.RGBA_ASTC_10x5_Format=37816,t.RGBA_ASTC_10x6_Format=37817,t.RGBA_ASTC_10x8_Format=37818,t.RGBA_ASTC_12x10_Format=37820,t.RGBA_ASTC_12x12_Format=37821,t.RGBA_ASTC_4x4_Format=37808,t.RGBA_ASTC_5x4_Format=37809,t.RGBA_ASTC_5x5_Format=37810,t.RGBA_ASTC_6x5_Format=37811,t.RGBA_ASTC_6x6_Format=37812,t.RGBA_ASTC_8x5_Format=37813,t.RGBA_ASTC_8x6_Format=37814,t.RGBA_ASTC_8x8_Format=37815,t.RGBA_BPTC_Format=36492,t.RGBA_ETC2_EAC_Format=O,t.RGBA_PVRTC_2BPPV1_Format=B,t.RGBA_PVRTC_4BPPV1_Format=z,t.RGBA_S3TC_DXT1_Format=C,t.RGBA_S3TC_DXT3_Format=P,t.RGBA_S3TC_DXT5_Format=D,t.RGBFormat=T,t.RGBIntegerFormat=1032,t.RGB_ETC1_Format=36196,t.RGB_ETC2_Format=F,t.RGB_PVRTC_2BPPV1_Format=N,t.RGB_PVRTC_4BPPV1_Format=I,t.RGB_S3TC_DXT1_Format=R,t.RGFormat=1030,t.RGIntegerFormat=1031,t.RawShaderMaterial=gi,t.Ray=re,t.Raycaster=class{constructor(t,e,n=0,i=1/0){this.ray=new re(t,e),this.near=n,this.far=i,this.camera=null,this.layers=new ge,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(t,e){this.ray.set(t,e)}setFromCamera(t,e){e&&e.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(t.x,t.y,.5).unproject(e).sub(this.ray.origin).normalize(),this.camera=e):e&&e.isOrthographicCamera?(this.ray.origin.set(t.x,t.y,(e.near+e.far)/(e.near-e.far)).unproject(e),this.ray.direction.set(0,0,-1).transformDirection(e.matrixWorld),this.camera=e):console.error("THREE.Raycaster: Unsupported camera type: "+e.type)}intersectObject(t,e=!0,n=[]){return wh(t,this,n,e),n.sort(Mh),n}intersectObjects(t,e=!0,n=[]){for(let i=0,r=t.length;i<r;i++)wh(t[i],this,n,e);return n.sort(Mh),n}},t.RectAreaLight=Ac,t.RedFormat=1028,t.RedIntegerFormat=1029,t.ReinhardToneMapping=2,t.RepeatWrapping=h,t.ReplaceStencilOp=7681,t.ReverseSubtractEquation=102,t.RingBufferGeometry=_l,t.RingGeometry=_l,t.SRGB8_ALPHA8_ASTC_10x10_Format=37851,t.SRGB8_ALPHA8_ASTC_10x5_Format=37848,t.SRGB8_ALPHA8_ASTC_10x6_Format=37849,t.SRGB8_ALPHA8_ASTC_10x8_Format=37850,t.SRGB8_ALPHA8_ASTC_12x10_Format=37852,t.SRGB8_ALPHA8_ASTC_12x12_Format=37853,t.SRGB8_ALPHA8_ASTC_4x4_Format=37840,t.SRGB8_ALPHA8_ASTC_5x4_Format=37841,t.SRGB8_ALPHA8_ASTC_5x5_Format=37842,t.SRGB8_ALPHA8_ASTC_6x5_Format=37843,t.SRGB8_ALPHA8_ASTC_6x6_Format=37844,t.SRGB8_ALPHA8_ASTC_8x5_Format=37845,t.SRGB8_ALPHA8_ASTC_8x6_Format=37846,t.SRGB8_ALPHA8_ASTC_8x8_Format=37847,t.Scene=$s,t.SceneUtils=$h,t.ShaderChunk=ai,t.ShaderLib=li,t.ShaderMaterial=Vn,t.ShadowMaterial=Cl,t.Shape=Ho,t.ShapeBufferGeometry=bl,t.ShapeGeometry=bl,t.ShapePath=class{constructor(){this.type="ShapePath",this.color=new Ze,this.subPaths=[],this.currentPath=null}moveTo(t,e){return this.currentPath=new Uo,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,r,s){return this.currentPath.bezierCurveTo(t,e,n,i,r,s),this}splineThru(t){return this.currentPath.splineThru(t),this}toShapes(t,e){function n(t){const e=[];for(let n=0,i=t.length;n<i;n++){const i=t[n],r=new Ho;r.curves=i.curves,e.push(r)}return e}function i(t,e){const n=e.length;let i=!1;for(let r=n-1,s=0;s<n;r=s++){let n=e[r],a=e[s],o=a.x-n.x,l=a.y-n.y;if(Math.abs(l)>Number.EPSILON){if(l<0&&(n=e[s],o=-o,a=e[r],l=-l),t.y<n.y||t.y>a.y)continue;if(t.y===n.y){if(t.x===n.x)return!0}else{const e=l*(t.x-n.x)-o*(t.y-n.y);if(0===e)return!0;if(e<0)continue;i=!i}}else{if(t.y!==n.y)continue;if(a.x<=t.x&&t.x<=n.x||n.x<=t.x&&t.x<=a.x)return!0}}return i}const r=dl.isClockWise,s=this.subPaths;if(0===s.length)return[];if(!0===e)return n(s);let a,o,l;const c=[];if(1===s.length)return o=s[0],l=new Ho,l.curves=o.curves,c.push(l),c;let h=!r(s[0].getPoints());h=t?!h:h;const u=[],d=[];let p,m,f=[],g=0;d[g]=void 0,f[g]=[];for(let e=0,n=s.length;e<n;e++)o=s[e],p=o.getPoints(),a=r(p),a=t?!a:a,a?(!h&&d[g]&&g++,d[g]={s:new Ho,p:p},d[g].s.curves=o.curves,h&&g++,f[g]=[]):f[g].push({h:o,p:p[0]});if(!d[0])return n(s);if(d.length>1){let t=!1;const e=[];for(let t=0,e=d.length;t<e;t++)u[t]=[];for(let n=0,r=d.length;n<r;n++){const r=f[n];for(let s=0;s<r.length;s++){const a=r[s];let o=!0;for(let r=0;r<d.length;r++)i(a.p,d[r].p)&&(n!==r&&e.push({froms:n,tos:r,hole:s}),o?(o=!1,u[r].push(a)):t=!0);o&&u[n].push(a)}}e.length>0&&(t||(f=u))}for(let t=0,e=d.length;t<e;t++){l=d[t].s,c.push(l),m=f[t];for(let t=0,e=m.length;t<e;t++)l.holes.push(m[t].h)}return c}},t.ShapeUtils=dl,t.ShortType=1011,t.Skeleton=Da,t.SkeletonHelper=Ih,t.SkinnedMesh=Aa,t.SmoothShading=2,t.Sphere=Zt,t.SphereBufferGeometry=Ml,t.SphereGeometry=Ml,t.Spherical=class{constructor(t=1,e=0,n=0){return this.radius=t,this.phi=e,this.theta=n,this}set(t,e,n){return this.radius=t,this.phi=e,this.theta=n,this}copy(t){return this.radius=t.radius,this.phi=t.phi,this.theta=t.theta,this}makeSafe(){const t=1e-6;return this.phi=Math.max(t,Math.min(Math.PI-t,this.phi)),this}setFromVector3(t){return this.setFromCartesianCoords(t.x,t.y,t.z)}setFromCartesianCoords(t,e,n){return this.radius=Math.sqrt(t*t+e*e+n*n),0===this.radius?(this.theta=0,this.phi=0):(this.theta=Math.atan2(t,n),this.phi=Math.acos(st(e/this.radius,-1,1))),this}clone(){return(new this.constructor).copy(this)}},t.SphericalHarmonics3=Lc,t.SplineCurve=Bo,t.SpotLight=yc,t.SpotLightHelper=class extends Ce{constructor(t,e){super(),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.color=e;const n=new xn,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 t=0,e=1,n=32;t<n;t++,e++){const r=t/n*Math.PI*2,s=e/n*Math.PI*2;i.push(Math.cos(r),Math.sin(r),1,Math.cos(s),Math.sin(s),1)}n.setAttribute("position",new hn(i,3));const r=new Ua({fog:!1,toneMapped:!1});this.cone=new Ja(n,r),this.add(this.cone),this.update()}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose()}update(){this.light.updateMatrixWorld();const t=this.light.distance?this.light.distance:1e3,e=t*Math.tan(this.light.angle);this.cone.scale.set(e,e,t),Rh.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(Rh),void 0!==this.color?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}},t.Sprite=va,t.SpriteMaterial=ia,t.SrcAlphaFactor=204,t.SrcAlphaSaturateFactor=210,t.SrcColorFactor=202,t.StaticCopyUsage=35046,t.StaticDrawUsage=Z,t.StaticReadUsage=35045,t.StereoCamera=class{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new jn,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new jn,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,jc.copy(t.projectionMatrix);const n=e.eyeSep/2,i=n*e.near/e.focus,r=e.near*Math.tan(nt*e.fov*.5)/e.zoom;let s,a;Wc.elements[12]=-n,Vc.elements[12]=n,s=-r*e.aspect+i,a=r*e.aspect+i,jc.elements[0]=2*e.near/(a-s),jc.elements[8]=(a+s)/(a-s),this.cameraL.projectionMatrix.copy(jc),s=-r*e.aspect-i,a=r*e.aspect-i,jc.elements[0]=2*e.near/(a-s),jc.elements[8]=(a+s)/(a-s),this.cameraR.projectionMatrix.copy(jc)}this.cameraL.matrixWorld.copy(t.matrixWorld).multiply(Wc),this.cameraR.matrixWorld.copy(t.matrixWorld).multiply(Vc)}},t.StreamCopyUsage=35042,t.StreamDrawUsage=35040,t.StreamReadUsage=35041,t.StringKeyframeTrack=Ql,t.SubtractEquation=101,t.SubtractiveBlending=3,t.TOUCH={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},t.TangentSpaceNormalMap=0,t.TetrahedronBufferGeometry=wl,t.TetrahedronGeometry=wl,t.TextGeometry=function(){return console.error("THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js"),new xn},t.Texture=bt,t.TextureLoader=hc,t.TorusBufferGeometry=Sl,t.TorusGeometry=Sl,t.TorusKnotBufferGeometry=Tl,t.TorusKnotGeometry=Tl,t.Triangle=Ge,t.TriangleFanDrawMode=2,t.TriangleStripDrawMode=1,t.TrianglesDrawMode=0,t.TubeBufferGeometry=El,t.TubeGeometry=El,t.UVMapping=i,t.Uint16Attribute=function(t,e){return console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead."),new an(t,e)},t.Uint16BufferAttribute=an,t.Uint32Attribute=function(t,e){return console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead."),new ln(t,e)},t.Uint32BufferAttribute=ln,t.Uint8Attribute=function(t,e){return console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead."),new nn(t,e)},t.Uint8BufferAttribute=nn,t.Uint8ClampedAttribute=function(t,e){return console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead."),new rn(t,e)},t.Uint8ClampedBufferAttribute=rn,t.Uniform=xh,t.UniformsLib=oi,t.UniformsUtils=kn,t.UnsignedByteType=x,t.UnsignedInt248Type=S,t.UnsignedIntType=b,t.UnsignedShort4444Type=1017,t.UnsignedShort5551Type=1018,t.UnsignedShort565Type=1019,t.UnsignedShortType=_,t.VSMShadowMap=3,t.Vector2=dt,t.Vector3=Lt,t.Vector4=wt,t.VectorKeyframeTrack=Kl,t.Vertex=function(t,e,n){return console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead."),new Lt(t,e,n)},t.VertexColors=2,t.VideoTexture=io,t.WebGL1Renderer=Zs,t.WebGLCubeRenderTarget=Yn,t.WebGLMultipleRenderTargets=Tt,t.WebGLMultisampleRenderTarget=Et,t.WebGLRenderTarget=St,t.WebGLRenderTargetCube=function(t,e,n){return console.warn("THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options )."),new Yn(t,n)},t.WebGLRenderer=Ys,t.WebGLUtils=Gs,t.WireframeGeometry=Al,t.WireframeHelper=function(t,e){return console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead."),new Ja(new Al(t.geometry),new Ua({color:void 0!==e?e:16777215}))},t.WrapAroundEnding=W,t.XHRLoader=function(t){return console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader."),new ac(t)},t.ZeroCurvatureEnding=k,t.ZeroFactor=200,t.ZeroSlopeEnding=V,t.ZeroStencilOp=0,t.sRGBEncoding=J,Object.defineProperty(t,"__esModule",{value:!0})}));
+!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).THREE={})}(this,(function(t){"use strict";const e="137",n=100,i=300,r=301,s=302,a=303,o=304,l=306,c=307,h=1e3,u=1001,d=1002,p=1003,m=1004,f=1005,g=1006,v=1007,y=1008,x=1009,_=1012,M=1014,b=1015,w=1016,S=1020,T=1023,E=1026,A=1027,R=33776,L=33777,C=33778,P=33779,D=35840,I=35841,N=35842,B=35843,z=37492,O=37496,F=37808,U=37809,H=37810,G=37811,k=37812,V=37813,W=37814,j=37815,q=37816,X=37817,J=37818,Y=37819,Z=37820,K=37821,Q=36492,$=2300,tt=2301,et=2302,nt=2400,it=2401,rt=2402,st=2500,at=2501,ot=3e3,lt=3001,ct=7680,ht=35044,ut=35048,dt="300 es",pt=1035;class mt{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[t]&&(n[t]=[]),-1===n[t].indexOf(e)&&n[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[t]&&-1!==n[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const n=this._listeners[t];if(void 0!==n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const n=e.slice(0);for(let e=0,i=n.length;e<i;e++)n[e].call(this,t);t.target=null}}}const ft=[];for(let t=0;t<256;t++)ft[t]=(t<16?"0":"")+t.toString(16);let gt=1234567;const vt=Math.PI/180,yt=180/Math.PI;function xt(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(ft[255&t]+ft[t>>8&255]+ft[t>>16&255]+ft[t>>24&255]+"-"+ft[255&e]+ft[e>>8&255]+"-"+ft[e>>16&15|64]+ft[e>>24&255]+"-"+ft[63&n|128]+ft[n>>8&255]+"-"+ft[n>>16&255]+ft[n>>24&255]+ft[255&i]+ft[i>>8&255]+ft[i>>16&255]+ft[i>>24&255]).toUpperCase()}function _t(t,e,n){return Math.max(e,Math.min(n,t))}function Mt(t,e){return(t%e+e)%e}function bt(t,e,n){return(1-n)*t+n*e}function wt(t){return 0==(t&t-1)&&0!==t}function St(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function Tt(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}var Et=Object.freeze({__proto__:null,DEG2RAD:vt,RAD2DEG:yt,generateUUID:xt,clamp:_t,euclideanModulo:Mt,mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},inverseLerp:function(t,e,n){return t!==e?(n-t)/(e-t):0},lerp:bt,damp:function(t,e,n,i){return bt(t,e,1-Math.exp(-n*i))},pingpong:function(t,e=1){return e-Math.abs(Mt(t,2*e)-e)},smoothstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*(3-2*t)},smootherstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},seededRandom:function(t){return void 0!==t&&(gt=t%2147483647),gt=16807*gt%2147483647,(gt-1)/2147483646},degToRad:function(t){return t*vt},radToDeg:function(t){return t*yt},isPowerOfTwo:wt,ceilPowerOfTwo:St,floorPowerOfTwo:Tt,setQuaternionFromProperEuler:function(t,e,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),c=s((e+i)/2),h=a((e+i)/2),u=s((e-i)/2),d=a((e-i)/2),p=s((i-e)/2),m=a((i-e)/2);switch(r){case"XYX":t.set(o*h,l*u,l*d,o*c);break;case"YZY":t.set(l*d,o*h,l*u,o*c);break;case"ZXZ":t.set(l*u,l*d,o*h,o*c);break;case"XZX":t.set(o*h,l*m,l*p,o*c);break;case"YXY":t.set(l*p,o*h,l*m,o*c);break;case"ZYZ":t.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}});class At{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,e){return void 0!==e?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(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,e){return void 0!==e?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(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=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}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=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(){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}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,n){return void 0!==n&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute()."),this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const n=Math.cos(e),i=Math.sin(e),r=this.x-t.x,s=this.y-t.y;return this.x=r*n-s*i+t.x,this.y=r*i+s*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}At.prototype.isVector2=!0;class Rt{constructor(){this.elements=[1,0,0,0,1,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}set(t,e,n,i,r,s,a,o,l){const c=this.elements;return c[0]=t,c[1]=i,c[2]=a,c[3]=e,c[4]=r,c[5]=o,c[6]=n,c[7]=s,c[8]=l,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,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],c=n[4],h=n[7],u=n[2],d=n[5],p=n[8],m=i[0],f=i[3],g=i[6],v=i[1],y=i[4],x=i[7],_=i[2],M=i[5],b=i[8];return r[0]=s*m+a*v+o*_,r[3]=s*f+a*y+o*M,r[6]=s*g+a*x+o*b,r[1]=l*m+c*v+h*_,r[4]=l*f+c*y+h*M,r[7]=l*g+c*x+h*b,r[2]=u*m+d*v+p*_,r[5]=u*f+d*y+p*M,r[8]=u*g+d*x+p*b,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],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8];return e*s*c-e*a*l-n*r*c+n*a*o+i*r*l-i*s*o}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=c*s-a*l,u=a*o-c*r,d=l*r-s*o,p=e*h+n*u+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=h*m,t[1]=(i*l-c*n)*m,t[2]=(a*n-i*s)*m,t[3]=u*m,t[4]=(c*e-i*o)*m,t[5]=(i*r-a*e)*m,t[6]=d*m,t[7]=(n*o-l*e)*m,t[8]=(s*e-n*r)*m,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,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+t,-i*l,i*o,-i*(-l*s+o*a)+a+e,0,0,1),this}scale(t,e){const n=this.elements;return n[0]*=t,n[3]*=t,n[6]*=t,n[1]*=e,n[4]*=e,n[7]*=e,this}rotate(t){const e=Math.cos(t),n=Math.sin(t),i=this.elements,r=i[0],s=i[3],a=i[6],o=i[1],l=i[4],c=i[7];return i[0]=e*r+n*o,i[3]=e*s+n*l,i[6]=e*a+n*c,i[1]=-n*r+e*o,i[4]=-n*s+e*l,i[7]=-n*a+e*c,this}translate(t,e){const n=this.elements;return n[0]+=t*n[2],n[3]+=t*n[5],n[6]+=t*n[8],n[1]+=e*n[2],n[4]+=e*n[5],n[7]+=e*n[8],this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<9;t++)if(e[t]!==n[t])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)}}function Lt(t){for(let e=t.length-1;e>=0;--e)if(t[e]>65535)return!0;return!1}Rt.prototype.isMatrix3=!0;const Ct={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function Pt(t,e){return new Ct[t](e)}function Dt(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}const It={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},Nt={h:0,s:0,l:0},Bt={h:0,s:0,l:0};function zt(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+6*(e-t)*(2/3-n):t}function Ot(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function Ft(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}class Ut{constructor(t,e,n){return void 0===e&&void 0===n?this.set(t):this.setRGB(t,e,n)}set(t){return t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t),this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,this}setRGB(t,e,n){return this.r=t,this.g=e,this.b=n,this}setHSL(t,e,n){if(t=Mt(t,1),e=_t(e,0,1),n=_t(n,0,1),0===e)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+e):n+e-n*e,r=2*n-i;this.r=zt(r,i,t+1/3),this.g=zt(r,i,t),this.b=zt(r,i,t-1/3)}return this}setStyle(t){function e(e){void 0!==e&&parseFloat(e)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let n;if(n=/^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(t)){let t;const i=n[1],r=n[2];switch(i){case"rgb":case"rgba":if(t=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return this.r=Math.min(255,parseInt(t[1],10))/255,this.g=Math.min(255,parseInt(t[2],10))/255,this.b=Math.min(255,parseInt(t[3],10))/255,e(t[4]),this;if(t=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return this.r=Math.min(100,parseInt(t[1],10))/100,this.g=Math.min(100,parseInt(t[2],10))/100,this.b=Math.min(100,parseInt(t[3],10))/100,e(t[4]),this;break;case"hsl":case"hsla":if(t=/^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r)){const n=parseFloat(t[1])/360,i=parseInt(t[2],10)/100,r=parseInt(t[3],10)/100;return e(t[4]),this.setHSL(n,i,r)}}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(t)){const t=n[1],e=t.length;if(3===e)return this.r=parseInt(t.charAt(0)+t.charAt(0),16)/255,this.g=parseInt(t.charAt(1)+t.charAt(1),16)/255,this.b=parseInt(t.charAt(2)+t.charAt(2),16)/255,this;if(6===e)return this.r=parseInt(t.charAt(0)+t.charAt(1),16)/255,this.g=parseInt(t.charAt(2)+t.charAt(3),16)/255,this.b=parseInt(t.charAt(4)+t.charAt(5),16)/255,this}return t&&t.length>0?this.setColorName(t):this}setColorName(t){const e=It[t.toLowerCase()];return void 0!==e?this.setHex(e):console.warn("THREE.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=Ot(t.r),this.g=Ot(t.g),this.b=Ot(t.b),this}copyLinearToSRGB(t){return this.r=Ft(t.r),this.g=Ft(t.g),this.b=Ft(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}getHSL(t){const e=this.r,n=this.g,i=this.b,r=Math.max(e,n,i),s=Math.min(e,n,i);let a,o;const l=(s+r)/2;if(s===r)a=0,o=0;else{const t=r-s;switch(o=l<=.5?t/(r+s):t/(2-r-s),r){case e:a=(n-i)/t+(n<i?6:0);break;case n:a=(i-e)/t+2;break;case i:a=(e-n)/t+4}a/=6}return t.h=a,t.s=o,t.l=l,t}getStyle(){return"rgb("+(255*this.r|0)+","+(255*this.g|0)+","+(255*this.b|0)+")"}offsetHSL(t,e,n){return this.getHSL(Nt),Nt.h+=t,Nt.s+=e,Nt.l+=n,this.setHSL(Nt.h,Nt.s,Nt.l),this}add(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this}addColors(t,e){return this.r=t.r+e.r,this.g=t.g+e.g,this.b=t.b+e.b,this}addScalar(t){return this.r+=t,this.g+=t,this.b+=t,this}sub(t){return this.r=Math.max(0,this.r-t.r),this.g=Math.max(0,this.g-t.g),this.b=Math.max(0,this.b-t.b),this}multiply(t){return this.r*=t.r,this.g*=t.g,this.b*=t.b,this}multiplyScalar(t){return this.r*=t,this.g*=t,this.b*=t,this}lerp(t,e){return this.r+=(t.r-this.r)*e,this.g+=(t.g-this.g)*e,this.b+=(t.b-this.b)*e,this}lerpColors(t,e,n){return this.r=t.r+(e.r-t.r)*n,this.g=t.g+(e.g-t.g)*n,this.b=t.b+(e.b-t.b)*n,this}lerpHSL(t,e){this.getHSL(Nt),t.getHSL(Bt);const n=bt(Nt.h,Bt.h,e),i=bt(Nt.s,Bt.s,e),r=bt(Nt.l,Bt.l,e);return this.setHSL(n,i,r),this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}fromArray(t,e=0){return this.r=t[e],this.g=t[e+1],this.b=t[e+2],this}toArray(t=[],e=0){return t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,t}fromBufferAttribute(t,e){return this.r=t.getX(e),this.g=t.getY(e),this.b=t.getZ(e),!0===t.normalized&&(this.r/=255,this.g/=255,this.b/=255),this}toJSON(){return this.getHex()}}let Ht;Ut.NAMES=It,Ut.prototype.isColor=!0,Ut.prototype.r=1,Ut.prototype.g=1,Ut.prototype.b=1;class Gt{static getDataURL(t){if(/^data:/i.test(t.src))return t.src;if("undefined"==typeof HTMLCanvasElement)return t.src;let e;if(t instanceof HTMLCanvasElement)e=t;else{void 0===Ht&&(Ht=Dt("canvas")),Ht.width=t.width,Ht.height=t.height;const n=Ht.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),e=Ht}return e.width>2048||e.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",t),e.toDataURL("image/jpeg",.6)):e.toDataURL("image/png")}static sRGBToLinear(t){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const e=Dt("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),r=i.data;for(let t=0;t<r.length;t++)r[t]=255*Ot(r[t]/255);return n.putImageData(i,0,0),e}if(t.data){const e=t.data.slice(0);for(let t=0;t<e.length;t++)e instanceof Uint8Array||e instanceof Uint8ClampedArray?e[t]=Math.floor(255*Ot(e[t]/255)):e[t]=Ot(e[t]);return{data:e,width:t.width,height:t.height}}return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),t}}let kt=0;class Vt extends mt{constructor(t=Vt.DEFAULT_IMAGE,e=Vt.DEFAULT_MAPPING,n=1001,i=1001,r=1006,s=1008,a=1023,o=1009,l=1,c=3e3){super(),Object.defineProperty(this,"id",{value:kt++}),this.uuid=xt(),this.name="",this.image=t,this.mipmaps=[],this.mapping=e,this.wrapS=n,this.wrapT=i,this.magFilter=r,this.minFilter=s,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new At(0,0),this.repeat=new At(1,1),this.center=new At(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Rt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.encoding=c,this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.needsPMREMUpdate=!1}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return(new this.constructor).copy(this)}copy(t){return this.name=t.name,this.image=t.image,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,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.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.encoding=t.encoding,this.userData=JSON.parse(JSON.stringify(t.userData)),this}toJSON(t){const e=void 0===t||"string"==typeof t;if(!e&&void 0!==t.textures[this.uuid])return t.textures[this.uuid];const n={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,type:this.type,encoding:this.encoding,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};if(void 0!==this.image){const i=this.image;if(void 0===i.uuid&&(i.uuid=xt()),!e&&void 0===t.images[i.uuid]){let e;if(Array.isArray(i)){e=[];for(let t=0,n=i.length;t<n;t++)i[t].isDataTexture?e.push(Wt(i[t].image)):e.push(Wt(i[t]))}else e=Wt(i);t.images[i.uuid]={uuid:i.uuid,url:e}}n.image=i.uuid}return"{}"!==JSON.stringify(this.userData)&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==i)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case h:t.x=t.x-Math.floor(t.x);break;case u:t.x=t.x<0?0:1;break;case d:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case h:t.y=t.y-Math.floor(t.y);break;case u:t.y=t.y<0?0:1;break;case d:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&this.version++}}function Wt(t){return"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap?Gt.getDataURL(t):t.data?{data:Array.prototype.slice.call(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}Vt.DEFAULT_IMAGE=void 0,Vt.DEFAULT_MAPPING=i,Vt.prototype.isTexture=!0;class jt{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=void 0!==t.w?t.w:1,this}add(t,e){return void 0!==e?(console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(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,e){return void 0!==e?(console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(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,r=this.w,s=t.elements;return this.x=s[0]*e+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*e+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*e+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*e+s[7]*n+s[11]*i+s[15]*r,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,r;const s=.01,a=.1,o=t.elements,l=o[0],c=o[4],h=o[8],u=o[1],d=o[5],p=o[9],m=o[2],f=o[6],g=o[10];if(Math.abs(c-u)<s&&Math.abs(h-m)<s&&Math.abs(p-f)<s){if(Math.abs(c+u)<a&&Math.abs(h+m)<a&&Math.abs(p+f)<a&&Math.abs(l+d+g-3)<a)return this.set(1,0,0,0),this;e=Math.PI;const t=(l+1)/2,o=(d+1)/2,v=(g+1)/2,y=(c+u)/4,x=(h+m)/4,_=(p+f)/4;return t>o&&t>v?t<s?(n=0,i=.707106781,r=.707106781):(n=Math.sqrt(t),i=y/n,r=x/n):o>v?o<s?(n=.707106781,i=0,r=.707106781):(i=Math.sqrt(o),n=y/i,r=_/i):v<s?(n=.707106781,i=.707106781,r=0):(r=Math.sqrt(v),n=x/r,i=_/r),this.set(n,i,r,e),this}let v=Math.sqrt((f-p)*(f-p)+(h-m)*(h-m)+(u-c)*(u-c));return Math.abs(v)<.001&&(v=1),this.x=(f-p)/v,this.y=(h-m)/v,this.z=(u-c)/v,this.w=Math.acos((l+d+g-1)/2),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=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}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=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(){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,n){return void 0!==n&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute()."),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}}jt.prototype.isVector4=!0;class qt extends mt{constructor(t,e,n={}){super(),this.width=t,this.height=e,this.depth=1,this.scissor=new jt(0,0,t,e),this.scissorTest=!1,this.viewport=new jt(0,0,t,e),this.texture=new Vt(void 0,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.encoding),this.texture.isRenderTargetTexture=!0,this.texture.image={width:t,height:e,depth:1},this.texture.generateMipmaps=void 0!==n.generateMipmaps&&n.generateMipmaps,this.texture.internalFormat=void 0!==n.internalFormat?n.internalFormat:null,this.texture.minFilter=void 0!==n.minFilter?n.minFilter:g,this.depthBuffer=void 0===n.depthBuffer||n.depthBuffer,this.stencilBuffer=void 0!==n.stencilBuffer&&n.stencilBuffer,this.depthTexture=void 0!==n.depthTexture?n.depthTexture:null}setTexture(t){t.image={width:this.width,height:this.height,depth:this.depth},this.texture=t}setSize(t,e,n=1){this.width===t&&this.height===e&&this.depth===n||(this.width=t,this.height=e,this.depth=n,this.texture.image.width=t,this.texture.image.height=e,this.texture.image.depth=n,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){return this.width=t.width,this.height=t.height,this.depth=t.depth,this.viewport.copy(t.viewport),this.texture=t.texture.clone(),this.texture.image=Object.assign({},t.texture.image),this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,this.depthTexture=t.depthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}qt.prototype.isWebGLRenderTarget=!0;class Xt extends qt{constructor(t,e,n){super(t,e);const i=this.texture;this.texture=[];for(let t=0;t<n;t++)this.texture[t]=i.clone()}setSize(t,e,n=1){if(this.width!==t||this.height!==e||this.depth!==n){this.width=t,this.height=e,this.depth=n;for(let i=0,r=this.texture.length;i<r;i++)this.texture[i].image.width=t,this.texture[i].image.height=e,this.texture[i].image.depth=n;this.dispose()}return this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e),this}copy(t){this.dispose(),this.width=t.width,this.height=t.height,this.depth=t.depth,this.viewport.set(0,0,this.width,this.height),this.scissor.set(0,0,this.width,this.height),this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,this.depthTexture=t.depthTexture,this.texture.length=0;for(let e=0,n=t.texture.length;e<n;e++)this.texture[e]=t.texture[e].clone();return this}}Xt.prototype.isWebGLMultipleRenderTargets=!0;class Jt extends qt{constructor(t,e,n={}){super(t,e,n),this.samples=4,this.ignoreDepthForMultisampleCopy=void 0===n.ignoreDepth||n.ignoreDepth,this.useRenderToTexture=void 0!==n.useRenderToTexture&&n.useRenderToTexture,this.useRenderbuffer=!1===this.useRenderToTexture}copy(t){return super.copy.call(this,t),this.samples=t.samples,this.useRenderToTexture=t.useRenderToTexture,this.useRenderbuffer=t.useRenderbuffer,this}}Jt.prototype.isWebGLMultisampleRenderTarget=!0;class Yt{constructor(t=0,e=0,n=0,i=1){this._x=t,this._y=e,this._z=n,this._w=i}static slerp(t,e,n,i){return console.warn("THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead."),n.slerpQuaternions(t,e,i)}static slerpFlat(t,e,n,i,r,s,a){let o=n[i+0],l=n[i+1],c=n[i+2],h=n[i+3];const u=r[s+0],d=r[s+1],p=r[s+2],m=r[s+3];if(0===a)return t[e+0]=o,t[e+1]=l,t[e+2]=c,void(t[e+3]=h);if(1===a)return t[e+0]=u,t[e+1]=d,t[e+2]=p,void(t[e+3]=m);if(h!==m||o!==u||l!==d||c!==p){let t=1-a;const e=o*u+l*d+c*p+h*m,n=e>=0?1:-1,i=1-e*e;if(i>Number.EPSILON){const r=Math.sqrt(i),s=Math.atan2(r,e*n);t=Math.sin(t*s)/r,a=Math.sin(a*s)/r}const r=a*n;if(o=o*t+u*r,l=l*t+d*r,c=c*t+p*r,h=h*t+m*r,t===1-a){const t=1/Math.sqrt(o*o+l*l+c*c+h*h);o*=t,l*=t,c*=t,h*=t}}t[e]=o,t[e+1]=l,t[e+2]=c,t[e+3]=h}static multiplyQuaternionsFlat(t,e,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],c=n[i+3],h=r[s],u=r[s+1],d=r[s+2],p=r[s+3];return t[e]=a*p+c*h+o*d-l*u,t[e+1]=o*p+c*u+l*h-a*d,t[e+2]=l*p+c*d+a*u-o*h,t[e+3]=c*p-a*h-o*u-l*d,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){if(!t||!t.isEuler)throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");const n=t._x,i=t._y,r=t._z,s=t._order,a=Math.cos,o=Math.sin,l=a(n/2),c=a(i/2),h=a(r/2),u=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"YXZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"ZXY":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"ZYX":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"YZX":this._x=u*c*h+l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h-u*d*p;break;case"XZY":this._x=u*c*h-l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h+u*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!1!==e&&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],r=e[8],s=e[1],a=e[5],o=e[9],l=e[2],c=e[6],h=e[10],u=n+a+h;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(c-o)*t,this._y=(r-l)*t,this._z=(s-i)*t}else if(n>a&&n>h){const t=2*Math.sqrt(1+n-a-h);this._w=(c-o)/t,this._x=.25*t,this._y=(i+s)/t,this._z=(r+l)/t}else if(a>h){const t=2*Math.sqrt(1+a-n-h);this._w=(r-l)/t,this._x=(i+s)/t,this._y=.25*t,this._z=(o+c)/t}else{const t=2*Math.sqrt(1+h-n-a);this._w=(s-i)/t,this._x=(r+l)/t,this._y=(o+c)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return n<Number.EPSILON?(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(_t(this.dot(t),-1,1)))}rotateTowards(t,e){const n=this.angleTo(t);if(0===n)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 0===t?(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,e){return void 0!==e?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const n=t._x,i=t._y,r=t._z,s=t._w,a=e._x,o=e._y,l=e._z,c=e._w;return this._x=n*c+s*a+i*l-r*o,this._y=i*c+s*o+r*a-n*l,this._z=r*c+s*l+n*o-i*a,this._w=s*c-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const n=this._x,i=this._y,r=this._z,s=this._w;let a=s*t._w+n*t._x+i*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=s,this._x=n,this._y=i,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const t=1-e;return this._w=t*s+e*this._w,this._x=t*n+e*this._x,this._y=t*i+e*this._y,this._z=t*r+e*this._z,this.normalize(),this._onChangeCallback(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),h=Math.sin((1-e)*c)/l,u=Math.sin(e*c)/l;return this._w=s*h+this._w*u,this._x=n*h+this._x*u,this._y=i*h+this._y*u,this._z=r*h+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,n){return this.copy(t).slerp(e,n)}random(){const t=Math.random(),e=Math.sqrt(1-t),n=Math.sqrt(t),i=2*Math.PI*Math.random(),r=2*Math.PI*Math.random();return this.set(e*Math.cos(i),n*Math.sin(r),n*Math.cos(r),e*Math.sin(i))}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}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}}Yt.prototype.isQuaternion=!0;class Zt{constructor(t=0,e=0,n=0){this.x=t,this.y=e,this.z=n}set(t,e,n){return void 0===n&&(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,e){return void 0!==e?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(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,e){return void 0!==e?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(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,e){return void 0!==e?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(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 t&&t.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),this.applyQuaternion(Qt.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Qt.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*i,this.y=r[1]*e+r[4]*n+r[7]*i,this.z=r[2]*e+r[5]*n+r[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=t.elements,s=1/(r[3]*e+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*e+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*e+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(t){const e=this.x,n=this.y,i=this.z,r=t.x,s=t.y,a=t.z,o=t.w,l=o*e+s*i-a*n,c=o*n+a*e-r*i,h=o*i+r*n-s*e,u=-r*e-s*n-a*i;return this.x=l*o+u*-r+c*-a-h*-s,this.y=c*o+u*-s+h*-r-l*-a,this.z=h*o+u*-a+l*-s-c*-r,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,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*i,this.y=r[1]*e+r[5]*n+r[9]*i,this.z=r[2]*e+r[6]*n+r[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=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}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=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(){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,e){return void 0!==e?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e)):this.crossVectors(this,t)}crossVectors(t,e){const n=t.x,i=t.y,r=t.z,s=e.x,a=e.y,o=e.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Kt.copy(this).projectOnVector(t),this.sub(Kt)}reflect(t){return this.sub(Kt.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(_t(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,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}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,n){return void 0!==n&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute()."),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=2*(Math.random()-.5),e=Math.random()*Math.PI*2,n=Math.sqrt(1-t**2);return this.x=n*Math.cos(e),this.y=n*Math.sin(e),this.z=t,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}Zt.prototype.isVector3=!0;const Kt=new Zt,Qt=new Yt;class $t{constructor(t=new Zt(1/0,1/0,1/0),e=new Zt(-1/0,-1/0,-1/0)){this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){let e=1/0,n=1/0,i=1/0,r=-1/0,s=-1/0,a=-1/0;for(let o=0,l=t.length;o<l;o+=3){const l=t[o],c=t[o+1],h=t[o+2];l<e&&(e=l),c<n&&(n=c),h<i&&(i=h),l>r&&(r=l),c>s&&(s=c),h>a&&(a=h)}return this.min.set(e,n,i),this.max.set(r,s,a),this}setFromBufferAttribute(t){let e=1/0,n=1/0,i=1/0,r=-1/0,s=-1/0,a=-1/0;for(let o=0,l=t.count;o<l;o++){const l=t.getX(o),c=t.getY(o),h=t.getZ(o);l<e&&(e=l),c<n&&(n=c),h<i&&(i=h),l>r&&(r=l),c>s&&(s=c),h>a&&(a=h)}return this.min.set(e,n,i),this.max.set(r,s,a),this}setFromPoints(t){this.makeEmpty();for(let e=0,n=t.length;e<n;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const n=ee.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(n),this.max.copy(t).add(n),this}setFromObject(t,e=!1){return this.makeEmpty(),this.expandByObject(t,e)}clone(){return(new this.constructor).copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(t){return this.isEmpty()?t.set(0,0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}expandByObject(t,e=!1){t.updateWorldMatrix(!1,!1);const n=t.geometry;if(void 0!==n)if(e&&null!=n.attributes&&void 0!==n.attributes.position){const e=n.attributes.position;for(let n=0,i=e.count;n<i;n++)ee.fromBufferAttribute(e,n).applyMatrix4(t.matrixWorld),this.expandByPoint(ee)}else null===n.boundingBox&&n.computeBoundingBox(),ne.copy(n.boundingBox),ne.applyMatrix4(t.matrixWorld),this.union(ne);const i=t.children;for(let t=0,n=i.length;t<n;t++)this.expandByObject(i[t],e);return this}containsPoint(t){return!(t.x<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,ee),ee.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(ce),he.subVectors(this.max,ce),ie.subVectors(t.a,ce),re.subVectors(t.b,ce),se.subVectors(t.c,ce),ae.subVectors(re,ie),oe.subVectors(se,re),le.subVectors(ie,se);let e=[0,-ae.z,ae.y,0,-oe.z,oe.y,0,-le.z,le.y,ae.z,0,-ae.x,oe.z,0,-oe.x,le.z,0,-le.x,-ae.y,ae.x,0,-oe.y,oe.x,0,-le.y,le.x,0];return!!pe(e,ie,re,se,he)&&(e=[1,0,0,0,1,0,0,0,1],!!pe(e,ie,re,se,he)&&(ue.crossVectors(ae,oe),e=[ue.x,ue.y,ue.z],pe(e,ie,re,se,he)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return ee.copy(t).clamp(this.min,this.max).sub(t).length()}getBoundingSphere(t){return this.getCenter(t.center),t.radius=.5*this.getSize(ee).length(),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()||(te[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),te[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),te[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),te[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),te[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),te[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),te[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),te[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(te)),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)}}$t.prototype.isBox3=!0;const te=[new Zt,new Zt,new Zt,new Zt,new Zt,new Zt,new Zt,new Zt],ee=new Zt,ne=new $t,ie=new Zt,re=new Zt,se=new Zt,ae=new Zt,oe=new Zt,le=new Zt,ce=new Zt,he=new Zt,ue=new Zt,de=new Zt;function pe(t,e,n,i,r){for(let s=0,a=t.length-3;s<=a;s+=3){de.fromArray(t,s);const a=r.x*Math.abs(de.x)+r.y*Math.abs(de.y)+r.z*Math.abs(de.z),o=e.dot(de),l=n.dot(de),c=i.dot(de);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const me=new $t,fe=new Zt,ge=new Zt,ve=new Zt;class ye{constructor(t=new Zt,e=-1){this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const n=this.center;void 0!==e?n.copy(e):me.setFromPoints(t).getCenter(n);let i=0;for(let e=0,r=t.length;e<r;e++)i=Math.max(i,n.distanceToSquared(t[e]));return this.radius=Math.sqrt(i),this}copy(t){return this.center.copy(t.center),this.radius=t.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(t){return t.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(t){return t.distanceTo(this.center)-this.radius}intersectsSphere(t){const e=this.radius+t.radius;return t.center.distanceToSquared(this.center)<=e*e}intersectsBox(t){return t.intersectsSphere(this)}intersectsPlane(t){return Math.abs(t.distanceToPoint(this.center))<=this.radius}clampPoint(t,e){const n=this.center.distanceToSquared(t);return e.copy(t),n>this.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){ve.subVectors(t,this.center);const e=ve.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),n=.5*(t-this.radius);this.center.add(ve.multiplyScalar(n/t)),this.radius+=n}return this}union(t){return!0===this.center.equals(t.center)?ge.set(0,0,1).multiplyScalar(t.radius):ge.subVectors(t.center,this.center).normalize().multiplyScalar(t.radius),this.expandByPoint(fe.copy(t.center).add(ge)),this.expandByPoint(fe.copy(t.center).sub(ge)),this}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const xe=new Zt,_e=new Zt,Me=new Zt,be=new Zt,we=new Zt,Se=new Zt,Te=new Zt;class Ee{constructor(t=new Zt,e=new Zt(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.direction).multiplyScalar(t).add(this.origin)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,xe)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.direction).multiplyScalar(n).add(this.origin)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=xe.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(xe.copy(this.direction).multiplyScalar(e).add(this.origin),xe.distanceToSquared(t))}distanceSqToSegment(t,e,n,i){_e.copy(t).add(e).multiplyScalar(.5),Me.copy(e).sub(t).normalize(),be.copy(this.origin).sub(_e);const r=.5*t.distanceTo(e),s=-this.direction.dot(Me),a=be.dot(this.direction),o=-be.dot(Me),l=be.lengthSq(),c=Math.abs(1-s*s);let h,u,d,p;if(c>0)if(h=s*o-a,u=s*a-o,p=r*c,h>=0)if(u>=-p)if(u<=p){const t=1/c;h*=t,u*=t,d=h*(h+s*u+2*a)+u*(s*h+u+2*o)+l}else u=r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u=-r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u<=-p?(h=Math.max(0,-(-s*r+a)),u=h>0?-r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l):u<=p?(h=0,u=Math.min(Math.max(-r,-o),r),d=u*(u+2*o)+l):(h=Math.max(0,-(s*r+a)),u=h>0?r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l);else u=s>0?-r:r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;return n&&n.copy(this.direction).multiplyScalar(h).add(this.origin),i&&i.copy(Me).multiplyScalar(u).add(_e),d}intersectSphere(t,e){xe.subVectors(t.center,this.origin);const n=xe.dot(this.direction),i=xe.dot(xe)-n*n,r=t.radius*t.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return a<0&&o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?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 null===n?null:this.at(n,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);if(0===e)return!0;return t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,i,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,u=this.origin;return l>=0?(n=(t.min.x-u.x)*l,i=(t.max.x-u.x)*l):(n=(t.max.x-u.x)*l,i=(t.min.x-u.x)*l),c>=0?(r=(t.min.y-u.y)*c,s=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,s=(t.min.y-u.y)*c),n>s||r>i?null:((r>n||n!=n)&&(n=r),(s<i||i!=i)&&(i=s),h>=0?(a=(t.min.z-u.z)*h,o=(t.max.z-u.z)*h):(a=(t.max.z-u.z)*h,o=(t.min.z-u.z)*h),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o<i||i!=i)&&(i=o),i<0?null:this.at(n>=0?n:i,e)))}intersectsBox(t){return null!==this.intersectBox(t,xe)}intersectTriangle(t,e,n,i,r){we.subVectors(e,t),Se.subVectors(n,t),Te.crossVectors(we,Se);let s,a=this.direction.dot(Te);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}be.subVectors(this.origin,t);const o=s*this.direction.dot(Se.crossVectors(be,Se));if(o<0)return null;const l=s*this.direction.dot(we.cross(be));if(l<0)return null;if(o+l>a)return null;const c=-s*be.dot(Te);return c<0?null:this.at(c/a,r)}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 Ae{constructor(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){const g=this.elements;return g[0]=t,g[4]=e,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=h,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=f,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new Ae).fromArray(this.elements)}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],e[9]=n[9],e[10]=n[10],e[11]=n[11],e[12]=n[12],e[13]=n[13],e[14]=n[14],e[15]=n[15],this}copyPosition(t){const e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,n=t.elements,i=1/Re.setFromMatrixColumn(t,0).length(),r=1/Re.setFromMatrixColumn(t,1).length(),s=1/Re.setFromMatrixColumn(t,2).length();return e[0]=n[0]*i,e[1]=n[1]*i,e[2]=n[2]*i,e[3]=0,e[4]=n[4]*r,e[5]=n[5]*r,e[6]=n[6]*r,e[7]=0,e[8]=n[8]*s,e[9]=n[9]*s,e[10]=n[10]*s,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){t&&t.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");const e=this.elements,n=t.x,i=t.y,r=t.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),c=Math.cos(r),h=Math.sin(r);if("XYZ"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=-o*h,e[8]=l,e[1]=n+i*l,e[5]=t-r*l,e[9]=-a*o,e[2]=r-t*l,e[6]=i+n*l,e[10]=s*o}else if("YXZ"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t+r*a,e[4]=i*a-n,e[8]=s*l,e[1]=s*h,e[5]=s*c,e[9]=-a,e[2]=n*a-i,e[6]=r+t*a,e[10]=s*o}else if("ZXY"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t-r*a,e[4]=-s*h,e[8]=i+n*a,e[1]=n+i*a,e[5]=s*c,e[9]=r-t*a,e[2]=-s*l,e[6]=a,e[10]=s*o}else if("ZYX"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=i*l-n,e[8]=t*l+r,e[1]=o*h,e[5]=r*l+t,e[9]=n*l-i,e[2]=-l,e[6]=a*o,e[10]=s*o}else if("YZX"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=r-t*h,e[8]=i*h+n,e[1]=h,e[5]=s*c,e[9]=-a*c,e[2]=-l*c,e[6]=n*h+i,e[10]=t-r*h}else if("XZY"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=-h,e[8]=l*c,e[1]=t*h+r,e[5]=s*c,e[9]=n*h-i,e[2]=i*h-n,e[6]=a*c,e[10]=r*h+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(Ce,t,Pe)}lookAt(t,e,n){const i=this.elements;return Ne.subVectors(t,e),0===Ne.lengthSq()&&(Ne.z=1),Ne.normalize(),De.crossVectors(n,Ne),0===De.lengthSq()&&(1===Math.abs(n.z)?Ne.x+=1e-4:Ne.z+=1e-4,Ne.normalize(),De.crossVectors(n,Ne)),De.normalize(),Ie.crossVectors(Ne,De),i[0]=De.x,i[4]=Ie.x,i[8]=Ne.x,i[1]=De.y,i[5]=Ie.y,i[9]=Ne.y,i[2]=De.z,i[6]=Ie.z,i[10]=Ne.z,this}multiply(t,e){return void 0!==e?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],c=n[1],h=n[5],u=n[9],d=n[13],p=n[2],m=n[6],f=n[10],g=n[14],v=n[3],y=n[7],x=n[11],_=n[15],M=i[0],b=i[4],w=i[8],S=i[12],T=i[1],E=i[5],A=i[9],R=i[13],L=i[2],C=i[6],P=i[10],D=i[14],I=i[3],N=i[7],B=i[11],z=i[15];return r[0]=s*M+a*T+o*L+l*I,r[4]=s*b+a*E+o*C+l*N,r[8]=s*w+a*A+o*P+l*B,r[12]=s*S+a*R+o*D+l*z,r[1]=c*M+h*T+u*L+d*I,r[5]=c*b+h*E+u*C+d*N,r[9]=c*w+h*A+u*P+d*B,r[13]=c*S+h*R+u*D+d*z,r[2]=p*M+m*T+f*L+g*I,r[6]=p*b+m*E+f*C+g*N,r[10]=p*w+m*A+f*P+g*B,r[14]=p*S+m*R+f*D+g*z,r[3]=v*M+y*T+x*L+_*I,r[7]=v*b+y*E+x*C+_*N,r[11]=v*w+y*A+x*P+_*B,r[15]=v*S+y*R+x*D+_*z,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[4],i=t[8],r=t[12],s=t[1],a=t[5],o=t[9],l=t[13],c=t[2],h=t[6],u=t[10],d=t[14];return t[3]*(+r*o*h-i*l*h-r*a*u+n*l*u+i*a*d-n*o*d)+t[7]*(+e*o*d-e*l*u+r*s*u-i*s*d+i*l*c-r*o*c)+t[11]*(+e*l*h-e*a*d-r*s*h+n*s*d+r*a*c-n*l*c)+t[15]*(-i*a*c-e*o*h+e*a*u+i*s*h-n*s*u+n*o*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,n){const i=this.elements;return t.isVector3?(i[12]=t.x,i[13]=t.y,i[14]=t.z):(i[12]=t,i[13]=e,i[14]=n),this}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=t[9],u=t[10],d=t[11],p=t[12],m=t[13],f=t[14],g=t[15],v=h*f*l-m*u*l+m*o*d-a*f*d-h*o*g+a*u*g,y=p*u*l-c*f*l-p*o*d+s*f*d+c*o*g-s*u*g,x=c*m*l-p*h*l+p*a*d-s*m*d-c*a*g+s*h*g,_=p*h*o-c*m*o-p*a*u+s*m*u+c*a*f-s*h*f,M=e*v+n*y+i*x+r*_;if(0===M)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const b=1/M;return t[0]=v*b,t[1]=(m*u*r-h*f*r-m*i*d+n*f*d+h*i*g-n*u*g)*b,t[2]=(a*f*r-m*o*r+m*i*l-n*f*l-a*i*g+n*o*g)*b,t[3]=(h*o*r-a*u*r-h*i*l+n*u*l+a*i*d-n*o*d)*b,t[4]=y*b,t[5]=(c*f*r-p*u*r+p*i*d-e*f*d-c*i*g+e*u*g)*b,t[6]=(p*o*r-s*f*r-p*i*l+e*f*l+s*i*g-e*o*g)*b,t[7]=(s*u*r-c*o*r+c*i*l-e*u*l-s*i*d+e*o*d)*b,t[8]=x*b,t[9]=(p*h*r-c*m*r-p*n*d+e*m*d+c*n*g-e*h*g)*b,t[10]=(s*m*r-p*a*r+p*n*l-e*m*l-s*n*g+e*a*g)*b,t[11]=(c*a*r-s*h*r-c*n*l+e*h*l+s*n*d-e*a*d)*b,t[12]=_*b,t[13]=(c*m*i-p*h*i+p*n*u-e*m*u-c*n*f+e*h*f)*b,t[14]=(p*a*i-s*m*i-p*n*o+e*m*o+s*n*f-e*a*f)*b,t[15]=(s*h*i-c*a*i+c*n*o-e*h*o-s*n*u+e*a*u)*b,this}scale(t){const e=this.elements,n=t.x,i=t.y,r=t.z;return e[0]*=n,e[4]*=i,e[8]*=r,e[1]*=n,e[5]*=i,e[9]*=r,e[2]*=n,e[6]*=i,e[10]*=r,e[3]*=n,e[7]*=i,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],n=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],i=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,n,i))}makeTranslation(t,e,n){return this.set(1,0,0,t,0,1,0,e,0,0,1,n,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),n=Math.sin(t);return this.set(1,0,0,0,0,e,-n,0,0,n,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,0,n,0,0,1,0,0,-n,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,0,n,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const n=Math.cos(e),i=Math.sin(e),r=1-n,s=t.x,a=t.y,o=t.z,l=r*s,c=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,c*a+n,c*o-i*s,0,l*o-i*a,c*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(t,e,n){return this.set(t,0,0,0,0,e,0,0,0,0,n,0,0,0,0,1),this}makeShear(t,e,n,i,r,s){return this.set(1,n,r,0,t,1,s,0,e,i,1,0,0,0,0,1),this}compose(t,e,n){const i=this.elements,r=e._x,s=e._y,a=e._z,o=e._w,l=r+r,c=s+s,h=a+a,u=r*l,d=r*c,p=r*h,m=s*c,f=s*h,g=a*h,v=o*l,y=o*c,x=o*h,_=n.x,M=n.y,b=n.z;return i[0]=(1-(m+g))*_,i[1]=(d+x)*_,i[2]=(p-y)*_,i[3]=0,i[4]=(d-x)*M,i[5]=(1-(u+g))*M,i[6]=(f+v)*M,i[7]=0,i[8]=(p+y)*b,i[9]=(f-v)*b,i[10]=(1-(u+m))*b,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}decompose(t,e,n){const i=this.elements;let r=Re.set(i[0],i[1],i[2]).length();const s=Re.set(i[4],i[5],i[6]).length(),a=Re.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),t.x=i[12],t.y=i[13],t.z=i[14],Le.copy(this);const o=1/r,l=1/s,c=1/a;return Le.elements[0]*=o,Le.elements[1]*=o,Le.elements[2]*=o,Le.elements[4]*=l,Le.elements[5]*=l,Le.elements[6]*=l,Le.elements[8]*=c,Le.elements[9]*=c,Le.elements[10]*=c,e.setFromRotationMatrix(Le),n.x=r,n.y=s,n.z=a,this}makePerspective(t,e,n,i,r,s){void 0===s&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");const a=this.elements,o=2*r/(e-t),l=2*r/(n-i),c=(e+t)/(e-t),h=(n+i)/(n-i),u=-(s+r)/(s-r),d=-2*s*r/(s-r);return a[0]=o,a[4]=0,a[8]=c,a[12]=0,a[1]=0,a[5]=l,a[9]=h,a[13]=0,a[2]=0,a[6]=0,a[10]=u,a[14]=d,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(t,e,n,i,r,s){const a=this.elements,o=1/(e-t),l=1/(n-i),c=1/(s-r),h=(e+t)*o,u=(n+i)*l,d=(s+r)*c;return a[0]=2*o,a[4]=0,a[8]=0,a[12]=-h,a[1]=0,a[5]=2*l,a[9]=0,a[13]=-u,a[2]=0,a[6]=0,a[10]=-2*c,a[14]=-d,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<16;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<16;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[e+9]=n[9],t[e+10]=n[10],t[e+11]=n[11],t[e+12]=n[12],t[e+13]=n[13],t[e+14]=n[14],t[e+15]=n[15],t}}Ae.prototype.isMatrix4=!0;const Re=new Zt,Le=new Ae,Ce=new Zt(0,0,0),Pe=new Zt(1,1,1),De=new Zt,Ie=new Zt,Ne=new Zt,Be=new Ae,ze=new Yt;class Oe{constructor(t=0,e=0,n=0,i=Oe.DefaultOrder){this._x=t,this._y=e,this._z=n,this._order=i}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 order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,n,i=this._order){return this._x=t,this._y=e,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,n=!0){const i=t.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],h=i[2],u=i[6],d=i[10];switch(e){case"XYZ":this._y=Math.asin(_t(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-_t(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,r),this._z=0);break;case"ZXY":this._x=Math.asin(_t(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-_t(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(_t(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-_t(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===n&&this._onChangeCallback(),this}setFromQuaternion(t,e,n){return Be.makeRotationFromQuaternion(t),this.setFromRotationMatrix(Be,e,n)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return ze.setFromEuler(this),this.setFromQuaternion(ze,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[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._order,t}toVector3(t){return t?t.set(this._x,this._y,this._z):new Zt(this._x,this._y,this._z)}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}}Oe.prototype.isEuler=!0,Oe.DefaultOrder="XYZ",Oe.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"];class Fe{constructor(){this.mask=1}set(t){this.mask=(1<<t|0)>>>0}enable(t){this.mask|=1<<t|0}enableAll(){this.mask=-1}toggle(t){this.mask^=1<<t|0}disable(t){this.mask&=~(1<<t|0)}disableAll(){this.mask=0}test(t){return 0!=(this.mask&t.mask)}isEnabled(t){return 0!=(this.mask&(1<<t|0))}}let Ue=0;const He=new Zt,Ge=new Yt,ke=new Ae,Ve=new Zt,We=new Zt,je=new Zt,qe=new Yt,Xe=new Zt(1,0,0),Je=new Zt(0,1,0),Ye=new Zt(0,0,1),Ze={type:"added"},Ke={type:"removed"};class Qe extends mt{constructor(){super(),Object.defineProperty(this,"id",{value:Ue++}),this.uuid=xt(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Qe.DefaultUp.clone();const t=new Zt,e=new Oe,n=new Yt,i=new Zt(1,1,1);e._onChange((function(){n.setFromEuler(e,!1)})),n._onChange((function(){e.setFromQuaternion(n,void 0,!1)})),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Ae},normalMatrix:{value:new Rt}}),this.matrix=new Ae,this.matrixWorld=new Ae,this.matrixAutoUpdate=Qe.DefaultMatrixAutoUpdate,this.matrixWorldNeedsUpdate=!1,this.layers=new Fe,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeRender(){}onAfterRender(){}applyMatrix4(t){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(t),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(t){return this.quaternion.premultiply(t),this}setRotationFromAxisAngle(t,e){this.quaternion.setFromAxisAngle(t,e)}setRotationFromEuler(t){this.quaternion.setFromEuler(t,!0)}setRotationFromMatrix(t){this.quaternion.setFromRotationMatrix(t)}setRotationFromQuaternion(t){this.quaternion.copy(t)}rotateOnAxis(t,e){return Ge.setFromAxisAngle(t,e),this.quaternion.multiply(Ge),this}rotateOnWorldAxis(t,e){return Ge.setFromAxisAngle(t,e),this.quaternion.premultiply(Ge),this}rotateX(t){return this.rotateOnAxis(Xe,t)}rotateY(t){return this.rotateOnAxis(Je,t)}rotateZ(t){return this.rotateOnAxis(Ye,t)}translateOnAxis(t,e){return He.copy(t).applyQuaternion(this.quaternion),this.position.add(He.multiplyScalar(e)),this}translateX(t){return this.translateOnAxis(Xe,t)}translateY(t){return this.translateOnAxis(Je,t)}translateZ(t){return this.translateOnAxis(Ye,t)}localToWorld(t){return t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return t.applyMatrix4(ke.copy(this.matrixWorld).invert())}lookAt(t,e,n){t.isVector3?Ve.copy(t):Ve.set(t,e,n);const i=this.parent;this.updateWorldMatrix(!0,!1),We.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?ke.lookAt(We,Ve,this.up):ke.lookAt(Ve,We,this.up),this.quaternion.setFromRotationMatrix(ke),i&&(ke.extractRotation(i.matrixWorld),Ge.setFromRotationMatrix(ke),this.quaternion.premultiply(Ge.invert()))}add(t){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return t===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",t),this):(t&&t.isObject3D?(null!==t.parent&&t.parent.remove(t),t.parent=this,this.children.push(t),t.dispatchEvent(Ze)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",t),this)}remove(t){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.remove(arguments[t]);return this}const e=this.children.indexOf(t);return-1!==e&&(t.parent=null,this.children.splice(e,1),t.dispatchEvent(Ke)),this}removeFromParent(){const t=this.parent;return null!==t&&t.remove(this),this}clear(){for(let t=0;t<this.children.length;t++){const e=this.children[t];e.parent=null,e.dispatchEvent(Ke)}return this.children.length=0,this}attach(t){return this.updateWorldMatrix(!0,!1),ke.copy(this.matrixWorld).invert(),null!==t.parent&&(t.parent.updateWorldMatrix(!0,!1),ke.multiply(t.parent.matrixWorld)),t.applyMatrix4(ke),this.add(t),t.updateWorldMatrix(!1,!0),this}getObjectById(t){return this.getObjectByProperty("id",t)}getObjectByName(t){return this.getObjectByProperty("name",t)}getObjectByProperty(t,e){if(this[t]===e)return this;for(let n=0,i=this.children.length;n<i;n++){const i=this.children[n].getObjectByProperty(t,e);if(void 0!==i)return i}}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(We,t,je),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(We,qe,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(e[8],e[9],e[10]).normalize()}raycast(){}traverse(t){t(this);const e=this.children;for(let n=0,i=e.length;n<i;n++)e[n].traverse(t)}traverseVisible(t){if(!1===this.visible)return;t(this);const e=this.children;for(let n=0,i=e.length;n<i;n++)e[n].traverseVisible(t)}traverseAncestors(t){const e=this.parent;null!==e&&(t(e),e.traverseAncestors(t))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||t)&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,t=!0);const e=this.children;for(let n=0,i=e.length;n<i;n++)e[n].updateMatrixWorld(t)}updateWorldMatrix(t,e){const n=this.parent;if(!0===t&&null!==n&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),!0===e){const t=this.children;for(let e=0,n=t.length;e<n;e++)t[e].updateWorldMatrix(!1,!0)}}toJSON(t){const e=void 0===t||"string"==typeof t,n={};e&&(t={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{}},n.metadata={version:4.5,type:"Object",generator:"Object3D.toJSON"});const i={};function r(e,n){return void 0===e[n.uuid]&&(e[n.uuid]=n.toJSON(t)),n.uuid}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),!0===this.castShadow&&(i.castShadow=!0),!0===this.receiveShadow&&(i.receiveShadow=!0),!1===this.visible&&(i.visible=!1),!1===this.frustumCulled&&(i.frustumCulled=!1),0!==this.renderOrder&&(i.renderOrder=this.renderOrder),"{}"!==JSON.stringify(this.userData)&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),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&&(i.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(t.geometries,this.geometry);const e=this.geometry.parameters;if(void 0!==e&&void 0!==e.shapes){const n=e.shapes;if(Array.isArray(n))for(let e=0,i=n.length;e<i;e++){const i=n[e];r(t.shapes,i)}else r(t.shapes,n)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(r(t.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const e=[];for(let n=0,i=this.material.length;n<i;n++)e.push(r(t.materials,this.material[n]));i.material=e}else i.material=r(t.materials,this.material);if(this.children.length>0){i.children=[];for(let e=0;e<this.children.length;e++)i.children.push(this.children[e].toJSON(t).object)}if(this.animations.length>0){i.animations=[];for(let e=0;e<this.animations.length;e++){const n=this.animations[e];i.animations.push(r(t.animations,n))}}if(e){const e=s(t.geometries),i=s(t.materials),r=s(t.textures),a=s(t.images),o=s(t.shapes),l=s(t.skeletons),c=s(t.animations);e.length>0&&(n.geometries=e),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),c.length>0&&(n.animations=c)}return n.object=i,n;function s(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}}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.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,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.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;e<t.children.length;e++){const n=t.children[e];this.add(n.clone())}return this}}Qe.DefaultUp=new Zt(0,1,0),Qe.DefaultMatrixAutoUpdate=!0,Qe.prototype.isObject3D=!0;const $e=new Zt,tn=new Zt,en=new Zt,nn=new Zt,rn=new Zt,sn=new Zt,an=new Zt,on=new Zt,ln=new Zt,cn=new Zt;class hn{constructor(t=new Zt,e=new Zt,n=new Zt){this.a=t,this.b=e,this.c=n}static getNormal(t,e,n,i){i.subVectors(n,e),$e.subVectors(t,e),i.cross($e);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(t,e,n,i,r){$e.subVectors(i,e),tn.subVectors(n,e),en.subVectors(t,e);const s=$e.dot($e),a=$e.dot(tn),o=$e.dot(en),l=tn.dot(tn),c=tn.dot(en),h=s*l-a*a;if(0===h)return r.set(-2,-1,-1);const u=1/h,d=(l*o-a*c)*u,p=(s*c-a*o)*u;return r.set(1-d-p,p,d)}static containsPoint(t,e,n,i){return this.getBarycoord(t,e,n,i,nn),nn.x>=0&&nn.y>=0&&nn.x+nn.y<=1}static getUV(t,e,n,i,r,s,a,o){return this.getBarycoord(t,e,n,i,nn),o.set(0,0),o.addScaledVector(r,nn.x),o.addScaledVector(s,nn.y),o.addScaledVector(a,nn.z),o}static isFrontFacing(t,e,n,i){return $e.subVectors(n,e),tn.subVectors(t,e),$e.cross(tn).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 $e.subVectors(this.c,this.b),tn.subVectors(this.a,this.b),.5*$e.cross(tn).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return hn.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return hn.getBarycoord(t,this.a,this.b,this.c,e)}getUV(t,e,n,i,r){return hn.getUV(t,this.a,this.b,this.c,e,n,i,r)}containsPoint(t){return hn.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return hn.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const n=this.a,i=this.b,r=this.c;let s,a;rn.subVectors(i,n),sn.subVectors(r,n),on.subVectors(t,n);const o=rn.dot(on),l=sn.dot(on);if(o<=0&&l<=0)return e.copy(n);ln.subVectors(t,i);const c=rn.dot(ln),h=sn.dot(ln);if(c>=0&&h<=c)return e.copy(i);const u=o*h-c*l;if(u<=0&&o>=0&&c<=0)return s=o/(o-c),e.copy(n).addScaledVector(rn,s);cn.subVectors(t,r);const d=rn.dot(cn),p=sn.dot(cn);if(p>=0&&d<=p)return e.copy(r);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(n).addScaledVector(sn,a);const f=c*p-d*h;if(f<=0&&h-c>=0&&d-p>=0)return an.subVectors(r,i),a=(h-c)/(h-c+(d-p)),e.copy(i).addScaledVector(an,a);const g=1/(f+m+u);return s=m*g,a=u*g,e.copy(n).addScaledVector(rn,s).addScaledVector(sn,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}let un=0;class dn extends mt{constructor(){super(),Object.defineProperty(this,"id",{value:un++}),this.uuid=xt(),this.name="",this.type="Material",this.fog=!0,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=n,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=ct,this.stencilZFail=ct,this.stencilZPass=ct,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.alphaWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(void 0!==t)for(const e in t){const n=t[e];if(void 0===n){console.warn("THREE.Material: '"+e+"' parameter is undefined.");continue}if("shading"===e){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===n;continue}const i=this[e];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[e]=n:console.warn("THREE."+this.type+": '"+e+"' is not a property of this material.")}}toJSON(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const n={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};function i(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(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.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,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).uuid),void 0!==this.attenuationDistance&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=this.transparent),n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.alphaWrite=this.alphaWrite,n.stencilWrite=this.stencilWrite,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaToCoverage&&(n.alphaToCoverage=this.alphaToCoverage),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=this.premultipliedAlpha),!0===this.wireframe&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=this.flatShading),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),"{}"!==JSON.stringify(this.userData)&&(n.userData=this.userData),e){const e=i(t.textures),r=i(t.images);e.length>0&&(n.textures=e),r.length>0&&(n.images=r)}return n}clone(){return(new this.constructor).copy(this)}copy(t){this.name=t.name,this.fog=t.fog,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.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(null!==e){const t=e.length;n=new Array(t);for(let i=0;i!==t;++i)n[i]=e[i].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.alphaWrite=t.alphaWrite,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.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,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){!0===t&&this.version++}}dn.prototype.isMaterial=!0;class pn extends dn{constructor(t){super(),this.type="MeshBasicMaterial",this.color=new Ut(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.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",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.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}}pn.prototype.isMeshBasicMaterial=!0;const mn=new Zt,fn=new At;class gn{constructor(t,e,n){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=!0===n,this.usage=ht,this.updateRange={offset:0,count:-1},this.version=0}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}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}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let i=0,r=this.itemSize;i<r;i++)this.array[t+i]=e.array[n+i];return this}copyArray(t){return this.array.set(t),this}copyColorsArray(t){const e=this.array;let n=0;for(let i=0,r=t.length;i<r;i++){let r=t[i];void 0===r&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",i),r=new Ut),e[n++]=r.r,e[n++]=r.g,e[n++]=r.b}return this}copyVector2sArray(t){const e=this.array;let n=0;for(let i=0,r=t.length;i<r;i++){let r=t[i];void 0===r&&(console.warn("THREE.BufferAttribute.copyVector2sArray(): vector is undefined",i),r=new At),e[n++]=r.x,e[n++]=r.y}return this}copyVector3sArray(t){const e=this.array;let n=0;for(let i=0,r=t.length;i<r;i++){let r=t[i];void 0===r&&(console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",i),r=new Zt),e[n++]=r.x,e[n++]=r.y,e[n++]=r.z}return this}copyVector4sArray(t){const e=this.array;let n=0;for(let i=0,r=t.length;i<r;i++){let r=t[i];void 0===r&&(console.warn("THREE.BufferAttribute.copyVector4sArray(): vector is undefined",i),r=new jt),e[n++]=r.x,e[n++]=r.y,e[n++]=r.z,e[n++]=r.w}return this}applyMatrix3(t){if(2===this.itemSize)for(let e=0,n=this.count;e<n;e++)fn.fromBufferAttribute(this,e),fn.applyMatrix3(t),this.setXY(e,fn.x,fn.y);else if(3===this.itemSize)for(let e=0,n=this.count;e<n;e++)mn.fromBufferAttribute(this,e),mn.applyMatrix3(t),this.setXYZ(e,mn.x,mn.y,mn.z);return this}applyMatrix4(t){for(let e=0,n=this.count;e<n;e++)mn.x=this.getX(e),mn.y=this.getY(e),mn.z=this.getZ(e),mn.applyMatrix4(t),this.setXYZ(e,mn.x,mn.y,mn.z);return this}applyNormalMatrix(t){for(let e=0,n=this.count;e<n;e++)mn.x=this.getX(e),mn.y=this.getY(e),mn.z=this.getZ(e),mn.applyNormalMatrix(t),this.setXYZ(e,mn.x,mn.y,mn.z);return this}transformDirection(t){for(let e=0,n=this.count;e<n;e++)mn.x=this.getX(e),mn.y=this.getY(e),mn.z=this.getZ(e),mn.transformDirection(t),this.setXYZ(e,mn.x,mn.y,mn.z);return this}set(t,e=0){return this.array.set(t,e),this}getX(t){return this.array[t*this.itemSize]}setX(t,e){return this.array[t*this.itemSize]=e,this}getY(t){return this.array[t*this.itemSize+1]}setY(t,e){return this.array[t*this.itemSize+1]=e,this}getZ(t){return this.array[t*this.itemSize+2]}setZ(t,e){return this.array[t*this.itemSize+2]=e,this}getW(t){return this.array[t*this.itemSize+3]}setW(t,e){return this.array[t*this.itemSize+3]=e,this}setXY(t,e,n){return t*=this.itemSize,this.array[t+0]=e,this.array[t+1]=n,this}setXYZ(t,e,n,i){return t*=this.itemSize,this.array[t+0]=e,this.array[t+1]=n,this.array[t+2]=i,this}setXYZW(t,e,n,i,r){return t*=this.itemSize,this.array[t+0]=e,this.array[t+1]=n,this.array[t+2]=i,this.array[t+3]=r,this}onUpload(t){return this.onUploadCallback=t,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const t={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.prototype.slice.call(this.array),normalized:this.normalized};return""!==this.name&&(t.name=this.name),this.usage!==ht&&(t.usage=this.usage),0===this.updateRange.offset&&-1===this.updateRange.count||(t.updateRange=this.updateRange),t}}gn.prototype.isBufferAttribute=!0;class vn extends gn{constructor(t,e,n){super(new Int8Array(t),e,n)}}class yn extends gn{constructor(t,e,n){super(new Uint8Array(t),e,n)}}class xn extends gn{constructor(t,e,n){super(new Uint8ClampedArray(t),e,n)}}class _n extends gn{constructor(t,e,n){super(new Int16Array(t),e,n)}}class Mn extends gn{constructor(t,e,n){super(new Uint16Array(t),e,n)}}class bn extends gn{constructor(t,e,n){super(new Int32Array(t),e,n)}}class wn extends gn{constructor(t,e,n){super(new Uint32Array(t),e,n)}}class Sn extends gn{constructor(t,e,n){super(new Uint16Array(t),e,n)}}Sn.prototype.isFloat16BufferAttribute=!0;class Tn extends gn{constructor(t,e,n){super(new Float32Array(t),e,n)}}class En extends gn{constructor(t,e,n){super(new Float64Array(t),e,n)}}let An=0;const Rn=new Ae,Ln=new Qe,Cn=new Zt,Pn=new $t,Dn=new $t,In=new Zt;class Nn extends mt{constructor(){super(),Object.defineProperty(this,"id",{value:An++}),this.uuid=xt(),this.name="",this.type="BufferGeometry",this.index=null,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(Lt(t)?wn:Mn)(t,1):this.index=t,this}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 void 0!==this.attributes[t]}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;void 0!==e&&(e.applyMatrix4(t),e.needsUpdate=!0);const n=this.attributes.normal;if(void 0!==n){const e=(new Rt).getNormalMatrix(t);n.applyNormalMatrix(e),n.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(t),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(t){return Rn.makeRotationFromQuaternion(t),this.applyMatrix4(Rn),this}rotateX(t){return Rn.makeRotationX(t),this.applyMatrix4(Rn),this}rotateY(t){return Rn.makeRotationY(t),this.applyMatrix4(Rn),this}rotateZ(t){return Rn.makeRotationZ(t),this.applyMatrix4(Rn),this}translate(t,e,n){return Rn.makeTranslation(t,e,n),this.applyMatrix4(Rn),this}scale(t,e,n){return Rn.makeScale(t,e,n),this.applyMatrix4(Rn),this}lookAt(t){return Ln.lookAt(t),Ln.updateMatrix(),this.applyMatrix4(Ln.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Cn).negate(),this.translate(Cn.x,Cn.y,Cn.z),this}setFromPoints(t){const e=[];for(let n=0,i=t.length;n<i;n++){const i=t[n];e.push(i.x,i.y,i.z||0)}return this.setAttribute("position",new Tn(e,3)),this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new $t);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)return console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".',this),void this.boundingBox.set(new Zt(-1/0,-1/0,-1/0),new Zt(1/0,1/0,1/0));if(void 0!==t){if(this.boundingBox.setFromBufferAttribute(t),e)for(let t=0,n=e.length;t<n;t++){const n=e[t];Pn.setFromBufferAttribute(n),this.morphTargetsRelative?(In.addVectors(this.boundingBox.min,Pn.min),this.boundingBox.expandByPoint(In),In.addVectors(this.boundingBox.max,Pn.max),this.boundingBox.expandByPoint(In)):(this.boundingBox.expandByPoint(Pn.min),this.boundingBox.expandByPoint(Pn.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new ye);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)return console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".',this),void this.boundingSphere.set(new Zt,1/0);if(t){const n=this.boundingSphere.center;if(Pn.setFromBufferAttribute(t),e)for(let t=0,n=e.length;t<n;t++){const n=e[t];Dn.setFromBufferAttribute(n),this.morphTargetsRelative?(In.addVectors(Pn.min,Dn.min),Pn.expandByPoint(In),In.addVectors(Pn.max,Dn.max),Pn.expandByPoint(In)):(Pn.expandByPoint(Dn.min),Pn.expandByPoint(Dn.max))}Pn.getCenter(n);let i=0;for(let e=0,r=t.count;e<r;e++)In.fromBufferAttribute(t,e),i=Math.max(i,n.distanceToSquared(In));if(e)for(let r=0,s=e.length;r<s;r++){const s=e[r],a=this.morphTargetsRelative;for(let e=0,r=s.count;e<r;e++)In.fromBufferAttribute(s,e),a&&(Cn.fromBufferAttribute(t,e),In.add(Cn)),i=Math.max(i,n.distanceToSquared(In))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const t=this.index,e=this.attributes;if(null===t||void 0===e.position||void 0===e.normal||void 0===e.uv)return void console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const n=t.array,i=e.position.array,r=e.normal.array,s=e.uv.array,a=i.length/3;void 0===e.tangent&&this.setAttribute("tangent",new gn(new Float32Array(4*a),4));const o=e.tangent.array,l=[],c=[];for(let t=0;t<a;t++)l[t]=new Zt,c[t]=new Zt;const h=new Zt,u=new Zt,d=new Zt,p=new At,m=new At,f=new At,g=new Zt,v=new Zt;function y(t,e,n){h.fromArray(i,3*t),u.fromArray(i,3*e),d.fromArray(i,3*n),p.fromArray(s,2*t),m.fromArray(s,2*e),f.fromArray(s,2*n),u.sub(h),d.sub(h),m.sub(p),f.sub(p);const r=1/(m.x*f.y-f.x*m.y);isFinite(r)&&(g.copy(u).multiplyScalar(f.y).addScaledVector(d,-m.y).multiplyScalar(r),v.copy(d).multiplyScalar(m.x).addScaledVector(u,-f.x).multiplyScalar(r),l[t].add(g),l[e].add(g),l[n].add(g),c[t].add(v),c[e].add(v),c[n].add(v))}let x=this.groups;0===x.length&&(x=[{start:0,count:n.length}]);for(let t=0,e=x.length;t<e;++t){const e=x[t],i=e.start;for(let t=i,r=i+e.count;t<r;t+=3)y(n[t+0],n[t+1],n[t+2])}const _=new Zt,M=new Zt,b=new Zt,w=new Zt;function S(t){b.fromArray(r,3*t),w.copy(b);const e=l[t];_.copy(e),_.sub(b.multiplyScalar(b.dot(e))).normalize(),M.crossVectors(w,e);const n=M.dot(c[t])<0?-1:1;o[4*t]=_.x,o[4*t+1]=_.y,o[4*t+2]=_.z,o[4*t+3]=n}for(let t=0,e=x.length;t<e;++t){const e=x[t],i=e.start;for(let t=i,r=i+e.count;t<r;t+=3)S(n[t+0]),S(n[t+1]),S(n[t+2])}}computeVertexNormals(){const t=this.index,e=this.getAttribute("position");if(void 0!==e){let n=this.getAttribute("normal");if(void 0===n)n=new gn(new Float32Array(3*e.count),3),this.setAttribute("normal",n);else for(let t=0,e=n.count;t<e;t++)n.setXYZ(t,0,0,0);const i=new Zt,r=new Zt,s=new Zt,a=new Zt,o=new Zt,l=new Zt,c=new Zt,h=new Zt;if(t)for(let u=0,d=t.count;u<d;u+=3){const d=t.getX(u+0),p=t.getX(u+1),m=t.getX(u+2);i.fromBufferAttribute(e,d),r.fromBufferAttribute(e,p),s.fromBufferAttribute(e,m),c.subVectors(s,r),h.subVectors(i,r),c.cross(h),a.fromBufferAttribute(n,d),o.fromBufferAttribute(n,p),l.fromBufferAttribute(n,m),a.add(c),o.add(c),l.add(c),n.setXYZ(d,a.x,a.y,a.z),n.setXYZ(p,o.x,o.y,o.z),n.setXYZ(m,l.x,l.y,l.z)}else for(let t=0,a=e.count;t<a;t+=3)i.fromBufferAttribute(e,t+0),r.fromBufferAttribute(e,t+1),s.fromBufferAttribute(e,t+2),c.subVectors(s,r),h.subVectors(i,r),c.cross(h),n.setXYZ(t+0,c.x,c.y,c.z),n.setXYZ(t+1,c.x,c.y,c.z),n.setXYZ(t+2,c.x,c.y,c.z);this.normalizeNormals(),n.needsUpdate=!0}}merge(t,e){if(!t||!t.isBufferGeometry)return void console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",t);void 0===e&&(e=0,console.warn("THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge."));const n=this.attributes;for(const i in n){if(void 0===t.attributes[i])continue;const r=n[i].array,s=t.attributes[i],a=s.array,o=s.itemSize*e,l=Math.min(a.length,r.length-o);for(let t=0,e=o;t<l;t++,e++)r[e]=a[t]}return this}normalizeNormals(){const t=this.attributes.normal;for(let e=0,n=t.count;e<n;e++)In.fromBufferAttribute(t,e),In.normalize(),t.setXYZ(e,In.x,In.y,In.z)}toNonIndexed(){function t(t,e){const n=t.array,i=t.itemSize,r=t.normalized,s=new n.constructor(e.length*i);let a=0,o=0;for(let r=0,l=e.length;r<l;r++){a=t.isInterleavedBufferAttribute?e[r]*t.data.stride+t.offset:e[r]*i;for(let t=0;t<i;t++)s[o++]=n[a++]}return new gn(s,i,r)}if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const e=new Nn,n=this.index.array,i=this.attributes;for(const r in i){const s=t(i[r],n);e.setAttribute(r,s)}const r=this.morphAttributes;for(const i in r){const s=[],a=r[i];for(let e=0,i=a.length;e<i;e++){const i=t(a[e],n);s.push(i)}e.morphAttributes[i]=s}e.morphTargetsRelative=this.morphTargetsRelative;const s=this.groups;for(let t=0,n=s.length;t<n;t++){const n=s[t];e.addGroup(n.start,n.count,n.materialIndex)}return e}toJSON(){const t={metadata:{version:4.5,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(t.uuid=this.uuid,t.type=this.type,""!==this.name&&(t.name=this.name),Object.keys(this.userData).length>0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const n in e)void 0!==e[n]&&(t[n]=e[n]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const n=this.attributes;for(const e in n){const i=n[e];t.data.attributes[e]=i.toJSON(t.data)}const i={};let r=!1;for(const e in this.morphAttributes){const n=this.morphAttributes[e],s=[];for(let e=0,i=n.length;e<i;e++){const i=n[e];s.push(i.toJSON(t.data))}s.length>0&&(i[e]=s,r=!0)}r&&(t.data.morphAttributes=i,t.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(t.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),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;null!==n&&this.setIndex(n.clone(e));const i=t.attributes;for(const t in i){const n=i[t];this.setAttribute(t,n.clone(e))}const r=t.morphAttributes;for(const t in r){const n=[],i=r[t];for(let t=0,r=i.length;t<r;t++)n.push(i[t].clone(e));this.morphAttributes[t]=n}this.morphTargetsRelative=t.morphTargetsRelative;const s=t.groups;for(let t=0,e=s.length;t<e;t++){const e=s[t];this.addGroup(e.start,e.count,e.materialIndex)}const a=t.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=t.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=t.drawRange.start,this.drawRange.count=t.drawRange.count,this.userData=t.userData,void 0!==t.parameters&&(this.parameters=Object.assign({},t.parameters)),this}dispose(){this.dispatchEvent({type:"dispose"})}}Nn.prototype.isBufferGeometry=!0;const Bn=new Ae,zn=new Ee,On=new ye,Fn=new Zt,Un=new Zt,Hn=new Zt,Gn=new Zt,kn=new Zt,Vn=new Zt,Wn=new Zt,jn=new Zt,qn=new Zt,Xn=new At,Jn=new At,Yn=new At,Zn=new Zt,Kn=new Zt;class Qn extends Qe{constructor(t=new Nn,e=new pn){super(),this.type="Mesh",this.geometry=t,this.material=e,this.updateMorphTargets()}copy(t){return super.copy(t),void 0!==t.morphTargetInfluences&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),void 0!==t.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=t.material,this.geometry=t.geometry,this}updateMorphTargets(){const t=this.geometry;if(t.isBufferGeometry){const e=t.morphAttributes,n=Object.keys(e);if(n.length>0){const t=e[n[0]];if(void 0!==t){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,n=t.length;e<n;e++){const n=t[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[n]=e}}}}else{const e=t.morphTargets;void 0!==e&&e.length>0&&console.error("THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}}raycast(t,e){const n=this.geometry,i=this.material,r=this.matrixWorld;if(void 0===i)return;if(null===n.boundingSphere&&n.computeBoundingSphere(),On.copy(n.boundingSphere),On.applyMatrix4(r),!1===t.ray.intersectsSphere(On))return;if(Bn.copy(r).invert(),zn.copy(t.ray).applyMatrix4(Bn),null!==n.boundingBox&&!1===zn.intersectsBox(n.boundingBox))return;let s;if(n.isBufferGeometry){const r=n.index,a=n.attributes.position,o=n.morphAttributes.position,l=n.morphTargetsRelative,c=n.attributes.uv,h=n.attributes.uv2,u=n.groups,d=n.drawRange;if(null!==r)if(Array.isArray(i))for(let n=0,p=u.length;n<p;n++){const p=u[n],m=i[p.materialIndex];for(let n=Math.max(p.start,d.start),i=Math.min(r.count,Math.min(p.start+p.count,d.start+d.count));n<i;n+=3){const i=r.getX(n),u=r.getX(n+1),d=r.getX(n+2);s=$n(this,m,t,zn,a,o,l,c,h,i,u,d),s&&(s.faceIndex=Math.floor(n/3),s.face.materialIndex=p.materialIndex,e.push(s))}}else{for(let n=Math.max(0,d.start),u=Math.min(r.count,d.start+d.count);n<u;n+=3){const u=r.getX(n),d=r.getX(n+1),p=r.getX(n+2);s=$n(this,i,t,zn,a,o,l,c,h,u,d,p),s&&(s.faceIndex=Math.floor(n/3),e.push(s))}}else if(void 0!==a)if(Array.isArray(i))for(let n=0,r=u.length;n<r;n++){const r=u[n],p=i[r.materialIndex];for(let n=Math.max(r.start,d.start),i=Math.min(a.count,Math.min(r.start+r.count,d.start+d.count));n<i;n+=3){s=$n(this,p,t,zn,a,o,l,c,h,n,n+1,n+2),s&&(s.faceIndex=Math.floor(n/3),s.face.materialIndex=r.materialIndex,e.push(s))}}else{for(let n=Math.max(0,d.start),r=Math.min(a.count,d.start+d.count);n<r;n+=3){s=$n(this,i,t,zn,a,o,l,c,h,n,n+1,n+2),s&&(s.faceIndex=Math.floor(n/3),e.push(s))}}}else n.isGeometry&&console.error("THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}}function $n(t,e,n,i,r,s,a,o,l,c,h,u){Fn.fromBufferAttribute(r,c),Un.fromBufferAttribute(r,h),Hn.fromBufferAttribute(r,u);const d=t.morphTargetInfluences;if(s&&d){Wn.set(0,0,0),jn.set(0,0,0),qn.set(0,0,0);for(let t=0,e=s.length;t<e;t++){const e=d[t],n=s[t];0!==e&&(Gn.fromBufferAttribute(n,c),kn.fromBufferAttribute(n,h),Vn.fromBufferAttribute(n,u),a?(Wn.addScaledVector(Gn,e),jn.addScaledVector(kn,e),qn.addScaledVector(Vn,e)):(Wn.addScaledVector(Gn.sub(Fn),e),jn.addScaledVector(kn.sub(Un),e),qn.addScaledVector(Vn.sub(Hn),e)))}Fn.add(Wn),Un.add(jn),Hn.add(qn)}t.isSkinnedMesh&&(t.boneTransform(c,Fn),t.boneTransform(h,Un),t.boneTransform(u,Hn));const p=function(t,e,n,i,r,s,a,o){let l;if(l=1===e.side?i.intersectTriangle(a,s,r,!0,o):i.intersectTriangle(r,s,a,2!==e.side,o),null===l)return null;Kn.copy(o),Kn.applyMatrix4(t.matrixWorld);const c=n.ray.origin.distanceTo(Kn);return c<n.near||c>n.far?null:{distance:c,point:Kn.clone(),object:t}}(t,e,n,i,Fn,Un,Hn,Zn);if(p){o&&(Xn.fromBufferAttribute(o,c),Jn.fromBufferAttribute(o,h),Yn.fromBufferAttribute(o,u),p.uv=hn.getUV(Zn,Fn,Un,Hn,Xn,Jn,Yn,new At)),l&&(Xn.fromBufferAttribute(l,c),Jn.fromBufferAttribute(l,h),Yn.fromBufferAttribute(l,u),p.uv2=hn.getUV(Zn,Fn,Un,Hn,Xn,Jn,Yn,new At));const t={a:c,b:h,c:u,normal:new Zt,materialIndex:0};hn.getNormal(Fn,Un,Hn,t.normal),p.face=t}return p}Qn.prototype.isMesh=!0;class ti extends Nn{constructor(t=1,e=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],h=[];let u=0,d=0;function p(t,e,n,i,r,s,p,m,f,g,v){const y=s/f,x=p/g,_=s/2,M=p/2,b=m/2,w=f+1,S=g+1;let T=0,E=0;const A=new Zt;for(let s=0;s<S;s++){const a=s*x-M;for(let o=0;o<w;o++){const u=o*y-_;A[t]=u*i,A[e]=a*r,A[n]=b,l.push(A.x,A.y,A.z),A[t]=0,A[e]=0,A[n]=m>0?1:-1,c.push(A.x,A.y,A.z),h.push(o/f),h.push(1-s/g),T+=1}}for(let t=0;t<g;t++)for(let e=0;e<f;e++){const n=u+e+w*t,i=u+e+w*(t+1),r=u+(e+1)+w*(t+1),s=u+(e+1)+w*t;o.push(n,i,s),o.push(i,r,s),E+=6}a.addGroup(d,E,v),d+=E,u+=T}p("z","y","x",-1,-1,n,e,t,s,r,0),p("z","y","x",1,-1,n,e,-t,s,r,1),p("x","z","y",1,1,t,n,e,i,s,2),p("x","z","y",1,-1,t,n,-e,i,s,3),p("x","y","z",1,-1,t,e,n,i,r,4),p("x","y","z",-1,-1,t,e,-n,i,r,5),this.setIndex(o),this.setAttribute("position",new Tn(l,3)),this.setAttribute("normal",new Tn(c,3)),this.setAttribute("uv",new Tn(h,2))}static fromJSON(t){return new ti(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}}function ei(t){const e={};for(const n in t){e[n]={};for(const i in t[n]){const r=t[n][i];r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)?e[n][i]=r.clone():Array.isArray(r)?e[n][i]=r.slice():e[n][i]=r}}return e}function ni(t){const e={};for(let n=0;n<t.length;n++){const i=ei(t[n]);for(const t in i)e[t]=i[t]}return e}const ii={clone:ei,merge:ni};class ri extends dn{constructor(t){super(),this.type="ShaderMaterial",this.defines={},this.uniforms={},this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.extensions={derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv2:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,void 0!==t&&(void 0!==t.attributes&&console.error("THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead."),this.setValues(t))}copy(t){return super.copy(t),this.fragmentShader=t.fragmentShader,this.vertexShader=t.vertexShader,this.uniforms=ei(t.uniforms),this.defines=Object.assign({},t.defines),this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.lights=t.lights,this.clipping=t.clipping,this.extensions=Object.assign({},t.extensions),this.glslVersion=t.glslVersion,this}toJSON(t){const e=super.toJSON(t);e.glslVersion=this.glslVersion,e.uniforms={};for(const n in this.uniforms){const i=this.uniforms[n].value;i&&i.isTexture?e.uniforms[n]={type:"t",value:i.toJSON(t).uuid}:i&&i.isColor?e.uniforms[n]={type:"c",value:i.getHex()}:i&&i.isVector2?e.uniforms[n]={type:"v2",value:i.toArray()}:i&&i.isVector3?e.uniforms[n]={type:"v3",value:i.toArray()}:i&&i.isVector4?e.uniforms[n]={type:"v4",value:i.toArray()}:i&&i.isMatrix3?e.uniforms[n]={type:"m3",value:i.toArray()}:i&&i.isMatrix4?e.uniforms[n]={type:"m4",value:i.toArray()}:e.uniforms[n]={value:i}}Object.keys(this.defines).length>0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader;const n={};for(const t in this.extensions)!0===this.extensions[t]&&(n[t]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}}ri.prototype.isShaderMaterial=!0;class si extends Qe{constructor(){super(),this.type="Camera",this.matrixWorldInverse=new Ae,this.projectionMatrix=new Ae,this.projectionMatrixInverse=new Ae}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(-e[8],-e[9],-e[10]).normalize()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}si.prototype.isCamera=!0;class ai extends si{constructor(t=50,e=1,n=.1,i=2e3){super(),this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*yt*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*vt*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*yt*Math.atan(Math.tan(.5*vt*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(t,e,n,i,r,s){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(.5*vt*this.fov)/this.zoom,n=2*e,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const t=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/t,e-=s.offsetY*n/a,i*=s.width/t,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,e,e-n,t,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}ai.prototype.isPerspectiveCamera=!0;const oi=90;class li extends Qe{constructor(t,e,n){if(super(),this.type="CubeCamera",!0!==n.isWebGLCubeRenderTarget)return void console.error("THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.");this.renderTarget=n;const i=new ai(oi,1,t,e);i.layers=this.layers,i.up.set(0,-1,0),i.lookAt(new Zt(1,0,0)),this.add(i);const r=new ai(oi,1,t,e);r.layers=this.layers,r.up.set(0,-1,0),r.lookAt(new Zt(-1,0,0)),this.add(r);const s=new ai(oi,1,t,e);s.layers=this.layers,s.up.set(0,0,1),s.lookAt(new Zt(0,1,0)),this.add(s);const a=new ai(oi,1,t,e);a.layers=this.layers,a.up.set(0,0,-1),a.lookAt(new Zt(0,-1,0)),this.add(a);const o=new ai(oi,1,t,e);o.layers=this.layers,o.up.set(0,-1,0),o.lookAt(new Zt(0,0,1)),this.add(o);const l=new ai(oi,1,t,e);l.layers=this.layers,l.up.set(0,-1,0),l.lookAt(new Zt(0,0,-1)),this.add(l)}update(t,e){null===this.parent&&this.updateMatrixWorld();const n=this.renderTarget,[i,r,s,a,o,l]=this.children,c=t.xr.enabled,h=t.getRenderTarget();t.xr.enabled=!1;const u=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,t.setRenderTarget(n,0),t.render(e,i),t.setRenderTarget(n,1),t.render(e,r),t.setRenderTarget(n,2),t.render(e,s),t.setRenderTarget(n,3),t.render(e,a),t.setRenderTarget(n,4),t.render(e,o),n.texture.generateMipmaps=u,t.setRenderTarget(n,5),t.render(e,l),t.setRenderTarget(h),t.xr.enabled=c,n.texture.needsPMREMUpdate=!0}}class ci extends Vt{constructor(t,e,n,i,s,a,o,l,c,h){super(t=void 0!==t?t:[],e=void 0!==e?e:r,n,i,s,a,o,l,c,h),this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}ci.prototype.isCubeTexture=!0;class hi extends qt{constructor(t,e,n){Number.isInteger(e)&&(console.warn("THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )"),e=n),super(t,t,e),e=e||{},this.texture=new ci(void 0,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.encoding),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==e.generateMipmaps&&e.generateMipmaps,this.texture.minFilter=void 0!==e.minFilter?e.minFilter:g}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.format=T,this.texture.encoding=e.encoding,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new ti(5,5,5),r=new ri({name:"CubemapFromEquirect",uniforms:ei(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=e;const s=new Qn(i,r),a=e.minFilter;e.minFilter===y&&(e.minFilter=g);return new li(1,10,this).update(t,s),e.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(t,e,n,i){const r=t.getRenderTarget();for(let r=0;r<6;r++)t.setRenderTarget(this,r),t.clear(e,n,i);t.setRenderTarget(r)}}hi.prototype.isWebGLCubeRenderTarget=!0;const ui=new Zt,di=new Zt,pi=new Rt;class mi{constructor(t=new Zt(1,0,0),e=0){this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,n,i){return this.normal.set(t,e,n),this.constant=i,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,n){const i=ui.subVectors(n,e).cross(di.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(i,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(this.normal).multiplyScalar(-this.distanceToPoint(t)).add(t)}intersectLine(t,e){const n=t.delta(ui),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(t.start)?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:e.copy(n).multiplyScalar(r).add(t.start)}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||pi.getNormalMatrix(t),i=this.coplanarPoint(ui).applyMatrix4(t),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),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)}}mi.prototype.isPlane=!0;const fi=new ye,gi=new Zt;class vi{constructor(t=new mi,e=new mi,n=new mi,i=new mi,r=new mi,s=new mi){this.planes=[t,e,n,i,r,s]}set(t,e,n,i,r,s){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(t){const e=this.planes;for(let n=0;n<6;n++)e[n].copy(t.planes[n]);return this}setFromProjectionMatrix(t){const e=this.planes,n=t.elements,i=n[0],r=n[1],s=n[2],a=n[3],o=n[4],l=n[5],c=n[6],h=n[7],u=n[8],d=n[9],p=n[10],m=n[11],f=n[12],g=n[13],v=n[14],y=n[15];return e[0].setComponents(a-i,h-o,m-u,y-f).normalize(),e[1].setComponents(a+i,h+o,m+u,y+f).normalize(),e[2].setComponents(a+r,h+l,m+d,y+g).normalize(),e[3].setComponents(a-r,h-l,m-d,y-g).normalize(),e[4].setComponents(a-s,h-c,m-p,y-v).normalize(),e[5].setComponents(a+s,h+c,m+p,y+v).normalize(),this}intersectsObject(t){const e=t.geometry;return null===e.boundingSphere&&e.computeBoundingSphere(),fi.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),this.intersectsSphere(fi)}intersectsSprite(t){return fi.center.set(0,0,0),fi.radius=.7071067811865476,fi.applyMatrix4(t.matrixWorld),this.intersectsSphere(fi)}intersectsSphere(t){const e=this.planes,n=t.center,i=-t.radius;for(let t=0;t<6;t++){if(e[t].distanceToPoint(n)<i)return!1}return!0}intersectsBox(t){const e=this.planes;for(let n=0;n<6;n++){const i=e[n];if(gi.x=i.normal.x>0?t.max.x:t.min.x,gi.y=i.normal.y>0?t.max.y:t.min.y,gi.z=i.normal.z>0?t.max.z:t.min.z,i.distanceToPoint(gi)<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)}}function yi(){let t=null,e=!1,n=null,i=null;function r(e,s){n(e,s),i=t.requestAnimationFrame(r)}return{start:function(){!0!==e&&null!==n&&(i=t.requestAnimationFrame(r),e=!0)},stop:function(){t.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(t){n=t},setContext:function(e){t=e}}}function xi(t,e){const n=e.isWebGL2,i=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),i.get(t)},remove:function(e){e.isInterleavedBufferAttribute&&(e=e.data);const n=i.get(e);n&&(t.deleteBuffer(n.buffer),i.delete(e))},update:function(e,r){if(e.isGLBufferAttribute){const t=i.get(e);return void((!t||t.version<e.version)&&i.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version}))}e.isInterleavedBufferAttribute&&(e=e.data);const s=i.get(e);void 0===s?i.set(e,function(e,i){const r=e.array,s=e.usage,a=t.createBuffer();t.bindBuffer(i,a),t.bufferData(i,r,s),e.onUploadCallback();let o=5126;return r instanceof Float32Array?o=5126:r instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):r instanceof Uint16Array?e.isFloat16BufferAttribute?n?o=5131:console.warn("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2."):o=5123:r instanceof Int16Array?o=5122:r instanceof Uint32Array?o=5125:r instanceof Int32Array?o=5124:r instanceof Int8Array?o=5120:(r instanceof Uint8Array||r instanceof Uint8ClampedArray)&&(o=5121),{buffer:a,type:o,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version}}(e,r)):s.version<e.version&&(!function(e,i,r){const s=i.array,a=i.updateRange;t.bindBuffer(r,e),-1===a.count?t.bufferSubData(r,0,s):(n?t.bufferSubData(r,a.offset*s.BYTES_PER_ELEMENT,s,a.offset,a.count):t.bufferSubData(r,a.offset*s.BYTES_PER_ELEMENT,s.subarray(a.offset,a.offset+a.count)),a.count=-1)}(s.buffer,e,r),s.version=e.version)}}}class _i extends Nn{constructor(t=1,e=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:t,height:e,widthSegments:n,heightSegments:i};const r=t/2,s=e/2,a=Math.floor(n),o=Math.floor(i),l=a+1,c=o+1,h=t/a,u=e/o,d=[],p=[],m=[],f=[];for(let t=0;t<c;t++){const e=t*u-s;for(let n=0;n<l;n++){const i=n*h-r;p.push(i,-e,0),m.push(0,0,1),f.push(n/a),f.push(1-t/o)}}for(let t=0;t<o;t++)for(let e=0;e<a;e++){const n=e+l*t,i=e+l*(t+1),r=e+1+l*(t+1),s=e+1+l*t;d.push(n,i,s),d.push(i,r,s)}this.setIndex(d),this.setAttribute("position",new Tn(p,3)),this.setAttribute("normal",new Tn(m,3)),this.setAttribute("uv",new Tn(f,2))}static fromJSON(t){return new _i(t.width,t.height,t.widthSegments,t.heightSegments)}}const Mi={alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",alphatest_fragment:"#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif",alphatest_pars_fragment:"#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",begin_vertex:"vec3 transformed = vec3( position );",beginnormal_vertex:"vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif",bsdfs:"vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn 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\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif",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; }\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 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 ) + 0.5;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\treturn texture2D( envMap, uv ).rgb;\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",encodings_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",encodings_pars_fragment:"vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\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\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\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\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3(\t\t0, 1,\t\t0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;",normal_fragment_maps:"#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif",output_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn 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\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t\tf.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t\tf.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif",shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",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\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3(\t1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108,\t1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605,\t1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif",uv_pars_fragment:"#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif",uv_vertex:"#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif",uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}",cube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}",depth_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",meshbasic_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",shadow_vert:"#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}"},bi={common:{diffuse:{value:new Ut(16777215)},opacity:{value:1},map:{value:null},uvTransform:{value:new Rt},uv2Transform:{value:new Rt},alphaMap:{value:null},alphaTest:{value:0}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new At(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ut(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Ut(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaTest:{value:0},uvTransform:{value:new Rt}},sprite:{diffuse:{value:new Ut(16777215)},opacity:{value:1},center:{value:new At(.5,.5)},rotation:{value:0},map:{value:null},alphaMap:{value:null},alphaTest:{value:0},uvTransform:{value:new Rt}}},wi={basic:{uniforms:ni([bi.common,bi.specularmap,bi.envmap,bi.aomap,bi.lightmap,bi.fog]),vertexShader:Mi.meshbasic_vert,fragmentShader:Mi.meshbasic_frag},lambert:{uniforms:ni([bi.common,bi.specularmap,bi.envmap,bi.aomap,bi.lightmap,bi.emissivemap,bi.fog,bi.lights,{emissive:{value:new Ut(0)}}]),vertexShader:Mi.meshlambert_vert,fragmentShader:Mi.meshlambert_frag},phong:{uniforms:ni([bi.common,bi.specularmap,bi.envmap,bi.aomap,bi.lightmap,bi.emissivemap,bi.bumpmap,bi.normalmap,bi.displacementmap,bi.fog,bi.lights,{emissive:{value:new Ut(0)},specular:{value:new Ut(1118481)},shininess:{value:30}}]),vertexShader:Mi.meshphong_vert,fragmentShader:Mi.meshphong_frag},standard:{uniforms:ni([bi.common,bi.envmap,bi.aomap,bi.lightmap,bi.emissivemap,bi.bumpmap,bi.normalmap,bi.displacementmap,bi.roughnessmap,bi.metalnessmap,bi.fog,bi.lights,{emissive:{value:new Ut(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Mi.meshphysical_vert,fragmentShader:Mi.meshphysical_frag},toon:{uniforms:ni([bi.common,bi.aomap,bi.lightmap,bi.emissivemap,bi.bumpmap,bi.normalmap,bi.displacementmap,bi.gradientmap,bi.fog,bi.lights,{emissive:{value:new Ut(0)}}]),vertexShader:Mi.meshtoon_vert,fragmentShader:Mi.meshtoon_frag},matcap:{uniforms:ni([bi.common,bi.bumpmap,bi.normalmap,bi.displacementmap,bi.fog,{matcap:{value:null}}]),vertexShader:Mi.meshmatcap_vert,fragmentShader:Mi.meshmatcap_frag},points:{uniforms:ni([bi.points,bi.fog]),vertexShader:Mi.points_vert,fragmentShader:Mi.points_frag},dashed:{uniforms:ni([bi.common,bi.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Mi.linedashed_vert,fragmentShader:Mi.linedashed_frag},depth:{uniforms:ni([bi.common,bi.displacementmap]),vertexShader:Mi.depth_vert,fragmentShader:Mi.depth_frag},normal:{uniforms:ni([bi.common,bi.bumpmap,bi.normalmap,bi.displacementmap,{opacity:{value:1}}]),vertexShader:Mi.meshnormal_vert,fragmentShader:Mi.meshnormal_frag},sprite:{uniforms:ni([bi.sprite,bi.fog]),vertexShader:Mi.sprite_vert,fragmentShader:Mi.sprite_frag},background:{uniforms:{uvTransform:{value:new Rt},t2D:{value:null}},vertexShader:Mi.background_vert,fragmentShader:Mi.background_frag},cube:{uniforms:ni([bi.envmap,{opacity:{value:1}}]),vertexShader:Mi.cube_vert,fragmentShader:Mi.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Mi.equirect_vert,fragmentShader:Mi.equirect_frag},distanceRGBA:{uniforms:ni([bi.common,bi.displacementmap,{referencePosition:{value:new Zt},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Mi.distanceRGBA_vert,fragmentShader:Mi.distanceRGBA_frag},shadow:{uniforms:ni([bi.lights,bi.fog,{color:{value:new Ut(0)},opacity:{value:1}}]),vertexShader:Mi.shadow_vert,fragmentShader:Mi.shadow_frag}};function Si(t,e,n,i,r,s){const a=new Ut(0);let o,c,h=!0===r?0:1,u=null,d=0,p=null;function m(t,e){n.buffers.color.setClear(t.r,t.g,t.b,e,s)}return{getClearColor:function(){return a},setClearColor:function(t,e=1){a.set(t),h=e,m(a,h)},getClearAlpha:function(){return h},setClearAlpha:function(t){h=t,m(a,h)},render:function(n,r){let s=!1,f=!0===r.isScene?r.background:null;f&&f.isTexture&&(f=e.get(f));const g=t.xr,v=g.getSession&&g.getSession();v&&"additive"===v.environmentBlendMode&&(f=null),null===f?m(a,h):f&&f.isColor&&(m(f,1),s=!0),(t.autoClear||s)&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),f&&(f.isCubeTexture||f.mapping===l)?(void 0===c&&(c=new Qn(new ti(1,1,1),new ri({name:"BackgroundCubeMaterial",uniforms:ei(wi.cube.uniforms),vertexShader:wi.cube.vertexShader,fragmentShader:wi.cube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(t,e,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(c)),c.material.uniforms.envMap.value=f,c.material.uniforms.flipEnvMap.value=f.isCubeTexture&&!1===f.isRenderTargetTexture?-1:1,u===f&&d===f.version&&p===t.toneMapping||(c.material.needsUpdate=!0,u=f,d=f.version,p=t.toneMapping),n.unshift(c,c.geometry,c.material,0,0,null)):f&&f.isTexture&&(void 0===o&&(o=new Qn(new _i(2,2),new ri({name:"BackgroundMaterial",uniforms:ei(wi.background.uniforms),vertexShader:wi.background.vertexShader,fragmentShader:wi.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),o.geometry.deleteAttribute("normal"),Object.defineProperty(o.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(o)),o.material.uniforms.t2D.value=f,!0===f.matrixAutoUpdate&&f.updateMatrix(),o.material.uniforms.uvTransform.value.copy(f.matrix),u===f&&d===f.version&&p===t.toneMapping||(o.material.needsUpdate=!0,u=f,d=f.version,p=t.toneMapping),n.unshift(o,o.geometry,o.material,0,0,null))}}}function Ti(t,e,n,i){const r=t.getParameter(34921),s=i.isWebGL2?null:e.get("OES_vertex_array_object"),a=i.isWebGL2||null!==s,o={},l=d(null);let c=l;function h(e){return i.isWebGL2?t.bindVertexArray(e):s.bindVertexArrayOES(e)}function u(e){return i.isWebGL2?t.deleteVertexArray(e):s.deleteVertexArrayOES(e)}function d(t){const e=[],n=[],i=[];for(let t=0;t<r;t++)e[t]=0,n[t]=0,i[t]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:e,enabledAttributes:n,attributeDivisors:i,object:t,attributes:{},index:null}}function p(){const t=c.newAttributes;for(let e=0,n=t.length;e<n;e++)t[e]=0}function m(t){f(t,0)}function f(n,r){const s=c.newAttributes,a=c.enabledAttributes,o=c.attributeDivisors;if(s[n]=1,0===a[n]&&(t.enableVertexAttribArray(n),a[n]=1),o[n]!==r){(i.isWebGL2?t:e.get("ANGLE_instanced_arrays"))[i.isWebGL2?"vertexAttribDivisor":"vertexAttribDivisorANGLE"](n,r),o[n]=r}}function g(){const e=c.newAttributes,n=c.enabledAttributes;for(let i=0,r=n.length;i<r;i++)n[i]!==e[i]&&(t.disableVertexAttribArray(i),n[i]=0)}function v(e,n,r,s,a,o){!0!==i.isWebGL2||5124!==r&&5125!==r?t.vertexAttribPointer(e,n,r,s,a,o):t.vertexAttribIPointer(e,n,r,a,o)}function y(){x(),c!==l&&(c=l,h(c.object))}function x(){l.geometry=null,l.program=null,l.wireframe=!1}return{setup:function(r,l,u,y,x){let _=!1;if(a){const e=function(e,n,r){const a=!0===r.wireframe;let l=o[e.id];void 0===l&&(l={},o[e.id]=l);let c=l[n.id];void 0===c&&(c={},l[n.id]=c);let h=c[a];void 0===h&&(h=d(i.isWebGL2?t.createVertexArray():s.createVertexArrayOES()),c[a]=h);return h}(y,u,l);c!==e&&(c=e,h(c.object)),_=function(t,e){const n=c.attributes,i=t.attributes;let r=0;for(const t in i){const e=n[t],s=i[t];if(void 0===e)return!0;if(e.attribute!==s)return!0;if(e.data!==s.data)return!0;r++}return c.attributesNum!==r||c.index!==e}(y,x),_&&function(t,e){const n={},i=t.attributes;let r=0;for(const t in i){const e=i[t],s={};s.attribute=e,e.data&&(s.data=e.data),n[t]=s,r++}c.attributes=n,c.attributesNum=r,c.index=e}(y,x)}else{const t=!0===l.wireframe;c.geometry===y.id&&c.program===u.id&&c.wireframe===t||(c.geometry=y.id,c.program=u.id,c.wireframe=t,_=!0)}!0===r.isInstancedMesh&&(_=!0),null!==x&&n.update(x,34963),_&&(!function(r,s,a,o){if(!1===i.isWebGL2&&(r.isInstancedMesh||o.isInstancedBufferGeometry)&&null===e.get("ANGLE_instanced_arrays"))return;p();const l=o.attributes,c=a.getAttributes(),h=s.defaultAttributeValues;for(const e in c){const i=c[e];if(i.location>=0){let s=l[e];if(void 0===s&&("instanceMatrix"===e&&r.instanceMatrix&&(s=r.instanceMatrix),"instanceColor"===e&&r.instanceColor&&(s=r.instanceColor)),void 0!==s){const e=s.normalized,a=s.itemSize,l=n.get(s);if(void 0===l)continue;const c=l.buffer,h=l.type,u=l.bytesPerElement;if(s.isInterleavedBufferAttribute){const n=s.data,l=n.stride,d=s.offset;if(n&&n.isInstancedInterleavedBuffer){for(let t=0;t<i.locationSize;t++)f(i.location+t,n.meshPerAttribute);!0!==r.isInstancedMesh&&void 0===o._maxInstanceCount&&(o._maxInstanceCount=n.meshPerAttribute*n.count)}else for(let t=0;t<i.locationSize;t++)m(i.location+t);t.bindBuffer(34962,c);for(let t=0;t<i.locationSize;t++)v(i.location+t,a/i.locationSize,h,e,l*u,(d+a/i.locationSize*t)*u)}else{if(s.isInstancedBufferAttribute){for(let t=0;t<i.locationSize;t++)f(i.location+t,s.meshPerAttribute);!0!==r.isInstancedMesh&&void 0===o._maxInstanceCount&&(o._maxInstanceCount=s.meshPerAttribute*s.count)}else for(let t=0;t<i.locationSize;t++)m(i.location+t);t.bindBuffer(34962,c);for(let t=0;t<i.locationSize;t++)v(i.location+t,a/i.locationSize,h,e,a*u,a/i.locationSize*t*u)}}else if(void 0!==h){const n=h[e];if(void 0!==n)switch(n.length){case 2:t.vertexAttrib2fv(i.location,n);break;case 3:t.vertexAttrib3fv(i.location,n);break;case 4:t.vertexAttrib4fv(i.location,n);break;default:t.vertexAttrib1fv(i.location,n)}}}}g()}(r,l,u,y),null!==x&&t.bindBuffer(34963,n.get(x).buffer))},reset:y,resetDefaultState:x,dispose:function(){y();for(const t in o){const e=o[t];for(const t in e){const n=e[t];for(const t in n)u(n[t].object),delete n[t];delete e[t]}delete o[t]}},releaseStatesOfGeometry:function(t){if(void 0===o[t.id])return;const e=o[t.id];for(const t in e){const n=e[t];for(const t in n)u(n[t].object),delete n[t];delete e[t]}delete o[t.id]},releaseStatesOfProgram:function(t){for(const e in o){const n=o[e];if(void 0===n[t.id])continue;const i=n[t.id];for(const t in i)u(i[t].object),delete i[t];delete n[t.id]}},initAttributes:p,enableAttribute:m,disableUnusedAttributes:g}}function Ei(t,e,n,i){const r=i.isWebGL2;let s;this.setMode=function(t){s=t},this.render=function(e,i){t.drawArrays(s,e,i),n.update(i,s,1)},this.renderInstances=function(i,a,o){if(0===o)return;let l,c;if(r)l=t,c="drawArraysInstanced";else if(l=e.get("ANGLE_instanced_arrays"),c="drawArraysInstancedANGLE",null===l)return void console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");l[c](s,i,a,o),n.update(a,s,o)}}function Ai(t,e,n){let i;function r(e){if("highp"===e){if(t.getShaderPrecisionFormat(35633,36338).precision>0&&t.getShaderPrecisionFormat(35632,36338).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(35633,36337).precision>0&&t.getShaderPrecisionFormat(35632,36337).precision>0?"mediump":"lowp"}const s="undefined"!=typeof WebGL2RenderingContext&&t instanceof WebGL2RenderingContext||"undefined"!=typeof WebGL2ComputeRenderingContext&&t instanceof WebGL2ComputeRenderingContext;let a=void 0!==n.precision?n.precision:"highp";const o=r(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=s||e.has("WEBGL_draw_buffers"),c=!0===n.logarithmicDepthBuffer,h=t.getParameter(34930),u=t.getParameter(35660),d=t.getParameter(3379),p=t.getParameter(34076),m=t.getParameter(34921),f=t.getParameter(36347),g=t.getParameter(36348),v=t.getParameter(36349),y=u>0,x=s||e.has("OES_texture_float");return{isWebGL2:s,drawBuffers:l,getMaxAnisotropy:function(){if(void 0!==i)return i;if(!0===e.has("EXT_texture_filter_anisotropic")){const n=e.get("EXT_texture_filter_anisotropic");i=t.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i},getMaxPrecision:r,precision:a,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:u,maxTextureSize:d,maxCubemapSize:p,maxAttributes:m,maxVertexUniforms:f,maxVaryings:g,maxFragmentUniforms:v,vertexTextures:y,floatFragmentTextures:x,floatVertexTextures:y&&x,maxSamples:s?t.getParameter(36183):0}}function Ri(t){const e=this;let n=null,i=0,r=!1,s=!1;const a=new mi,o=new Rt,l={value:null,needsUpdate:!1};function c(){l.value!==n&&(l.value=n,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function h(t,n,i,r){const s=null!==t?t.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const e=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length<e)&&(c=new Float32Array(e));for(let e=0,n=i;e!==s;++e,n+=4)a.copy(t[e]).applyMatrix4(r,o),a.normal.toArray(c,n),c[n+3]=a.constant}l.value=c,l.needsUpdate=!0}return e.numPlanes=s,e.numIntersection=0,c}this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(t,e,s){const a=0!==t.length||e||0!==i||r;return r=e,n=h(t,s,0),i=t.length,a},this.beginShadows=function(){s=!0,h(null)},this.endShadows=function(){s=!1,c()},this.setState=function(e,a,o){const u=e.clippingPlanes,d=e.clipIntersection,p=e.clipShadows,m=t.get(e);if(!r||null===u||0===u.length||s&&!p)s?h(null):c();else{const t=s?0:i,e=4*t;let r=m.clippingState||null;l.value=r,r=h(u,a,e,o);for(let t=0;t!==e;++t)r[t]=n[t];m.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=t}}}function Li(t){let e=new WeakMap;function n(t,e){return e===a?t.mapping=r:e===o&&(t.mapping=s),t}function i(t){const n=t.target;n.removeEventListener("dispose",i);const r=e.get(n);void 0!==r&&(e.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture&&!1===r.isRenderTargetTexture){const s=r.mapping;if(s===a||s===o){if(e.has(r)){return n(e.get(r).texture,r.mapping)}{const s=r.image;if(s&&s.height>0){const a=new hi(s.height/2);return a.fromEquirectangularTexture(t,r),e.set(r,a),r.addEventListener("dispose",i),n(a.texture,r.mapping)}return null}}}return r},dispose:function(){e=new WeakMap}}}wi.physical={uniforms:ni([wi.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatNormalScale:{value:new At(1,1)},clearcoatNormalMap:{value:null},sheen:{value:0},sheenColor:{value:new Ut(0)},sheenColorMap:{value:null},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},transmission:{value:0},transmissionMap:{value:null},transmissionSamplerSize:{value:new At},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},attenuationDistance:{value:0},attenuationColor:{value:new Ut(0)},specularIntensity:{value:1},specularIntensityMap:{value:null},specularColor:{value:new Ut(1,1,1)},specularColorMap:{value:null}}]),vertexShader:Mi.meshphysical_vert,fragmentShader:Mi.meshphysical_frag};class Ci extends si{constructor(t=-1,e=1,n=1,i=-1,r=.1,s=2e3){super(),this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=n,this.bottom=i,this.near=r,this.far=s,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=null===t.view?null:Object.assign({},t.view),this}setViewOffset(t,e,n,i,r,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=n-t,s=n+t,a=i+e,o=i-e;if(null!==this.view&&this.view.enabled){const t=(this.right-this.left)/this.view.fullWidth/this.zoom,e=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=t*this.view.offsetX,s=r+t*this.view.width,a-=e*this.view.offsetY,o=a-e*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,this.near,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,null!==this.view&&(e.object.view=Object.assign({},this.view)),e}}Ci.prototype.isOrthographicCamera=!0;class Pi extends ri{constructor(t){super(t),this.type="RawShaderMaterial"}}Pi.prototype.isRawShaderMaterial=!0;const Di=Math.pow(2,8),Ii=[.125,.215,.35,.446,.526,.582],Ni=5+Ii.length,Bi=20,zi=new Ci,{_lodPlanes:Oi,_sizeLods:Fi,_sigmas:Ui}=qi(),Hi=new Ut;let Gi=null;const ki=(1+Math.sqrt(5))/2,Vi=1/ki,Wi=[new Zt(1,1,1),new Zt(-1,1,1),new Zt(1,1,-1),new Zt(-1,1,-1),new Zt(0,ki,Vi),new Zt(0,ki,-Vi),new Zt(Vi,0,ki),new Zt(-Vi,0,ki),new Zt(ki,Vi,0),new Zt(-ki,Vi,0)];class ji{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._blurMaterial=function(t){const e=new Float32Array(t),n=new Zt(0,1,0);return new Pi({name:"SphericalGaussianBlur",defines:{n:t},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:e},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:Ki(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}(Bi),this._equirectShader=null,this._cubemapShader=null,this._compileMaterial(this._blurMaterial)}fromScene(t,e=0,n=.1,i=100){Gi=this._renderer.getRenderTarget();const r=this._allocateTargets();return this._sceneToCubeUV(t,n,i,r),e>0&&this._blur(r,0,0,e),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){null===this._cubemapShader&&(this._cubemapShader=Zi(),this._compileMaterial(this._cubemapShader))}compileEquirectangularShader(){null===this._equirectShader&&(this._equirectShader=Yi(),this._compileMaterial(this._equirectShader))}dispose(){this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose(),null!==this._cubemapShader&&this._cubemapShader.dispose(),null!==this._equirectShader&&this._equirectShader.dispose();for(let t=0;t<Oi.length;t++)Oi[t].dispose()}_cleanup(t){this._renderer.setRenderTarget(Gi),t.scissorTest=!1,Ji(t,0,0,t.width,t.height)}_fromTexture(t,e){Gi=this._renderer.getRenderTarget();const n=e||this._allocateTargets(t);return this._textureToCubeUV(t,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(t){const e={magFilter:g,minFilter:g,generateMipmaps:!1,type:w,format:T,encoding:ot,depthBuffer:!1},n=Xi(e);return n.depthBuffer=!t,null===this._pingPongRenderTarget&&(this._pingPongRenderTarget=Xi(e)),n}_compileMaterial(t){const e=new Qn(Oi[0],t);this._renderer.compile(e,zi)}_sceneToCubeUV(t,e,n,i){const r=new ai(90,1,e,n),s=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(Hi),o.toneMapping=0,o.autoClear=!1;const h=new pn({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),u=new Qn(new ti,h);let d=!1;const p=t.background;p?p.isColor&&(h.color.copy(p),t.background=null,d=!0):(h.color.copy(Hi),d=!0);for(let e=0;e<6;e++){const n=e%3;0===n?(r.up.set(0,s[e],0),r.lookAt(a[e],0,0)):1===n?(r.up.set(0,0,s[e]),r.lookAt(0,a[e],0)):(r.up.set(0,s[e],0),r.lookAt(0,0,a[e])),Ji(i,n*Di,e>2?Di:0,Di,Di),o.setRenderTarget(i),d&&o.render(u,r),o.render(t,r)}u.geometry.dispose(),u.material.dispose(),o.toneMapping=c,o.autoClear=l,t.background=p}_textureToCubeUV(t,e){const n=this._renderer,i=t.mapping===r||t.mapping===s;i?(null===this._cubemapShader&&(this._cubemapShader=Zi()),this._cubemapShader.uniforms.flipEnvMap.value=!1===t.isRenderTargetTexture?-1:1):null===this._equirectShader&&(this._equirectShader=Yi());const a=i?this._cubemapShader:this._equirectShader,o=new Qn(Oi[0],a),l=a.uniforms;l.envMap.value=t,i||l.texelSize.value.set(1/t.image.width,1/t.image.height),Ji(e,0,0,3*Di,2*Di),n.setRenderTarget(e),n.render(o,zi)}_applyPMREM(t){const e=this._renderer,n=e.autoClear;e.autoClear=!1;for(let e=1;e<Ni;e++){const n=Math.sqrt(Ui[e]*Ui[e]-Ui[e-1]*Ui[e-1]),i=Wi[(e-1)%Wi.length];this._blur(t,e-1,e,n,i)}e.autoClear=n}_blur(t,e,n,i,r){const s=this._pingPongRenderTarget;this._halfBlur(t,s,e,n,i,"latitudinal",r),this._halfBlur(s,t,n,n,i,"longitudinal",r)}_halfBlur(t,e,n,i,r,s,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==s&&"longitudinal"!==s&&console.error("blur direction must be either latitudinal or longitudinal!");const c=new Qn(Oi[i],l),h=l.uniforms,u=Fi[n]-1,d=isFinite(r)?Math.PI/(2*u):2*Math.PI/39,p=r/d,m=isFinite(r)?1+Math.floor(3*p):Bi;m>Bi&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let t=0;t<Bi;++t){const e=t/p,n=Math.exp(-e*e/2);f.push(n),0===t?g+=n:t<m&&(g+=2*n)}for(let t=0;t<f.length;t++)f[t]=f[t]/g;h.envMap.value=t.texture,h.samples.value=m,h.weights.value=f,h.latitudinal.value="latitudinal"===s,a&&(h.poleAxis.value=a),h.dTheta.value=d,h.mipInt.value=8-n;const v=Fi[i];Ji(e,3*Math.max(0,Di-2*v),(0===i?0:2*Di)+2*v*(i>4?i-8+4:0),3*v,2*v),o.setRenderTarget(e),o.render(c,zi)}}function qi(){const t=[],e=[],n=[];let i=8;for(let r=0;r<Ni;r++){const s=Math.pow(2,i);e.push(s);let a=1/s;r>4?a=Ii[r-8+4-1]:0===r&&(a=0),n.push(a);const o=1/(s-1),l=-o/2,c=1+o/2,h=[l,l,c,l,c,c,l,l,c,c,l,c],u=6,d=6,p=3,m=2,f=1,g=new Float32Array(p*d*u),v=new Float32Array(m*d*u),y=new Float32Array(f*d*u);for(let t=0;t<u;t++){const e=t%3*2/3-1,n=t>2?0:-1,i=[e,n,0,e+2/3,n,0,e+2/3,n+1,0,e,n,0,e+2/3,n+1,0,e,n+1,0];g.set(i,p*d*t),v.set(h,m*d*t);const r=[t,t,t,t,t,t];y.set(r,f*d*t)}const x=new Nn;x.setAttribute("position",new gn(g,p)),x.setAttribute("uv",new gn(v,m)),x.setAttribute("faceIndex",new gn(y,f)),t.push(x),i>4&&i--}return{_lodPlanes:t,_sizeLods:e,_sigmas:n}}function Xi(t){const e=new qt(3*Di,3*Di,t);return e.texture.mapping=l,e.texture.name="PMREM.cubeUv",e.scissorTest=!0,e}function Ji(t,e,n,i,r){t.viewport.set(e,n,i,r),t.scissor.set(e,n,i,r)}function Yi(){const t=new At(1,1);return new Pi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null},texelSize:{value:t}},vertexShader:Ki(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform vec2 texelSize;\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tvec2 f = fract( uv / texelSize - 0.5 );\n\t\t\t\tuv -= f * texelSize;\n\t\t\t\tvec3 tl = texture2D ( envMap, uv ).rgb;\n\t\t\t\tuv.x += texelSize.x;\n\t\t\t\tvec3 tr = texture2D ( envMap, uv ).rgb;\n\t\t\t\tuv.y += texelSize.y;\n\t\t\t\tvec3 br = texture2D ( envMap, uv ).rgb;\n\t\t\t\tuv.x -= texelSize.x;\n\t\t\t\tvec3 bl = texture2D ( envMap, uv ).rgb;\n\n\t\t\t\tvec3 tm = mix( tl, tr, f.x );\n\t\t\t\tvec3 bm = mix( bl, br, f.x );\n\t\t\t\tgl_FragColor.rgb = mix( tm, bm, f.y );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Zi(){return new Pi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ki(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Ki(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute vec3 position;\n\t\tattribute vec2 uv;\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function Qi(t){let e=new WeakMap,n=null;function i(t){const n=t.target;n.removeEventListener("dispose",i);const r=e.get(n);void 0!==r&&(e.delete(n),r.dispose())}return{get:function(l){if(l&&l.isTexture){const c=l.mapping,h=c===a||c===o,u=c===r||c===s;if(h||u){if(l.isRenderTargetTexture&&!0===l.needsPMREMUpdate){l.needsPMREMUpdate=!1;let i=e.get(l);return null===n&&(n=new ji(t)),i=h?n.fromEquirectangular(l,i):n.fromCubemap(l,i),e.set(l,i),i.texture}if(e.has(l))return e.get(l).texture;{const r=l.image;if(h&&r&&r.height>0||u&&r&&function(t){let e=0;const n=6;for(let i=0;i<n;i++)void 0!==t[i]&&e++;return e===n}(r)){null===n&&(n=new ji(t));const r=h?n.fromEquirectangular(l):n.fromCubemap(l);return e.set(l,r),l.addEventListener("dispose",i),r.texture}return null}}}return l},dispose:function(){e=new WeakMap,null!==n&&(n.dispose(),n=null)}}}function $i(t){const e={};function n(n){if(void 0!==e[n])return e[n];let i;switch(n){case"WEBGL_depth_texture":i=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=t.getExtension(n)}return e[n]=i,i}return{has:function(t){return null!==n(t)},init:function(t){t.isWebGL2?n("EXT_color_buffer_float"):(n("WEBGL_depth_texture"),n("OES_texture_float"),n("OES_texture_half_float"),n("OES_texture_half_float_linear"),n("OES_standard_derivatives"),n("OES_element_index_uint"),n("OES_vertex_array_object"),n("ANGLE_instanced_arrays")),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture")},get:function(t){const e=n(t);return null===e&&console.warn("THREE.WebGLRenderer: "+t+" extension not supported."),e}}}function tr(t,e,n,i){const r={},s=new WeakMap;function a(t){const o=t.target;null!==o.index&&e.remove(o.index);for(const t in o.attributes)e.remove(o.attributes[t]);o.removeEventListener("dispose",a),delete r[o.id];const l=s.get(o);l&&(e.remove(l),s.delete(o)),i.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,n.memory.geometries--}function o(t){const n=[],i=t.index,r=t.attributes.position;let a=0;if(null!==i){const t=i.array;a=i.version;for(let e=0,i=t.length;e<i;e+=3){const i=t[e+0],r=t[e+1],s=t[e+2];n.push(i,r,r,s,s,i)}}else{const t=r.array;a=r.version;for(let e=0,i=t.length/3-1;e<i;e+=3){const t=e+0,i=e+1,r=e+2;n.push(t,i,i,r,r,t)}}const o=new(Lt(n)?wn:Mn)(n,1);o.version=a;const l=s.get(t);l&&e.remove(l),s.set(t,o)}return{get:function(t,e){return!0===r[e.id]||(e.addEventListener("dispose",a),r[e.id]=!0,n.memory.geometries++),e},update:function(t){const n=t.attributes;for(const t in n)e.update(n[t],34962);const i=t.morphAttributes;for(const t in i){const n=i[t];for(let t=0,i=n.length;t<i;t++)e.update(n[t],34962)}},getWireframeAttribute:function(t){const e=s.get(t);if(e){const n=t.index;null!==n&&e.version<n.version&&o(t)}else o(t);return s.get(t)}}}function er(t,e,n,i){const r=i.isWebGL2;let s,a,o;this.setMode=function(t){s=t},this.setIndex=function(t){a=t.type,o=t.bytesPerElement},this.render=function(e,i){t.drawElements(s,i,a,e*o),n.update(i,s,1)},this.renderInstances=function(i,l,c){if(0===c)return;let h,u;if(r)h=t,u="drawElementsInstanced";else if(h=e.get("ANGLE_instanced_arrays"),u="drawElementsInstancedANGLE",null===h)return void console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");h[u](s,l,a,i*o,c),n.update(l,s,c)}}function nr(t){const e={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:e,programs:null,autoReset:!0,reset:function(){e.frame++,e.calls=0,e.triangles=0,e.points=0,e.lines=0},update:function(t,n,i){switch(e.calls++,n){case 4:e.triangles+=i*(t/3);break;case 1:e.lines+=i*(t/2);break;case 3:e.lines+=i*(t-1);break;case 2:e.lines+=i*t;break;case 0:e.points+=i*t;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",n)}}}}class ir extends Vt{constructor(t=null,e=1,n=1,i=1){super(null),this.image={data:t,width:e,height:n,depth:i},this.magFilter=p,this.minFilter=p,this.wrapR=u,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}function rr(t,e){return t[0]-e[0]}function sr(t,e){return Math.abs(e[1])-Math.abs(t[1])}function ar(t,e){let n=1;const i=e.isInterleavedBufferAttribute?e.data.array:e.array;i instanceof Int8Array?n=127:i instanceof Int16Array?n=32767:i instanceof Int32Array?n=2147483647:console.error("THREE.WebGLMorphtargets: Unsupported morph attribute data type: ",i),t.divideScalar(n)}function or(t,e,n){const i={},r=new Float32Array(8),s=new WeakMap,a=new Zt,o=[];for(let t=0;t<8;t++)o[t]=[t,0];return{update:function(l,c,h,u){const d=l.morphTargetInfluences;if(!0===e.isWebGL2){const i=c.morphAttributes.position.length;let r=s.get(c);if(void 0===r||r.count!==i){void 0!==r&&r.texture.dispose();const t=void 0!==c.morphAttributes.normal,n=c.morphAttributes.position,o=c.morphAttributes.normal||[],l=!0===t?2:1;let h=c.attributes.position.count*l,u=1;h>e.maxTextureSize&&(u=Math.ceil(h/e.maxTextureSize),h=e.maxTextureSize);const d=new Float32Array(h*u*4*i),p=new ir(d,h,u,i);p.format=T,p.type=b,p.needsUpdate=!0;const m=4*l;for(let e=0;e<i;e++){const i=n[e],r=o[e],s=h*u*4*e;for(let e=0;e<i.count;e++){a.fromBufferAttribute(i,e),!0===i.normalized&&ar(a,i);const n=e*m;d[s+n+0]=a.x,d[s+n+1]=a.y,d[s+n+2]=a.z,d[s+n+3]=0,!0===t&&(a.fromBufferAttribute(r,e),!0===r.normalized&&ar(a,r),d[s+n+4]=a.x,d[s+n+5]=a.y,d[s+n+6]=a.z,d[s+n+7]=0)}}function f(){p.dispose(),s.delete(c),c.removeEventListener("dispose",f)}r={count:i,texture:p,size:new At(h,u)},s.set(c,r),c.addEventListener("dispose",f)}let o=0;for(let t=0;t<d.length;t++)o+=d[t];const l=c.morphTargetsRelative?1:1-o;u.getUniforms().setValue(t,"morphTargetBaseInfluence",l),u.getUniforms().setValue(t,"morphTargetInfluences",d),u.getUniforms().setValue(t,"morphTargetsTexture",r.texture,n),u.getUniforms().setValue(t,"morphTargetsTextureSize",r.size)}else{const e=void 0===d?0:d.length;let n=i[c.id];if(void 0===n||n.length!==e){n=[];for(let t=0;t<e;t++)n[t]=[t,0];i[c.id]=n}for(let t=0;t<e;t++){const e=n[t];e[0]=t,e[1]=d[t]}n.sort(sr);for(let t=0;t<8;t++)t<e&&n[t][1]?(o[t][0]=n[t][0],o[t][1]=n[t][1]):(o[t][0]=Number.MAX_SAFE_INTEGER,o[t][1]=0);o.sort(rr);const s=c.morphAttributes.position,a=c.morphAttributes.normal;let l=0;for(let t=0;t<8;t++){const e=o[t],n=e[0],i=e[1];n!==Number.MAX_SAFE_INTEGER&&i?(s&&c.getAttribute("morphTarget"+t)!==s[n]&&c.setAttribute("morphTarget"+t,s[n]),a&&c.getAttribute("morphNormal"+t)!==a[n]&&c.setAttribute("morphNormal"+t,a[n]),r[t]=i,l+=i):(s&&!0===c.hasAttribute("morphTarget"+t)&&c.deleteAttribute("morphTarget"+t),a&&!0===c.hasAttribute("morphNormal"+t)&&c.deleteAttribute("morphNormal"+t),r[t]=0)}const h=c.morphTargetsRelative?1:1-l;u.getUniforms().setValue(t,"morphTargetBaseInfluence",h),u.getUniforms().setValue(t,"morphTargetInfluences",r)}}}}function lr(t,e,n,i){let r=new WeakMap;function s(t){const e=t.target;e.removeEventListener("dispose",s),n.remove(e.instanceMatrix),null!==e.instanceColor&&n.remove(e.instanceColor)}return{update:function(t){const a=i.render.frame,o=t.geometry,l=e.get(t,o);return r.get(l)!==a&&(e.update(l),r.set(l,a)),t.isInstancedMesh&&(!1===t.hasEventListener("dispose",s)&&t.addEventListener("dispose",s),n.update(t.instanceMatrix,34962),null!==t.instanceColor&&n.update(t.instanceColor,34962)),l},dispose:function(){r=new WeakMap}}}ir.prototype.isDataTexture2DArray=!0;class cr extends Vt{constructor(t=null,e=1,n=1,i=1){super(null),this.image={data:t,width:e,height:n,depth:i},this.magFilter=p,this.minFilter=p,this.wrapR=u,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}cr.prototype.isDataTexture3D=!0;const hr=new Vt,ur=new ir,dr=new cr,pr=new ci,mr=[],fr=[],gr=new Float32Array(16),vr=new Float32Array(9),yr=new Float32Array(4);function xr(t,e,n){const i=t[0];if(i<=0||i>0)return t;const r=e*n;let s=mr[r];if(void 0===s&&(s=new Float32Array(r),mr[r]=s),0!==e){i.toArray(s,0);for(let i=1,r=0;i!==e;++i)r+=n,t[i].toArray(s,r)}return s}function _r(t,e){if(t.length!==e.length)return!1;for(let n=0,i=t.length;n<i;n++)if(t[n]!==e[n])return!1;return!0}function Mr(t,e){for(let n=0,i=e.length;n<i;n++)t[n]=e[n]}function br(t,e){let n=fr[e];void 0===n&&(n=new Int32Array(e),fr[e]=n);for(let i=0;i!==e;++i)n[i]=t.allocateTextureUnit();return n}function wr(t,e){const n=this.cache;n[0]!==e&&(t.uniform1f(this.addr,e),n[0]=e)}function Sr(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y||(t.uniform2f(this.addr,e.x,e.y),n[0]=e.x,n[1]=e.y);else{if(_r(n,e))return;t.uniform2fv(this.addr,e),Mr(n,e)}}function Tr(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y&&n[2]===e.z||(t.uniform3f(this.addr,e.x,e.y,e.z),n[0]=e.x,n[1]=e.y,n[2]=e.z);else if(void 0!==e.r)n[0]===e.r&&n[1]===e.g&&n[2]===e.b||(t.uniform3f(this.addr,e.r,e.g,e.b),n[0]=e.r,n[1]=e.g,n[2]=e.b);else{if(_r(n,e))return;t.uniform3fv(this.addr,e),Mr(n,e)}}function Er(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y&&n[2]===e.z&&n[3]===e.w||(t.uniform4f(this.addr,e.x,e.y,e.z,e.w),n[0]=e.x,n[1]=e.y,n[2]=e.z,n[3]=e.w);else{if(_r(n,e))return;t.uniform4fv(this.addr,e),Mr(n,e)}}function Ar(t,e){const n=this.cache,i=e.elements;if(void 0===i){if(_r(n,e))return;t.uniformMatrix2fv(this.addr,!1,e),Mr(n,e)}else{if(_r(n,i))return;yr.set(i),t.uniformMatrix2fv(this.addr,!1,yr),Mr(n,i)}}function Rr(t,e){const n=this.cache,i=e.elements;if(void 0===i){if(_r(n,e))return;t.uniformMatrix3fv(this.addr,!1,e),Mr(n,e)}else{if(_r(n,i))return;vr.set(i),t.uniformMatrix3fv(this.addr,!1,vr),Mr(n,i)}}function Lr(t,e){const n=this.cache,i=e.elements;if(void 0===i){if(_r(n,e))return;t.uniformMatrix4fv(this.addr,!1,e),Mr(n,e)}else{if(_r(n,i))return;gr.set(i),t.uniformMatrix4fv(this.addr,!1,gr),Mr(n,i)}}function Cr(t,e){const n=this.cache;n[0]!==e&&(t.uniform1i(this.addr,e),n[0]=e)}function Pr(t,e){const n=this.cache;_r(n,e)||(t.uniform2iv(this.addr,e),Mr(n,e))}function Dr(t,e){const n=this.cache;_r(n,e)||(t.uniform3iv(this.addr,e),Mr(n,e))}function Ir(t,e){const n=this.cache;_r(n,e)||(t.uniform4iv(this.addr,e),Mr(n,e))}function Nr(t,e){const n=this.cache;n[0]!==e&&(t.uniform1ui(this.addr,e),n[0]=e)}function Br(t,e){const n=this.cache;_r(n,e)||(t.uniform2uiv(this.addr,e),Mr(n,e))}function zr(t,e){const n=this.cache;_r(n,e)||(t.uniform3uiv(this.addr,e),Mr(n,e))}function Or(t,e){const n=this.cache;_r(n,e)||(t.uniform4uiv(this.addr,e),Mr(n,e))}function Fr(t,e,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(t.uniform1i(this.addr,r),i[0]=r),n.safeSetTexture2D(e||hr,r)}function Ur(t,e,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(t.uniform1i(this.addr,r),i[0]=r),n.setTexture3D(e||dr,r)}function Hr(t,e,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(t.uniform1i(this.addr,r),i[0]=r),n.safeSetTextureCube(e||pr,r)}function Gr(t,e,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(t.uniform1i(this.addr,r),i[0]=r),n.setTexture2DArray(e||ur,r)}function kr(t,e){t.uniform1fv(this.addr,e)}function Vr(t,e){const n=xr(e,this.size,2);t.uniform2fv(this.addr,n)}function Wr(t,e){const n=xr(e,this.size,3);t.uniform3fv(this.addr,n)}function jr(t,e){const n=xr(e,this.size,4);t.uniform4fv(this.addr,n)}function qr(t,e){const n=xr(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,n)}function Xr(t,e){const n=xr(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,n)}function Jr(t,e){const n=xr(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,n)}function Yr(t,e){t.uniform1iv(this.addr,e)}function Zr(t,e){t.uniform2iv(this.addr,e)}function Kr(t,e){t.uniform3iv(this.addr,e)}function Qr(t,e){t.uniform4iv(this.addr,e)}function $r(t,e){t.uniform1uiv(this.addr,e)}function ts(t,e){t.uniform2uiv(this.addr,e)}function es(t,e){t.uniform3uiv(this.addr,e)}function ns(t,e){t.uniform4uiv(this.addr,e)}function is(t,e,n){const i=e.length,r=br(n,i);t.uniform1iv(this.addr,r);for(let t=0;t!==i;++t)n.safeSetTexture2D(e[t]||hr,r[t])}function rs(t,e,n){const i=e.length,r=br(n,i);t.uniform1iv(this.addr,r);for(let t=0;t!==i;++t)n.setTexture3D(e[t]||dr,r[t])}function ss(t,e,n){const i=e.length,r=br(n,i);t.uniform1iv(this.addr,r);for(let t=0;t!==i;++t)n.safeSetTextureCube(e[t]||pr,r[t])}function as(t,e,n){const i=e.length,r=br(n,i);t.uniform1iv(this.addr,r);for(let t=0;t!==i;++t)n.setTexture2DArray(e[t]||ur,r[t])}function os(t,e,n){this.id=t,this.addr=n,this.cache=[],this.setValue=function(t){switch(t){case 5126:return wr;case 35664:return Sr;case 35665:return Tr;case 35666:return Er;case 35674:return Ar;case 35675:return Rr;case 35676:return Lr;case 5124:case 35670:return Cr;case 35667:case 35671:return Pr;case 35668:case 35672:return Dr;case 35669:case 35673:return Ir;case 5125:return Nr;case 36294:return Br;case 36295:return zr;case 36296:return Or;case 35678:case 36198:case 36298:case 36306:case 35682:return Fr;case 35679:case 36299:case 36307:return Ur;case 35680:case 36300:case 36308:case 36293:return Hr;case 36289:case 36303:case 36311:case 36292:return Gr}}(e.type)}function ls(t,e,n){this.id=t,this.addr=n,this.cache=[],this.size=e.size,this.setValue=function(t){switch(t){case 5126:return kr;case 35664:return Vr;case 35665:return Wr;case 35666:return jr;case 35674:return qr;case 35675:return Xr;case 35676:return Jr;case 5124:case 35670:return Yr;case 35667:case 35671:return Zr;case 35668:case 35672:return Kr;case 35669:case 35673:return Qr;case 5125:return $r;case 36294:return ts;case 36295:return es;case 36296:return ns;case 35678:case 36198:case 36298:case 36306:case 35682:return is;case 35679:case 36299:case 36307:return rs;case 35680:case 36300:case 36308:case 36293:return ss;case 36289:case 36303:case 36311:case 36292:return as}}(e.type)}function cs(t){this.id=t,this.seq=[],this.map={}}ls.prototype.updateCache=function(t){const e=this.cache;t instanceof Float32Array&&e.length!==t.length&&(this.cache=new Float32Array(t.length)),Mr(e,t)},cs.prototype.setValue=function(t,e,n){const i=this.seq;for(let r=0,s=i.length;r!==s;++r){const s=i[r];s.setValue(t,e[s.id],n)}};const hs=/(\w+)(\])?(\[|\.)?/g;function us(t,e){t.seq.push(e),t.map[e.id]=e}function ds(t,e,n){const i=t.name,r=i.length;for(hs.lastIndex=0;;){const s=hs.exec(i),a=hs.lastIndex;let o=s[1];const l="]"===s[2],c=s[3];if(l&&(o|=0),void 0===c||"["===c&&a+2===r){us(n,void 0===c?new os(o,t,e):new ls(o,t,e));break}{let t=n.map[o];void 0===t&&(t=new cs(o),us(n,t)),n=t}}}function ps(t,e){this.seq=[],this.map={};const n=t.getProgramParameter(e,35718);for(let i=0;i<n;++i){const n=t.getActiveUniform(e,i);ds(n,t.getUniformLocation(e,n.name),this)}}function ms(t,e,n){const i=t.createShader(e);return t.shaderSource(i,n),t.compileShader(i),i}ps.prototype.setValue=function(t,e,n,i){const r=this.map[e];void 0!==r&&r.setValue(t,n,i)},ps.prototype.setOptional=function(t,e,n){const i=e[n];void 0!==i&&this.setValue(t,n,i)},ps.upload=function(t,e,n,i){for(let r=0,s=e.length;r!==s;++r){const s=e[r],a=n[s.id];!1!==a.needsUpdate&&s.setValue(t,a.value,i)}},ps.seqWithValue=function(t,e){const n=[];for(let i=0,r=t.length;i!==r;++i){const r=t[i];r.id in e&&n.push(r)}return n};let fs=0;function gs(t,e,n){const i=t.getShaderParameter(e,35713),r=t.getShaderInfoLog(e).trim();return i&&""===r?"":n.toUpperCase()+"\n\n"+r+"\n\n"+function(t){const e=t.split("\n");for(let t=0;t<e.length;t++)e[t]=t+1+": "+e[t];return e.join("\n")}(t.getShaderSource(e))}function vs(t,e){const n=function(t){switch(t){case ot:return["Linear","( value )"];case lt:return["sRGB","( value )"];default:return console.warn("THREE.WebGLProgram: Unsupported encoding:",t),["Linear","( value )"]}}(e);return"vec4 "+t+"( vec4 value ) { return LinearTo"+n[0]+n[1]+"; }"}function ys(t,e){let n;switch(e){case 1:n="Linear";break;case 2:n="Reinhard";break;case 3:n="OptimizedCineon";break;case 4:n="ACESFilmic";break;case 5:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}function xs(t){return""!==t}function _s(t,e){return t.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function Ms(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const bs=/^[ \t]*#include +<([\w\d./]+)>/gm;function ws(t){return t.replace(bs,Ss)}function Ss(t,e){const n=Mi[e];if(void 0===n)throw new Error("Can not resolve #include <"+e+">");return ws(n)}const Ts=/#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,Es=/#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 As(t){return t.replace(Es,Ls).replace(Ts,Rs)}function Rs(t,e,n,i){return console.warn("WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead."),Ls(t,e,n,i)}function Ls(t,e,n,i){let r="";for(let t=parseInt(e);t<parseInt(n);t++)r+=i.replace(/\[\s*i\s*\]/g,"[ "+t+" ]").replace(/UNROLLED_LOOP_INDEX/g,t);return r}function Cs(t){let e="precision "+t.precision+" float;\nprecision "+t.precision+" int;";return"highp"===t.precision?e+="\n#define HIGH_PRECISION":"mediump"===t.precision?e+="\n#define MEDIUM_PRECISION":"lowp"===t.precision&&(e+="\n#define LOW_PRECISION"),e}function Ps(t,e,n,i){const a=t.getContext(),o=n.defines;let h=n.vertexShader,u=n.fragmentShader;const d=function(t){let e="SHADOWMAP_TYPE_BASIC";return 1===t.shadowMapType?e="SHADOWMAP_TYPE_PCF":2===t.shadowMapType?e="SHADOWMAP_TYPE_PCF_SOFT":3===t.shadowMapType&&(e="SHADOWMAP_TYPE_VSM"),e}(n),p=function(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case r:case s:e="ENVMAP_TYPE_CUBE";break;case l:case c:e="ENVMAP_TYPE_CUBE_UV"}return e}(n),m=function(t){let e="ENVMAP_MODE_REFLECTION";if(t.envMap)switch(t.envMapMode){case s:case c:e="ENVMAP_MODE_REFRACTION"}return e}(n),f=function(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case 0:e="ENVMAP_BLENDING_MULTIPLY";break;case 1:e="ENVMAP_BLENDING_MIX";break;case 2:e="ENVMAP_BLENDING_ADD"}return e}(n),g=n.isWebGL2?"":function(t){return[t.extensionDerivatives||t.envMapCubeUV||t.bumpMap||t.tangentSpaceNormalMap||t.clearcoatNormalMap||t.flatShading||"physical"===t.shaderID?"#extension GL_OES_standard_derivatives : enable":"",(t.extensionFragDepth||t.logarithmicDepthBuffer)&&t.rendererExtensionFragDepth?"#extension GL_EXT_frag_depth : enable":"",t.extensionDrawBuffers&&t.rendererExtensionDrawBuffers?"#extension GL_EXT_draw_buffers : require":"",(t.extensionShaderTextureLOD||t.envMap||t.transmission)&&t.rendererExtensionShaderTextureLod?"#extension GL_EXT_shader_texture_lod : enable":""].filter(xs).join("\n")}(n),v=function(t){const e=[];for(const n in t){const i=t[n];!1!==i&&e.push("#define "+n+" "+i)}return e.join("\n")}(o),y=a.createProgram();let x,_,M=n.glslVersion?"#version "+n.glslVersion+"\n":"";n.isRawShaderMaterial?(x=[v].filter(xs).join("\n"),x.length>0&&(x+="\n"),_=[g,v].filter(xs).join("\n"),_.length>0&&(_+="\n")):(x=[Cs(n),"#define SHADER_NAME "+n.shaderName,v,n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define MAX_BONES "+n.maxBones,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+m:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMap&&n.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",n.normalMap&&n.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.displacementMap&&n.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",n.specularColorMap?"#define USE_SPECULARCOLORMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEENCOLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",n.vertexTangents?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUvs?"#define USE_UV":"",n.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.useVertexTexture?"#define BONE_TEXTURE":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphTargets&&n.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",n.morphTargets&&n.isWebGL2?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+d:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.logarithmicDepthBuffer&&n.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(xs).join("\n"),_=[g,Cs(n),"#define SHADER_NAME "+n.shaderName,v,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+p:"",n.envMap?"#define "+m:"",n.envMap?"#define "+f:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMap&&n.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",n.normalMap&&n.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",n.specularColorMap?"#define USE_SPECULARCOLORMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEENCOLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.vertexTangents?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUvs?"#define USE_UV":"",n.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+d:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.logarithmicDepthBuffer&&n.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"",(n.extensionShaderTextureLOD||n.envMap)&&n.rendererExtensionShaderTextureLod?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?Mi.tonemapping_pars_fragment:"",0!==n.toneMapping?ys("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.alphaWrite?"":"#define OPAQUE",Mi.encodings_pars_fragment,vs("linearToOutputTexel",n.outputEncoding),n.depthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(xs).join("\n")),h=ws(h),h=_s(h,n),h=Ms(h,n),u=ws(u),u=_s(u,n),u=Ms(u,n),h=As(h),u=As(u),n.isWebGL2&&!0!==n.isRawShaderMaterial&&(M="#version 300 es\n",x=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+x,_=["#define varying in",n.glslVersion===dt?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===dt?"":"#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"+_);const b=M+_+u,w=ms(a,35633,M+x+h),S=ms(a,35632,b);if(a.attachShader(y,w),a.attachShader(y,S),void 0!==n.index0AttributeName?a.bindAttribLocation(y,0,n.index0AttributeName):!0===n.morphTargets&&a.bindAttribLocation(y,0,"position"),a.linkProgram(y),t.debug.checkShaderErrors){const t=a.getProgramInfoLog(y).trim(),e=a.getShaderInfoLog(w).trim(),n=a.getShaderInfoLog(S).trim();let i=!0,r=!0;if(!1===a.getProgramParameter(y,35714)){i=!1;const e=gs(a,w,"vertex"),n=gs(a,S,"fragment");console.error("THREE.WebGLProgram: Shader Error "+a.getError()+" - VALIDATE_STATUS "+a.getProgramParameter(y,35715)+"\n\nProgram Info Log: "+t+"\n"+e+"\n"+n)}else""!==t?console.warn("THREE.WebGLProgram: Program Info Log:",t):""!==e&&""!==n||(r=!1);r&&(this.diagnostics={runnable:i,programLog:t,vertexShader:{log:e,prefix:x},fragmentShader:{log:n,prefix:_}})}let T,E;return a.deleteShader(w),a.deleteShader(S),this.getUniforms=function(){return void 0===T&&(T=new ps(a,y)),T},this.getAttributes=function(){return void 0===E&&(E=function(t,e){const n={},i=t.getProgramParameter(e,35721);for(let r=0;r<i;r++){const i=t.getActiveAttrib(e,r),s=i.name;let a=1;35674===i.type&&(a=2),35675===i.type&&(a=3),35676===i.type&&(a=4),n[s]={type:i.type,location:t.getAttribLocation(e,s),locationSize:a}}return n}(a,y)),E},this.destroy=function(){i.releaseStatesOfProgram(this),a.deleteProgram(y),this.program=void 0},this.name=n.shaderName,this.id=fs++,this.cacheKey=e,this.usedTimes=1,this.program=y,this.vertexShader=w,this.fragmentShader=S,this}let Ds=0;class Is{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t){const e=t.vertexShader,n=t.fragmentShader,i=this._getShaderStage(e),r=this._getShaderStage(n),s=this._getShaderCacheForMaterial(t);return!1===s.has(i)&&(s.add(i),i.usedTimes++),!1===s.has(r)&&(s.add(r),r.usedTimes++),this}remove(t){const e=this.materialCache.get(t);for(const t of e)t.usedTimes--,0===t.usedTimes&&this.shaderCache.delete(t);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;return!1===e.has(t)&&e.set(t,new Set),e.get(t)}_getShaderStage(t){const e=this.shaderCache;if(!1===e.has(t)){const n=new Ns;e.set(t,n)}return e.get(t)}}class Ns{constructor(){this.id=Ds++,this.usedTimes=0}}function Bs(t,e,n,i,r,s,a){const o=new Fe,h=new Is,u=[],d=r.isWebGL2,p=r.logarithmicDepthBuffer,m=r.floatVertexTextures,f=r.maxVertexUniforms,g=r.vertexTextures;let v=r.precision;const y={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",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"};return{getParameters:function(s,o,u,x,_){const M=x.fog,b=s.isMeshStandardMaterial?x.environment:null,w=(s.isMeshStandardMaterial?n:e).get(s.envMap||b),S=y[s.type],T=_.isSkinnedMesh?function(t){const e=t.skeleton.bones;if(m)return 1024;{const t=f,n=Math.floor((t-20)/4),i=Math.min(n,e.length);return i<e.length?(console.warn("THREE.WebGLRenderer: Skeleton has "+e.length+" bones. This GPU supports "+i+"."),0):i}}(_):0;let E,A,R,L;if(null!==s.precision&&(v=r.getMaxPrecision(s.precision),v!==s.precision&&console.warn("THREE.WebGLProgram.getParameters:",s.precision,"not supported, using",v,"instead.")),S){const t=wi[S];E=t.vertexShader,A=t.fragmentShader}else E=s.vertexShader,A=s.fragmentShader,h.update(s),R=h.getVertexShaderID(s),L=h.getFragmentShaderID(s);const C=t.getRenderTarget(),P=s.alphaTest>0,D=s.clearcoat>0;return{isWebGL2:d,shaderID:S,shaderName:s.type,vertexShader:E,fragmentShader:A,defines:s.defines,customVertexShaderID:R,customFragmentShaderID:L,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:v,instancing:!0===_.isInstancedMesh,instancingColor:!0===_.isInstancedMesh&&null!==_.instanceColor,supportsVertexTextures:g,outputEncoding:null===C?t.outputEncoding:!0===C.isXRRenderTarget?C.texture.encoding:ot,map:!!s.map,matcap:!!s.matcap,envMap:!!w,envMapMode:w&&w.mapping,envMapCubeUV:!!w&&(w.mapping===l||w.mapping===c),lightMap:!!s.lightMap,aoMap:!!s.aoMap,emissiveMap:!!s.emissiveMap,bumpMap:!!s.bumpMap,normalMap:!!s.normalMap,objectSpaceNormalMap:1===s.normalMapType,tangentSpaceNormalMap:0===s.normalMapType,decodeVideoTexture:!!s.map&&!0===s.map.isVideoTexture&&s.map.encoding===lt,clearcoat:D,clearcoatMap:D&&!!s.clearcoatMap,clearcoatRoughnessMap:D&&!!s.clearcoatRoughnessMap,clearcoatNormalMap:D&&!!s.clearcoatNormalMap,displacementMap:!!s.displacementMap,roughnessMap:!!s.roughnessMap,metalnessMap:!!s.metalnessMap,specularMap:!!s.specularMap,specularIntensityMap:!!s.specularIntensityMap,specularColorMap:!!s.specularColorMap,alphaMap:!!s.alphaMap,alphaTest:P,alphaWrite:s.alphaWrite||s.transparent,gradientMap:!!s.gradientMap,sheen:s.sheen>0,sheenColorMap:!!s.sheenColorMap,sheenRoughnessMap:!!s.sheenRoughnessMap,transmission:s.transmission>0,transmissionMap:!!s.transmissionMap,thicknessMap:!!s.thicknessMap,combine:s.combine,vertexTangents:!!s.normalMap&&!!_.geometry&&!!_.geometry.attributes.tangent,vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!_.geometry&&!!_.geometry.attributes.color&&4===_.geometry.attributes.color.itemSize,vertexUvs:!!(s.map||s.bumpMap||s.normalMap||s.specularMap||s.alphaMap||s.emissiveMap||s.roughnessMap||s.metalnessMap||s.clearcoatMap||s.clearcoatRoughnessMap||s.clearcoatNormalMap||s.displacementMap||s.transmissionMap||s.thicknessMap||s.specularIntensityMap||s.specularColorMap||s.sheenColorMap||s.sheenRoughnessMap),uvsVertexOnly:!(s.map||s.bumpMap||s.normalMap||s.specularMap||s.alphaMap||s.emissiveMap||s.roughnessMap||s.metalnessMap||s.clearcoatNormalMap||s.transmission>0||s.transmissionMap||s.thicknessMap||s.specularIntensityMap||s.specularColorMap||s.sheen>0||s.sheenColorMap||s.sheenRoughnessMap||!s.displacementMap),fog:!!M,useFog:s.fog,fogExp2:M&&M.isFogExp2,flatShading:!!s.flatShading,sizeAttenuation:s.sizeAttenuation,logarithmicDepthBuffer:p,skinning:!0===_.isSkinnedMesh&&T>0,maxBones:T,useVertexTexture:m,morphTargets:!!_.geometry&&!!_.geometry.morphAttributes.position,morphNormals:!!_.geometry&&!!_.geometry.morphAttributes.normal,morphTargetsCount:_.geometry&&_.geometry.morphAttributes.position?_.geometry.morphAttributes.position.length:0,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:s.dithering,shadowMapEnabled:t.shadowMap.enabled&&u.length>0,shadowMapType:t.shadowMap.type,toneMapping:s.toneMapped?t.toneMapping:0,physicallyCorrectLights:t.physicallyCorrectLights,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:1===s.side,depthPacking:void 0!==s.depthPacking&&s.depthPacking,index0AttributeName:s.index0AttributeName,extensionDerivatives:s.extensions&&s.extensions.derivatives,extensionFragDepth:s.extensions&&s.extensions.fragDepth,extensionDrawBuffers:s.extensions&&s.extensions.drawBuffers,extensionShaderTextureLOD:s.extensions&&s.extensions.shaderTextureLOD,rendererExtensionFragDepth:d||i.has("EXT_frag_depth"),rendererExtensionDrawBuffers:d||i.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:d||i.has("EXT_shader_texture_lod"),customProgramCacheKey:s.customProgramCacheKey()}},getProgramCacheKey:function(e){const n=[];if(e.shaderID?n.push(e.shaderID):(n.push(e.customVertexShaderID),n.push(e.customFragmentShaderID)),void 0!==e.defines)for(const t in e.defines)n.push(t),n.push(e.defines[t]);return!1===e.isRawShaderMaterial&&(!function(t,e){t.push(e.precision),t.push(e.outputEncoding),t.push(e.envMapMode),t.push(e.combine),t.push(e.vertexUvs),t.push(e.fogExp2),t.push(e.sizeAttenuation),t.push(e.maxBones),t.push(e.morphTargetsCount),t.push(e.numDirLights),t.push(e.numPointLights),t.push(e.numSpotLights),t.push(e.numHemiLights),t.push(e.numRectAreaLights),t.push(e.numDirLightShadows),t.push(e.numPointLightShadows),t.push(e.numSpotLightShadows),t.push(e.shadowMapType),t.push(e.toneMapping),t.push(e.numClippingPlanes),t.push(e.numClipIntersection),t.push(e.alphaWrite)}(n,e),function(t,e){o.disableAll(),e.isWebGL2&&o.enable(0);e.supportsVertexTextures&&o.enable(1);e.instancing&&o.enable(2);e.instancingColor&&o.enable(3);e.map&&o.enable(4);e.matcap&&o.enable(5);e.envMap&&o.enable(6);e.envMapCubeUV&&o.enable(7);e.lightMap&&o.enable(8);e.aoMap&&o.enable(9);e.emissiveMap&&o.enable(10);e.bumpMap&&o.enable(11);e.normalMap&&o.enable(12);e.objectSpaceNormalMap&&o.enable(13);e.tangentSpaceNormalMap&&o.enable(14);e.clearcoat&&o.enable(15);e.clearcoatMap&&o.enable(16);e.clearcoatRoughnessMap&&o.enable(17);e.clearcoatNormalMap&&o.enable(18);e.displacementMap&&o.enable(19);e.specularMap&&o.enable(20);e.roughnessMap&&o.enable(21);e.metalnessMap&&o.enable(22);e.gradientMap&&o.enable(23);e.alphaMap&&o.enable(24);e.alphaTest&&o.enable(25);e.vertexColors&&o.enable(26);e.vertexAlphas&&o.enable(27);e.vertexUvs&&o.enable(28);e.vertexTangents&&o.enable(29);e.uvsVertexOnly&&o.enable(30);e.fog&&o.enable(31);t.push(o.mask),o.disableAll(),e.useFog&&o.enable(0);e.flatShading&&o.enable(1);e.logarithmicDepthBuffer&&o.enable(2);e.skinning&&o.enable(3);e.useVertexTexture&&o.enable(4);e.morphTargets&&o.enable(5);e.morphNormals&&o.enable(6);e.premultipliedAlpha&&o.enable(7);e.shadowMapEnabled&&o.enable(8);e.physicallyCorrectLights&&o.enable(9);e.doubleSided&&o.enable(10);e.flipSided&&o.enable(11);e.depthPacking&&o.enable(12);e.dithering&&o.enable(13);e.specularIntensityMap&&o.enable(14);e.specularColorMap&&o.enable(15);e.transmission&&o.enable(16);e.transmissionMap&&o.enable(17);e.thicknessMap&&o.enable(18);e.sheen&&o.enable(19);e.sheenColorMap&&o.enable(20);e.sheenRoughnessMap&&o.enable(21);e.decodeVideoTexture&&o.enable(22);t.push(o.mask)}(n,e),n.push(t.outputEncoding)),n.push(e.customProgramCacheKey),n.join()},getUniforms:function(t){const e=y[t.type];let n;if(e){const t=wi[e];n=ii.clone(t.uniforms)}else n=t.uniforms;return n},acquireProgram:function(e,n){let i;for(let t=0,e=u.length;t<e;t++){const e=u[t];if(e.cacheKey===n){i=e,++i.usedTimes;break}}return void 0===i&&(i=new Ps(t,n,e,s),u.push(i)),i},releaseProgram:function(t){if(0==--t.usedTimes){const e=u.indexOf(t);u[e]=u[u.length-1],u.pop(),t.destroy()}},releaseShaderCache:function(t){h.remove(t)},programs:u,dispose:function(){h.dispose()}}}function zs(){let t=new WeakMap;return{get:function(e){let n=t.get(e);return void 0===n&&(n={},t.set(e,n)),n},remove:function(e){t.delete(e)},update:function(e,n,i){t.get(e)[n]=i},dispose:function(){t=new WeakMap}}}function Os(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function Fs(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function Us(){const t=[];let e=0;const n=[],i=[],r=[];function s(n,i,r,s,a,o){let l=t[e];return void 0===l?(l={id:n.id,object:n,geometry:i,material:r,groupOrder:s,renderOrder:n.renderOrder,z:a,group:o},t[e]=l):(l.id=n.id,l.object=n,l.geometry=i,l.material=r,l.groupOrder=s,l.renderOrder=n.renderOrder,l.z=a,l.group=o),e++,l}return{opaque:n,transmissive:i,transparent:r,init:function(){e=0,n.length=0,i.length=0,r.length=0},push:function(t,e,a,o,l,c){const h=s(t,e,a,o,l,c);a.transmission>0?i.push(h):!0===a.transparent?r.push(h):n.push(h)},unshift:function(t,e,a,o,l,c){const h=s(t,e,a,o,l,c);a.transmission>0?i.unshift(h):!0===a.transparent?r.unshift(h):n.unshift(h)},finish:function(){for(let n=e,i=t.length;n<i;n++){const e=t[n];if(null===e.id)break;e.id=null,e.object=null,e.geometry=null,e.material=null,e.group=null}},sort:function(t,e){n.length>1&&n.sort(t||Os),i.length>1&&i.sort(e||Fs),r.length>1&&r.sort(e||Fs)}}}function Hs(){let t=new WeakMap;return{get:function(e,n){let i;return!1===t.has(e)?(i=new Us,t.set(e,[i])):n>=t.get(e).length?(i=new Us,t.get(e).push(i)):i=t.get(e)[n],i},dispose:function(){t=new WeakMap}}}function Gs(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let n;switch(e.type){case"DirectionalLight":n={direction:new Zt,color:new Ut};break;case"SpotLight":n={position:new Zt,direction:new Zt,color:new Ut,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Zt,color:new Ut,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Zt,skyColor:new Ut,groundColor:new Ut};break;case"RectAreaLight":n={color:new Ut,position:new Zt,halfWidth:new Zt,halfHeight:new Zt}}return t[e.id]=n,n}}}let ks=0;function Vs(t,e){return(e.castShadow?1:0)-(t.castShadow?1:0)}function Ws(t,e){const n=new Gs,i=function(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let n;switch(e.type){case"DirectionalLight":case"SpotLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new At};break;case"PointLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new At,shadowCameraNear:1,shadowCameraFar:1e3}}return t[e.id]=n,n}}}(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadow:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]};for(let t=0;t<9;t++)r.probe.push(new Zt);const s=new Zt,a=new Ae,o=new Ae;return{setup:function(s,a){let o=0,l=0,c=0;for(let t=0;t<9;t++)r.probe[t].set(0,0,0);let h=0,u=0,d=0,p=0,m=0,f=0,g=0,v=0;s.sort(Vs);const y=!0!==a?Math.PI:1;for(let t=0,e=s.length;t<e;t++){const e=s[t],a=e.color,x=e.intensity,_=e.distance,M=e.shadow&&e.shadow.map?e.shadow.map.texture:null;if(e.isAmbientLight)o+=a.r*x*y,l+=a.g*x*y,c+=a.b*x*y;else if(e.isLightProbe)for(let t=0;t<9;t++)r.probe[t].addScaledVector(e.sh.coefficients[t],x);else if(e.isDirectionalLight){const t=n.get(e);if(t.color.copy(e.color).multiplyScalar(e.intensity*y),e.castShadow){const t=e.shadow,n=i.get(e);n.shadowBias=t.bias,n.shadowNormalBias=t.normalBias,n.shadowRadius=t.radius,n.shadowMapSize=t.mapSize,r.directionalShadow[h]=n,r.directionalShadowMap[h]=M,r.directionalShadowMatrix[h]=e.shadow.matrix,f++}r.directional[h]=t,h++}else if(e.isSpotLight){const t=n.get(e);if(t.position.setFromMatrixPosition(e.matrixWorld),t.color.copy(a).multiplyScalar(x*y),t.distance=_,t.coneCos=Math.cos(e.angle),t.penumbraCos=Math.cos(e.angle*(1-e.penumbra)),t.decay=e.decay,e.castShadow){const t=e.shadow,n=i.get(e);n.shadowBias=t.bias,n.shadowNormalBias=t.normalBias,n.shadowRadius=t.radius,n.shadowMapSize=t.mapSize,r.spotShadow[d]=n,r.spotShadowMap[d]=M,r.spotShadowMatrix[d]=e.shadow.matrix,v++}r.spot[d]=t,d++}else if(e.isRectAreaLight){const t=n.get(e);t.color.copy(a).multiplyScalar(x),t.halfWidth.set(.5*e.width,0,0),t.halfHeight.set(0,.5*e.height,0),r.rectArea[p]=t,p++}else if(e.isPointLight){const t=n.get(e);if(t.color.copy(e.color).multiplyScalar(e.intensity*y),t.distance=e.distance,t.decay=e.decay,e.castShadow){const t=e.shadow,n=i.get(e);n.shadowBias=t.bias,n.shadowNormalBias=t.normalBias,n.shadowRadius=t.radius,n.shadowMapSize=t.mapSize,n.shadowCameraNear=t.camera.near,n.shadowCameraFar=t.camera.far,r.pointShadow[u]=n,r.pointShadowMap[u]=M,r.pointShadowMatrix[u]=e.shadow.matrix,g++}r.point[u]=t,u++}else if(e.isHemisphereLight){const t=n.get(e);t.skyColor.copy(e.color).multiplyScalar(x*y),t.groundColor.copy(e.groundColor).multiplyScalar(x*y),r.hemi[m]=t,m++}}p>0&&(e.isWebGL2||!0===t.has("OES_texture_float_linear")?(r.rectAreaLTC1=bi.LTC_FLOAT_1,r.rectAreaLTC2=bi.LTC_FLOAT_2):!0===t.has("OES_texture_half_float_linear")?(r.rectAreaLTC1=bi.LTC_HALF_1,r.rectAreaLTC2=bi.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),r.ambient[0]=o,r.ambient[1]=l,r.ambient[2]=c;const x=r.hash;x.directionalLength===h&&x.pointLength===u&&x.spotLength===d&&x.rectAreaLength===p&&x.hemiLength===m&&x.numDirectionalShadows===f&&x.numPointShadows===g&&x.numSpotShadows===v||(r.directional.length=h,r.spot.length=d,r.rectArea.length=p,r.point.length=u,r.hemi.length=m,r.directionalShadow.length=f,r.directionalShadowMap.length=f,r.pointShadow.length=g,r.pointShadowMap.length=g,r.spotShadow.length=v,r.spotShadowMap.length=v,r.directionalShadowMatrix.length=f,r.pointShadowMatrix.length=g,r.spotShadowMatrix.length=v,x.directionalLength=h,x.pointLength=u,x.spotLength=d,x.rectAreaLength=p,x.hemiLength=m,x.numDirectionalShadows=f,x.numPointShadows=g,x.numSpotShadows=v,r.version=ks++)},setupView:function(t,e){let n=0,i=0,l=0,c=0,h=0;const u=e.matrixWorldInverse;for(let e=0,d=t.length;e<d;e++){const d=t[e];if(d.isDirectionalLight){const t=r.directional[n];t.direction.setFromMatrixPosition(d.matrixWorld),s.setFromMatrixPosition(d.target.matrixWorld),t.direction.sub(s),t.direction.transformDirection(u),n++}else if(d.isSpotLight){const t=r.spot[l];t.position.setFromMatrixPosition(d.matrixWorld),t.position.applyMatrix4(u),t.direction.setFromMatrixPosition(d.matrixWorld),s.setFromMatrixPosition(d.target.matrixWorld),t.direction.sub(s),t.direction.transformDirection(u),l++}else if(d.isRectAreaLight){const t=r.rectArea[c];t.position.setFromMatrixPosition(d.matrixWorld),t.position.applyMatrix4(u),o.identity(),a.copy(d.matrixWorld),a.premultiply(u),o.extractRotation(a),t.halfWidth.set(.5*d.width,0,0),t.halfHeight.set(0,.5*d.height,0),t.halfWidth.applyMatrix4(o),t.halfHeight.applyMatrix4(o),c++}else if(d.isPointLight){const t=r.point[i];t.position.setFromMatrixPosition(d.matrixWorld),t.position.applyMatrix4(u),i++}else if(d.isHemisphereLight){const t=r.hemi[h];t.direction.setFromMatrixPosition(d.matrixWorld),t.direction.transformDirection(u),t.direction.normalize(),h++}}},state:r}}function js(t,e){const n=new Ws(t,e),i=[],r=[];return{init:function(){i.length=0,r.length=0},state:{lightsArray:i,shadowsArray:r,lights:n},setupLights:function(t){n.setup(i,t)},setupLightsView:function(t){n.setupView(i,t)},pushLight:function(t){i.push(t)},pushShadow:function(t){r.push(t)}}}function qs(t,e){let n=new WeakMap;return{get:function(i,r=0){let s;return!1===n.has(i)?(s=new js(t,e),n.set(i,[s])):r>=n.get(i).length?(s=new js(t,e),n.get(i).push(s)):s=n.get(i)[r],s},dispose:function(){n=new WeakMap}}}class Xs extends dn{constructor(t){super(),this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!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}}Xs.prototype.isMeshDepthMaterial=!0;class Js extends dn{constructor(t){super(),this.type="MeshDistanceMaterial",this.referencePosition=new Zt,this.nearDistance=1,this.farDistance=1e3,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.fog=!1,this.setValues(t)}copy(t){return super.copy(t),this.referencePosition.copy(t.referencePosition),this.nearDistance=t.nearDistance,this.farDistance=t.farDistance,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}Js.prototype.isMeshDistanceMaterial=!0;function Ys(t,e,n){let i=new vi;const r=new At,s=new At,a=new jt,o=new Xs({depthPacking:3201}),l=new Js,c={},h=n.maxTextureSize,u={0:1,1:0,2:2},d=new ri({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new At},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),m=d.clone();m.defines.HORIZONTAL_PASS=1;const f=new Nn;f.setAttribute("position",new gn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Qn(f,d),y=this;function x(n,i){const r=e.update(v);d.defines.VSM_SAMPLES!==n.blurSamples&&(d.defines.VSM_SAMPLES=n.blurSamples,m.defines.VSM_SAMPLES=n.blurSamples,d.needsUpdate=!0,m.needsUpdate=!0),d.uniforms.shadow_pass.value=n.map.texture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,t.setRenderTarget(n.mapPass),t.clear(),t.renderBufferDirect(i,null,r,d,v,null),m.uniforms.shadow_pass.value=n.mapPass.texture,m.uniforms.resolution.value=n.mapSize,m.uniforms.radius.value=n.radius,t.setRenderTarget(n.map),t.clear(),t.renderBufferDirect(i,null,r,m,v,null)}function _(e,n,i,r,s,a,h){let d=null;const p=!0===r.isPointLight?e.customDistanceMaterial:e.customDepthMaterial;if(d=void 0!==p?p:!0===r.isPointLight?l:o,t.localClippingEnabled&&!0===i.clipShadows&&0!==i.clippingPlanes.length||i.displacementMap&&0!==i.displacementScale||i.alphaMap&&i.alphaTest>0){const t=d.uuid,e=i.uuid;let n=c[t];void 0===n&&(n={},c[t]=n);let r=n[e];void 0===r&&(r=d.clone(),n[e]=r),d=r}return d.visible=i.visible,d.wireframe=i.wireframe,d.side=3===h?null!==i.shadowSide?i.shadowSide:i.side:null!==i.shadowSide?i.shadowSide:u[i.side],d.alphaMap=i.alphaMap,d.alphaTest=i.alphaTest,d.clipShadows=i.clipShadows,d.clippingPlanes=i.clippingPlanes,d.clipIntersection=i.clipIntersection,d.displacementMap=i.displacementMap,d.displacementScale=i.displacementScale,d.displacementBias=i.displacementBias,d.wireframeLinewidth=i.wireframeLinewidth,d.linewidth=i.linewidth,!0===r.isPointLight&&!0===d.isMeshDistanceMaterial&&(d.referencePosition.setFromMatrixPosition(r.matrixWorld),d.nearDistance=s,d.farDistance=a),d}function M(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===o)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=e.update(n),r=n.material;if(Array.isArray(r)){const e=i.groups;for(let l=0,c=e.length;l<c;l++){const c=e[l],h=r[c.materialIndex];if(h&&h.visible){const e=_(n,0,h,a,s.near,s.far,o);t.renderBufferDirect(s,null,i,e,n,c)}}}else if(r.visible){const e=_(n,0,r,a,s.near,s.far,o);t.renderBufferDirect(s,null,i,e,n,null)}}const l=n.children;for(let t=0,e=l.length;t<e;t++)M(l[t],r,s,a,o)}this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1,this.render=function(e,n,o){if(!1===y.enabled)return;if(!1===y.autoUpdate&&!1===y.needsUpdate)return;if(0===e.length)return;const l=t.getRenderTarget(),c=t.getActiveCubeFace(),u=t.getActiveMipmapLevel(),d=t.state;d.setBlending(0),d.buffers.color.setClear(1,1,1,1),d.buffers.depth.setTest(!0),d.setScissorTest(!1);for(let l=0,c=e.length;l<c;l++){const c=e[l],u=c.shadow;if(void 0===u){console.warn("THREE.WebGLShadowMap:",c,"has no shadow.");continue}if(!1===u.autoUpdate&&!1===u.needsUpdate)continue;r.copy(u.mapSize);const m=u.getFrameExtents();if(r.multiply(m),s.copy(u.mapSize),(r.x>h||r.y>h)&&(r.x>h&&(s.x=Math.floor(h/m.x),r.x=s.x*m.x,u.mapSize.x=s.x),r.y>h&&(s.y=Math.floor(h/m.y),r.y=s.y*m.y,u.mapSize.y=s.y)),null===u.map&&!u.isPointLightShadow&&3===this.type){const t={minFilter:g,magFilter:g,format:T};u.map=new qt(r.x,r.y,t),u.map.texture.name=c.name+".shadowMap",u.mapPass=new qt(r.x,r.y,t),u.camera.updateProjectionMatrix()}if(null===u.map){const t={minFilter:p,magFilter:p,format:T};u.map=new qt(r.x,r.y,t),u.map.texture.name=c.name+".shadowMap",u.camera.updateProjectionMatrix()}t.setRenderTarget(u.map),t.clear();const f=u.getViewportCount();for(let t=0;t<f;t++){const e=u.getViewport(t);a.set(s.x*e.x,s.y*e.y,s.x*e.z,s.y*e.w),d.viewport(a),u.updateMatrices(c,t),i=u.getFrustum(),M(n,o,u.camera,c,this.type)}u.isPointLightShadow||3!==this.type||x(u,o),u.needsUpdate=!1}y.needsUpdate=!1,t.setRenderTarget(l,c,u)}}function Zs(t,e,i){const r=i.isWebGL2;const s=new function(){let e=!1;const n=new jt;let i=null;const r=new jt(0,0,0,0);return{setMask:function(n){i===n||e||(t.colorMask(n,n,n,n),i=n)},setLocked:function(t){e=t},setClear:function(e,i,s,a,o){!0===o&&(e*=a,i*=a,s*=a),n.set(e,i,s,a),!1===r.equals(n)&&(t.clearColor(e,i,s,a),r.copy(n))},reset:function(){e=!1,i=null,r.set(-1,0,0,0)}}},a=new function(){let e=!1,n=null,i=null,r=null;return{setTest:function(t){t?U(2929):H(2929)},setMask:function(i){n===i||e||(t.depthMask(i),n=i)},setFunc:function(e){if(i!==e){if(e)switch(e){case 0:t.depthFunc(512);break;case 1:t.depthFunc(519);break;case 2:t.depthFunc(513);break;case 3:default:t.depthFunc(515);break;case 4:t.depthFunc(514);break;case 5:t.depthFunc(518);break;case 6:t.depthFunc(516);break;case 7:t.depthFunc(517)}else t.depthFunc(515);i=e}},setLocked:function(t){e=t},setClear:function(e){r!==e&&(t.clearDepth(e),r=e)},reset:function(){e=!1,n=null,i=null,r=null}}},o=new function(){let e=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,c=null;return{setTest:function(t){e||(t?U(2960):H(2960))},setMask:function(i){n===i||e||(t.stencilMask(i),n=i)},setFunc:function(e,n,a){i===e&&r===n&&s===a||(t.stencilFunc(e,n,a),i=e,r=n,s=a)},setOp:function(e,n,i){a===e&&o===n&&l===i||(t.stencilOp(e,n,i),a=e,o=n,l=i)},setLocked:function(t){e=t},setClear:function(e){c!==e&&(t.clearStencil(e),c=e)},reset:function(){e=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,c=null}}};let l={},c={},h=new WeakMap,u=[],d=null,p=!1,m=null,f=null,g=null,v=null,y=null,x=null,_=null,M=!1,b=null,w=null,S=null,T=null,E=null;const A=t.getParameter(35661);let R=!1,L=0;const C=t.getParameter(7938);-1!==C.indexOf("WebGL")?(L=parseFloat(/^WebGL (\d)/.exec(C)[1]),R=L>=1):-1!==C.indexOf("OpenGL ES")&&(L=parseFloat(/^OpenGL ES (\d)/.exec(C)[1]),R=L>=2);let P=null,D={};const I=t.getParameter(3088),N=t.getParameter(2978),B=(new jt).fromArray(I),z=(new jt).fromArray(N);function O(e,n,i){const r=new Uint8Array(4),s=t.createTexture();t.bindTexture(e,s),t.texParameteri(e,10241,9728),t.texParameteri(e,10240,9728);for(let e=0;e<i;e++)t.texImage2D(n+e,0,6408,1,1,0,6408,5121,r);return s}const F={};function U(e){!0!==l[e]&&(t.enable(e),l[e]=!0)}function H(e){!1!==l[e]&&(t.disable(e),l[e]=!1)}F[3553]=O(3553,3553,1),F[34067]=O(34067,34069,6),s.setClear(0,0,0,1),a.setClear(1),o.setClear(0),U(2929),a.setFunc(3),W(!1),j(1),U(2884),V(0);const G={[n]:32774,101:32778,102:32779};if(r)G[103]=32775,G[104]=32776;else{const t=e.get("EXT_blend_minmax");null!==t&&(G[103]=t.MIN_EXT,G[104]=t.MAX_EXT)}const k={200:0,201:1,202:768,204:770,210:776,208:774,206:772,203:769,205:771,209:775,207:773};function V(e,i,r,s,a,o,l,c){if(0!==e){if(!1===p&&(U(3042),p=!0),5===e)a=a||i,o=o||r,l=l||s,i===f&&a===y||(t.blendEquationSeparate(G[i],G[a]),f=i,y=a),r===g&&s===v&&o===x&&l===_||(t.blendFuncSeparate(k[r],k[s],k[o],k[l]),g=r,v=s,x=o,_=l),m=e,M=null;else if(e!==m||c!==M){if(f===n&&y===n||(t.blendEquation(32774),f=n,y=n),c)switch(e){case 1:t.blendFuncSeparate(1,771,1,771);break;case 2:t.blendFunc(1,1);break;case 3:t.blendFuncSeparate(0,769,0,1);break;case 4:t.blendFuncSeparate(0,768,0,770);break;default:console.error("THREE.WebGLState: Invalid blending: ",e)}else switch(e){case 1:t.blendFuncSeparate(770,771,1,771);break;case 2:t.blendFunc(770,1);break;case 3:t.blendFuncSeparate(0,769,0,1);break;case 4:t.blendFunc(0,768);break;default:console.error("THREE.WebGLState: Invalid blending: ",e)}g=null,v=null,x=null,_=null,m=e,M=c}}else!0===p&&(H(3042),p=!1)}function W(e){b!==e&&(e?t.frontFace(2304):t.frontFace(2305),b=e)}function j(e){0!==e?(U(2884),e!==w&&(1===e?t.cullFace(1029):2===e?t.cullFace(1028):t.cullFace(1032))):H(2884),w=e}function q(e,n,i){e?(U(32823),T===n&&E===i||(t.polygonOffset(n,i),T=n,E=i)):H(32823)}function X(e){void 0===e&&(e=33984+A-1),P!==e&&(t.activeTexture(e),P=e)}return{buffers:{color:s,depth:a,stencil:o},enable:U,disable:H,bindFramebuffer:function(e,n){return c[e]!==n&&(t.bindFramebuffer(e,n),c[e]=n,r&&(36009===e&&(c[36160]=n),36160===e&&(c[36009]=n)),!0)},drawBuffers:function(n,r){let s=u,a=!1;if(n)if(s=h.get(r),void 0===s&&(s=[],h.set(r,s)),n.isWebGLMultipleRenderTargets){const t=n.texture;if(s.length!==t.length||36064!==s[0]){for(let e=0,n=t.length;e<n;e++)s[e]=36064+e;s.length=t.length,a=!0}}else 36064!==s[0]&&(s[0]=36064,a=!0);else 1029!==s[0]&&(s[0]=1029,a=!0);a&&(i.isWebGL2?t.drawBuffers(s):e.get("WEBGL_draw_buffers").drawBuffersWEBGL(s))},useProgram:function(e){return d!==e&&(t.useProgram(e),d=e,!0)},setBlending:V,setMaterial:function(t,e){2===t.side?H(2884):U(2884);let n=1===t.side;e&&(n=!n),W(n),1===t.blending&&!1===t.transparent?V(0):V(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.premultipliedAlpha),a.setFunc(t.depthFunc),a.setTest(t.depthTest),a.setMask(t.depthWrite),s.setMask(t.colorWrite);const i=t.stencilWrite;o.setTest(i),i&&(o.setMask(t.stencilWriteMask),o.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),o.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),q(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),!0===t.alphaToCoverage?U(32926):H(32926)},setFlipSided:W,setCullFace:j,setLineWidth:function(e){e!==S&&(R&&t.lineWidth(e),S=e)},setPolygonOffset:q,setScissorTest:function(t){t?U(3089):H(3089)},activeTexture:X,bindTexture:function(e,n){null===P&&X();let i=D[P];void 0===i&&(i={type:void 0,texture:void 0},D[P]=i),i.type===e&&i.texture===n||(t.bindTexture(e,n||F[e]),i.type=e,i.texture=n)},unbindTexture:function(){const e=D[P];void 0!==e&&void 0!==e.type&&(t.bindTexture(e.type,null),e.type=void 0,e.texture=void 0)},compressedTexImage2D:function(){try{t.compressedTexImage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texImage2D:function(){try{t.texImage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texImage3D:function(){try{t.texImage3D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texStorage2D:function(){try{t.texStorage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texStorage3D:function(){try{t.texStorage3D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texSubImage2D:function(){try{t.texSubImage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texSubImage3D:function(){try{t.texSubImage3D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},compressedTexSubImage2D:function(){try{t.compressedTexSubImage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},scissor:function(e){!1===B.equals(e)&&(t.scissor(e.x,e.y,e.z,e.w),B.copy(e))},viewport:function(e){!1===z.equals(e)&&(t.viewport(e.x,e.y,e.z,e.w),z.copy(e))},reset:function(){t.disable(3042),t.disable(2884),t.disable(2929),t.disable(32823),t.disable(3089),t.disable(2960),t.disable(32926),t.blendEquation(32774),t.blendFunc(1,0),t.blendFuncSeparate(1,0,1,0),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(513),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(519,0,4294967295),t.stencilOp(7680,7680,7680),t.clearStencil(0),t.cullFace(1029),t.frontFace(2305),t.polygonOffset(0,0),t.activeTexture(33984),t.bindFramebuffer(36160,null),!0===r&&(t.bindFramebuffer(36009,null),t.bindFramebuffer(36008,null)),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),l={},P=null,D={},c={},h=new WeakMap,u=[],d=null,p=!1,m=null,f=null,g=null,v=null,y=null,x=null,_=null,M=!1,b=null,w=null,S=null,T=null,E=null,B.set(0,0,t.canvas.width,t.canvas.height),z.set(0,0,t.canvas.width,t.canvas.height),s.reset(),a.reset(),o.reset()}}}function Ks(t,e,n,i,r,s,a){const o=r.isWebGL2,l=r.maxTextures,c=r.maxCubemapSize,R=r.maxTextureSize,L=r.maxSamples,C=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):void 0,P=new WeakMap;let D,I=!1;try{I="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(t){}function N(t,e){return I?new OffscreenCanvas(t,e):Dt("canvas")}function B(t,e,n,i){let r=1;if((t.width>i||t.height>i)&&(r=i/Math.max(t.width,t.height)),r<1||!0===e){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const i=e?Tt:Math.floor,s=i(r*t.width),a=i(r*t.height);void 0===D&&(D=N(s,a));const o=n?N(s,a):D;o.width=s,o.height=a;return o.getContext("2d").drawImage(t,0,0,s,a),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+t.width+"x"+t.height+") to ("+s+"x"+a+")."),o}return"data"in t&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+t.width+"x"+t.height+")."),t}return t}function z(t){return wt(t.width)&&wt(t.height)}function O(t,e){return t.generateMipmaps&&e&&t.minFilter!==p&&t.minFilter!==g}function F(e){t.generateMipmap(e)}function U(n,i,r,s,a=!1){if(!1===o)return i;if(null!==n){if(void 0!==t[n])return t[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let l=i;return 6403===i&&(5126===r&&(l=33326),5131===r&&(l=33325),5121===r&&(l=33321)),33319===i&&(5126===r&&(l=33328),5131===r&&(l=33327),5121===r&&(l=33323)),6408===i&&(5126===r&&(l=34836),5131===r&&(l=34842),5121===r&&(l=s===lt&&!1===a?35907:32856),32819===r&&(l=32854),32820===r&&(l=32855)),33325!==l&&33326!==l&&33327!==l&&33328!==l&&34842!==l&&34836!==l||e.get("EXT_color_buffer_float"),l}function H(t,e,n){return!0===O(t,n)||t.isFramebufferTexture&&t.minFilter!==p&&t.minFilter!==g?Math.log2(Math.max(e.width,e.height))+1:void 0!==t.mipmaps&&t.mipmaps.length>0?t.mipmaps.length:t.isCompressedTexture&&Array.isArray(t.image)?e.mipmaps.length:1}function G(t){return t===p||t===m||t===f?9728:9729}function k(e){const n=e.target;n.removeEventListener("dispose",k),function(e){const n=i.get(e);if(void 0===n.__webglInit)return;t.deleteTexture(n.__webglTexture),i.remove(e)}(n),n.isVideoTexture&&P.delete(n),a.memory.textures--}function V(e){const n=e.target;n.removeEventListener("dispose",V),function(e){const n=e.texture,r=i.get(e),s=i.get(n);if(!e)return;void 0!==s.__webglTexture&&(t.deleteTexture(s.__webglTexture),a.memory.textures--);e.depthTexture&&e.depthTexture.dispose();if(e.isWebGLCubeRenderTarget)for(let e=0;e<6;e++)t.deleteFramebuffer(r.__webglFramebuffer[e]),r.__webglDepthbuffer&&t.deleteRenderbuffer(r.__webglDepthbuffer[e]);else t.deleteFramebuffer(r.__webglFramebuffer),r.__webglDepthbuffer&&t.deleteRenderbuffer(r.__webglDepthbuffer),r.__webglMultisampledFramebuffer&&t.deleteFramebuffer(r.__webglMultisampledFramebuffer),r.__webglColorRenderbuffer&&t.deleteRenderbuffer(r.__webglColorRenderbuffer),r.__webglDepthRenderbuffer&&t.deleteRenderbuffer(r.__webglDepthRenderbuffer);if(e.isWebGLMultipleRenderTargets)for(let e=0,r=n.length;e<r;e++){const r=i.get(n[e]);r.__webglTexture&&(t.deleteTexture(r.__webglTexture),a.memory.textures--),i.remove(n[e])}i.remove(n),i.remove(e)}(n)}let W=0;function j(t,e){const r=i.get(t);if(t.isVideoTexture&&function(t){const e=a.render.frame;P.get(t)!==e&&(P.set(t,e),t.update())}(t),t.version>0&&r.__version!==t.version){const n=t.image;if(void 0===n)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined");else{if(!1!==n.complete)return void K(r,t,e);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}n.activeTexture(33984+e),n.bindTexture(3553,r.__webglTexture)}function q(e,r){const a=i.get(e);e.version>0&&a.__version!==e.version?function(e,i,r){if(6!==i.image.length)return;Z(e,i),n.activeTexture(33984+r),n.bindTexture(34067,e.__webglTexture),t.pixelStorei(37440,i.flipY),t.pixelStorei(37441,i.premultiplyAlpha),t.pixelStorei(3317,i.unpackAlignment),t.pixelStorei(37443,0);const a=i&&(i.isCompressedTexture||i.image[0].isCompressedTexture),l=i.image[0]&&i.image[0].isDataTexture,h=[];for(let t=0;t<6;t++)h[t]=a||l?l?i.image[t].image:i.image[t]:B(i.image[t],!1,!0,c),h[t]=nt(i,h[t]);const u=h[0],d=z(u)||o,p=s.convert(i.format,i.encoding),m=s.convert(i.type),f=U(i.internalFormat,p,m,i.encoding),g=o&&!0!==i.isVideoTexture,v=void 0===e.__version;let y,x=H(i,u,d);if(Y(34067,i,d),a){g&&v&&n.texStorage2D(34067,x,f,u.width,u.height);for(let t=0;t<6;t++){y=h[t].mipmaps;for(let e=0;e<y.length;e++){const r=y[e];i.format!==T?null!==p?g?n.compressedTexSubImage2D(34069+t,e,0,0,r.width,r.height,p,r.data):n.compressedTexImage2D(34069+t,e,f,r.width,r.height,0,r.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):g?n.texSubImage2D(34069+t,e,0,0,r.width,r.height,p,m,r.data):n.texImage2D(34069+t,e,f,r.width,r.height,0,p,m,r.data)}}}else{y=i.mipmaps,g&&v&&(y.length>0&&x++,n.texStorage2D(34067,x,f,h[0].width,h[0].height));for(let t=0;t<6;t++)if(l){g?n.texSubImage2D(34069+t,0,0,0,h[t].width,h[t].height,p,m,h[t].data):n.texImage2D(34069+t,0,f,h[t].width,h[t].height,0,p,m,h[t].data);for(let e=0;e<y.length;e++){const i=y[e].image[t].image;g?n.texSubImage2D(34069+t,e+1,0,0,i.width,i.height,p,m,i.data):n.texImage2D(34069+t,e+1,f,i.width,i.height,0,p,m,i.data)}}else{g?n.texSubImage2D(34069+t,0,0,0,p,m,h[t]):n.texImage2D(34069+t,0,f,p,m,h[t]);for(let e=0;e<y.length;e++){const i=y[e];g?n.texSubImage2D(34069+t,e+1,0,0,p,m,i.image[t]):n.texImage2D(34069+t,e+1,f,p,m,i.image[t])}}}O(i,d)&&F(34067);e.__version=i.version,i.onUpdate&&i.onUpdate(i)}(a,e,r):(n.activeTexture(33984+r),n.bindTexture(34067,a.__webglTexture))}const X={[h]:10497,[u]:33071,[d]:33648},J={[p]:9728,[m]:9984,[f]:9986,[g]:9729,[v]:9985,[y]:9987};function Y(n,s,a){if(a?(t.texParameteri(n,10242,X[s.wrapS]),t.texParameteri(n,10243,X[s.wrapT]),32879!==n&&35866!==n||t.texParameteri(n,32882,X[s.wrapR]),t.texParameteri(n,10240,J[s.magFilter]),t.texParameteri(n,10241,J[s.minFilter])):(t.texParameteri(n,10242,33071),t.texParameteri(n,10243,33071),32879!==n&&35866!==n||t.texParameteri(n,32882,33071),s.wrapS===u&&s.wrapT===u||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),t.texParameteri(n,10240,G(s.magFilter)),t.texParameteri(n,10241,G(s.minFilter)),s.minFilter!==p&&s.minFilter!==g&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),!0===e.has("EXT_texture_filter_anisotropic")){const a=e.get("EXT_texture_filter_anisotropic");if(s.type===b&&!1===e.has("OES_texture_float_linear"))return;if(!1===o&&s.type===w&&!1===e.has("OES_texture_half_float_linear"))return;(s.anisotropy>1||i.get(s).__currentAnisotropy)&&(t.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy)}}function Z(e,n){void 0===e.__webglInit&&(e.__webglInit=!0,n.addEventListener("dispose",k),e.__webglTexture=t.createTexture(),a.memory.textures++)}function K(e,i,r){let a=3553;i.isDataTexture2DArray&&(a=35866),i.isDataTexture3D&&(a=32879),Z(e,i),n.activeTexture(33984+r),n.bindTexture(a,e.__webglTexture),t.pixelStorei(37440,i.flipY),t.pixelStorei(37441,i.premultiplyAlpha),t.pixelStorei(3317,i.unpackAlignment),t.pixelStorei(37443,0);const l=function(t){return!o&&(t.wrapS!==u||t.wrapT!==u||t.minFilter!==p&&t.minFilter!==g)}(i)&&!1===z(i.image);let c=B(i.image,l,!1,R);c=nt(i,c);const h=z(c)||o,d=s.convert(i.format,i.encoding);let m,f=s.convert(i.type),v=U(i.internalFormat,d,f,i.encoding,i.isVideoTexture);Y(a,i,h);const y=i.mipmaps,x=o&&!0!==i.isVideoTexture,w=void 0===e.__version,L=H(i,c,h);if(i.isDepthTexture)v=6402,o?v=i.type===b?36012:i.type===M?33190:i.type===S?35056:33189:i.type===b&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),i.format===E&&6402===v&&i.type!==_&&i.type!==M&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),i.type=_,f=s.convert(i.type)),i.format===A&&6402===v&&(v=34041,i.type!==S&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),i.type=S,f=s.convert(i.type))),x&&w?n.texStorage2D(3553,1,v,c.width,c.height):n.texImage2D(3553,0,v,c.width,c.height,0,d,f,null);else if(i.isDataTexture)if(y.length>0&&h){x&&w&&n.texStorage2D(3553,L,v,y[0].width,y[0].height);for(let t=0,e=y.length;t<e;t++)m=y[t],x?n.texSubImage2D(3553,0,0,0,m.width,m.height,d,f,m.data):n.texImage2D(3553,t,v,m.width,m.height,0,d,f,m.data);i.generateMipmaps=!1}else x?(w&&n.texStorage2D(3553,L,v,c.width,c.height),n.texSubImage2D(3553,0,0,0,c.width,c.height,d,f,c.data)):n.texImage2D(3553,0,v,c.width,c.height,0,d,f,c.data);else if(i.isCompressedTexture){x&&w&&n.texStorage2D(3553,L,v,y[0].width,y[0].height);for(let t=0,e=y.length;t<e;t++)m=y[t],i.format!==T?null!==d?x?n.compressedTexSubImage2D(3553,t,0,0,m.width,m.height,d,m.data):n.compressedTexImage2D(3553,t,v,m.width,m.height,0,m.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):x?n.texSubImage2D(3553,t,0,0,m.width,m.height,d,f,m.data):n.texImage2D(3553,t,v,m.width,m.height,0,d,f,m.data)}else if(i.isDataTexture2DArray)x?(w&&n.texStorage3D(35866,L,v,c.width,c.height,c.depth),n.texSubImage3D(35866,0,0,0,0,c.width,c.height,c.depth,d,f,c.data)):n.texImage3D(35866,0,v,c.width,c.height,c.depth,0,d,f,c.data);else if(i.isDataTexture3D)x?(w&&n.texStorage3D(32879,L,v,c.width,c.height,c.depth),n.texSubImage3D(32879,0,0,0,0,c.width,c.height,c.depth,d,f,c.data)):n.texImage3D(32879,0,v,c.width,c.height,c.depth,0,d,f,c.data);else if(i.isFramebufferTexture)x&&w?n.texStorage2D(3553,L,v,c.width,c.height):n.texImage2D(3553,0,v,c.width,c.height,0,d,f,null);else if(y.length>0&&h){x&&w&&n.texStorage2D(3553,L,v,y[0].width,y[0].height);for(let t=0,e=y.length;t<e;t++)m=y[t],x?n.texSubImage2D(3553,t,0,0,d,f,m):n.texImage2D(3553,t,v,d,f,m);i.generateMipmaps=!1}else x?(w&&n.texStorage2D(3553,L,v,c.width,c.height),n.texSubImage2D(3553,0,0,0,d,f,c)):n.texImage2D(3553,0,v,d,f,c);O(i,h)&&F(a),e.__version=i.version,i.onUpdate&&i.onUpdate(i)}function Q(e,r,a,o,l){const c=s.convert(a.format,a.encoding),h=s.convert(a.type),u=U(a.internalFormat,c,h,a.encoding);i.get(r).__hasExternalTextures||(32879===l||35866===l?n.texImage3D(l,0,u,r.width,r.height,r.depth,0,c,h,null):n.texImage2D(l,0,u,r.width,r.height,0,c,h,null)),n.bindFramebuffer(36160,e),r.useRenderToTexture?C.framebufferTexture2DMultisampleEXT(36160,o,l,i.get(a).__webglTexture,0,et(r)):t.framebufferTexture2D(36160,o,l,i.get(a).__webglTexture,0),n.bindFramebuffer(36160,null)}function $(e,n,i){if(t.bindRenderbuffer(36161,e),n.depthBuffer&&!n.stencilBuffer){let r=33189;if(i||n.useRenderToTexture){const e=n.depthTexture;e&&e.isDepthTexture&&(e.type===b?r=36012:e.type===M&&(r=33190));const i=et(n);n.useRenderToTexture?C.renderbufferStorageMultisampleEXT(36161,i,r,n.width,n.height):t.renderbufferStorageMultisample(36161,i,r,n.width,n.height)}else t.renderbufferStorage(36161,r,n.width,n.height);t.framebufferRenderbuffer(36160,36096,36161,e)}else if(n.depthBuffer&&n.stencilBuffer){const r=et(n);i&&n.useRenderbuffer?t.renderbufferStorageMultisample(36161,r,35056,n.width,n.height):n.useRenderToTexture?C.renderbufferStorageMultisampleEXT(36161,r,35056,n.width,n.height):t.renderbufferStorage(36161,34041,n.width,n.height),t.framebufferRenderbuffer(36160,33306,36161,e)}else{const e=!0===n.isWebGLMultipleRenderTargets?n.texture[0]:n.texture,r=s.convert(e.format,e.encoding),a=s.convert(e.type),o=U(e.internalFormat,r,a,e.encoding),l=et(n);i&&n.useRenderbuffer?t.renderbufferStorageMultisample(36161,l,o,n.width,n.height):n.useRenderToTexture?C.renderbufferStorageMultisampleEXT(36161,l,o,n.width,n.height):t.renderbufferStorage(36161,o,n.width,n.height)}t.bindRenderbuffer(36161,null)}function tt(e){const r=i.get(e),s=!0===e.isWebGLCubeRenderTarget;if(e.depthTexture&&!r.__autoAllocateDepthBuffer){if(s)throw new Error("target.depthTexture not supported in Cube render targets");!function(e,r){if(r&&r.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(36160,e),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");i.get(r.depthTexture).__webglTexture&&r.depthTexture.image.width===r.width&&r.depthTexture.image.height===r.height||(r.depthTexture.image.width=r.width,r.depthTexture.image.height=r.height,r.depthTexture.needsUpdate=!0),j(r.depthTexture,0);const s=i.get(r.depthTexture).__webglTexture,a=et(r);if(r.depthTexture.format===E)r.useRenderToTexture?C.framebufferTexture2DMultisampleEXT(36160,36096,3553,s,0,a):t.framebufferTexture2D(36160,36096,3553,s,0);else{if(r.depthTexture.format!==A)throw new Error("Unknown depthTexture format");r.useRenderToTexture?C.framebufferTexture2DMultisampleEXT(36160,33306,3553,s,0,a):t.framebufferTexture2D(36160,33306,3553,s,0)}}(r.__webglFramebuffer,e)}else if(s){r.__webglDepthbuffer=[];for(let i=0;i<6;i++)n.bindFramebuffer(36160,r.__webglFramebuffer[i]),r.__webglDepthbuffer[i]=t.createRenderbuffer(),$(r.__webglDepthbuffer[i],e,!1)}else n.bindFramebuffer(36160,r.__webglFramebuffer),r.__webglDepthbuffer=t.createRenderbuffer(),$(r.__webglDepthbuffer,e,!1);n.bindFramebuffer(36160,null)}function et(t){return o&&(t.useRenderbuffer||t.useRenderToTexture)?Math.min(L,t.samples):0}function nt(t,n){const i=t.encoding,r=t.format,s=t.type;return!0===t.isCompressedTexture||!0===t.isVideoTexture||t.format===pt||i!==ot&&(i===lt?!1===o?!0===e.has("EXT_sRGB")&&r===T?(t.format=pt,t.minFilter=g,t.generateMipmaps=!1):n=Gt.sRGBToLinear(n):r===T&&s===x||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture encoding:",i)),n}let it=!1,rt=!1;this.allocateTextureUnit=function(){const t=W;return t>=l&&console.warn("THREE.WebGLTextures: Trying to use "+t+" texture units while this GPU supports only "+l),W+=1,t},this.resetTextureUnits=function(){W=0},this.setTexture2D=j,this.setTexture2DArray=function(t,e){const r=i.get(t);t.version>0&&r.__version!==t.version?K(r,t,e):(n.activeTexture(33984+e),n.bindTexture(35866,r.__webglTexture))},this.setTexture3D=function(t,e){const r=i.get(t);t.version>0&&r.__version!==t.version?K(r,t,e):(n.activeTexture(33984+e),n.bindTexture(32879,r.__webglTexture))},this.setTextureCube=q,this.rebindTextures=function(t,e,n){const r=i.get(t);void 0!==e&&Q(r.__webglFramebuffer,t,t.texture,36064,3553),void 0!==n&&tt(t)},this.setupRenderTarget=function(e){const l=e.texture,c=i.get(e),h=i.get(l);e.addEventListener("dispose",V),!0!==e.isWebGLMultipleRenderTargets&&(void 0===h.__webglTexture&&(h.__webglTexture=t.createTexture()),h.__version=l.version,a.memory.textures++);const u=!0===e.isWebGLCubeRenderTarget,d=!0===e.isWebGLMultipleRenderTargets,p=l.isDataTexture3D||l.isDataTexture2DArray,m=z(e)||o;if(u){c.__webglFramebuffer=[];for(let e=0;e<6;e++)c.__webglFramebuffer[e]=t.createFramebuffer()}else if(c.__webglFramebuffer=t.createFramebuffer(),d)if(r.drawBuffers){const n=e.texture;for(let e=0,r=n.length;e<r;e++){const r=i.get(n[e]);void 0===r.__webglTexture&&(r.__webglTexture=t.createTexture(),a.memory.textures++)}}else console.warn("THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.");else if(e.useRenderbuffer)if(o){c.__webglMultisampledFramebuffer=t.createFramebuffer(),c.__webglColorRenderbuffer=t.createRenderbuffer(),t.bindRenderbuffer(36161,c.__webglColorRenderbuffer);const i=s.convert(l.format,l.encoding),r=s.convert(l.type),a=U(l.internalFormat,i,r,l.encoding),o=et(e);t.renderbufferStorageMultisample(36161,o,a,e.width,e.height),n.bindFramebuffer(36160,c.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(36160,36064,36161,c.__webglColorRenderbuffer),t.bindRenderbuffer(36161,null),e.depthBuffer&&(c.__webglDepthRenderbuffer=t.createRenderbuffer(),$(c.__webglDepthRenderbuffer,e,!0)),n.bindFramebuffer(36160,null)}else console.warn("THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.");if(u){n.bindTexture(34067,h.__webglTexture),Y(34067,l,m);for(let t=0;t<6;t++)Q(c.__webglFramebuffer[t],e,l,36064,34069+t);O(l,m)&&F(34067),n.unbindTexture()}else if(d){const t=e.texture;for(let r=0,s=t.length;r<s;r++){const s=t[r],a=i.get(s);n.bindTexture(3553,a.__webglTexture),Y(3553,s,m),Q(c.__webglFramebuffer,e,s,36064+r,3553),O(s,m)&&F(3553)}n.unbindTexture()}else{let t=3553;if(p)if(o){t=l.isDataTexture3D?32879:35866}else console.warn("THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.");n.bindTexture(t,h.__webglTexture),Y(t,l,m),Q(c.__webglFramebuffer,e,l,36064,t),O(l,m)&&F(t),n.unbindTexture()}e.depthBuffer&&tt(e)},this.updateRenderTargetMipmap=function(t){const e=z(t)||o,r=!0===t.isWebGLMultipleRenderTargets?t.texture:[t.texture];for(let s=0,a=r.length;s<a;s++){const a=r[s];if(O(a,e)){const e=t.isWebGLCubeRenderTarget?34067:3553,r=i.get(a).__webglTexture;n.bindTexture(e,r),F(e),n.unbindTexture()}}},this.updateMultisampleRenderTarget=function(e){if(e.useRenderbuffer)if(o){const r=e.width,s=e.height;let a=16384;const o=[36064],l=e.stencilBuffer?33306:36096;e.depthBuffer&&o.push(l),e.ignoreDepthForMultisampleCopy||(e.depthBuffer&&(a|=256),e.stencilBuffer&&(a|=1024));const c=i.get(e);n.bindFramebuffer(36008,c.__webglMultisampledFramebuffer),n.bindFramebuffer(36009,c.__webglFramebuffer),e.ignoreDepthForMultisampleCopy&&(t.invalidateFramebuffer(36008,[l]),t.invalidateFramebuffer(36009,[l])),t.blitFramebuffer(0,0,r,s,0,0,r,s,a,9728),t.invalidateFramebuffer(36008,o),n.bindFramebuffer(36008,null),n.bindFramebuffer(36009,c.__webglMultisampledFramebuffer)}else console.warn("THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.")},this.setupDepthRenderbuffer=tt,this.setupFrameBufferTexture=Q,this.safeSetTexture2D=function(t,e){t&&t.isWebGLRenderTarget&&(!1===it&&(console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead."),it=!0),t=t.texture),j(t,e)},this.safeSetTextureCube=function(t,e){t&&t.isWebGLCubeRenderTarget&&(!1===rt&&(console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead."),rt=!0),t=t.texture),q(t,e)}}function Qs(t,e,n){const i=n.isWebGL2;return{convert:function(t,n=null){let r;if(t===x)return 5121;if(1017===t)return 32819;if(1018===t)return 32820;if(1010===t)return 5120;if(1011===t)return 5122;if(t===_)return 5123;if(1013===t)return 5124;if(t===M)return 5125;if(t===b)return 5126;if(t===w)return i?5131:(r=e.get("OES_texture_half_float"),null!==r?r.HALF_FLOAT_OES:null);if(1021===t)return 6406;if(t===T)return 6408;if(1024===t)return 6409;if(1025===t)return 6410;if(t===E)return 6402;if(t===A)return 34041;if(1028===t)return 6403;if(t===pt)return r=e.get("EXT_sRGB"),null!==r?r.SRGB_ALPHA_EXT:null;if(1029===t)return 36244;if(1030===t)return 33319;if(1031===t)return 33320;if(1033===t)return 36249;if(t===R||t===L||t===C||t===P)if(n===lt){if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(t===R)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(t===L)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(t===C)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(t===P)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=e.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(t===R)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(t===L)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(t===C)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(t===P)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(t===D||t===I||t===N||t===B){if(r=e.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(t===D)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(t===I)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(t===N)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(t===B)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===t)return r=e.get("WEBGL_compressed_texture_etc1"),null!==r?r.COMPRESSED_RGB_ETC1_WEBGL:null;if(t===z||t===O){if(r=e.get("WEBGL_compressed_texture_etc"),null===r)return null;if(t===z)return n===lt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(t===O)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}if(t===F||t===U||t===H||t===G||t===k||t===V||t===W||t===j||t===q||t===X||t===J||t===Y||t===Z||t===K){if(r=e.get("WEBGL_compressed_texture_astc"),null===r)return null;if(t===F)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(t===U)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(t===H)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(t===G)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(t===k)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(t===V)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(t===W)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(t===j)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(t===q)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(t===X)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(t===J)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(t===Y)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(t===Z)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(t===K)return n===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(t===Q){if(r=e.get("EXT_texture_compression_bptc"),null===r)return null;if(t===Q)return n===lt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT}return t===S?i?34042:(r=e.get("WEBGL_depth_texture"),null!==r?r.UNSIGNED_INT_24_8_WEBGL:null):void 0}}}class $s extends ai{constructor(t=[]){super(),this.cameras=t}}$s.prototype.isArrayCamera=!0;class ta extends Qe{constructor(){super(),this.type="Group"}}ta.prototype.isGroup=!0;const ea={type:"move"};class na{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new ta,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new ta,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Zt,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Zt),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new ta,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Zt,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Zt),this._grip}dispatchEvent(t){return null!==this._targetRay&&this._targetRay.dispatchEvent(t),null!==this._grip&&this._grip.dispatchEvent(t),null!==this._hand&&this._hand.dispatchEvent(t),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(t,e,n){let i=null,r=null,s=null;const a=this._targetRay,o=this._grip,l=this._hand;if(t&&"visible-blurred"!==e.session.visibilityState)if(null!==a&&(i=e.getPose(t.targetRaySpace,n),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(ea))),l&&t.hand){s=!0;for(const i of t.hand.values()){const t=e.getJointPose(i,n);if(void 0===l.joints[i.jointName]){const t=new ta;t.matrixAutoUpdate=!1,t.visible=!1,l.joints[i.jointName]=t,l.add(t)}const r=l.joints[i.jointName];null!==t&&(r.matrix.fromArray(t.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.jointRadius=t.radius),r.visible=null!==t}const i=l.joints["index-finger-tip"],r=l.joints["thumb-tip"],a=i.position.distanceTo(r.position),o=.02,c=.005;l.inputState.pinching&&a>o+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&a<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else null!==o&&t.gripSpace&&(r=e.getPose(t.gripSpace,n),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1));return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}}class ia extends Vt{constructor(t,e,n,i,r,s,a,o,l,c){if((c=void 0!==c?c:E)!==E&&c!==A)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===n&&c===E&&(n=_),void 0===n&&c===A&&(n=S),super(null,i,r,s,a,o,c,n,l),this.image={width:t,height:e},this.magFilter=void 0!==a?a:p,this.minFilter=void 0!==o?o:p,this.flipY=!1,this.generateMipmaps=!1}}ia.prototype.isDepthTexture=!0;class ra extends mt{constructor(t,e){super();const n=this;let i=null,r=1,s=null,a="local-floor";const o=t.extensions.has("WEBGL_multisampled_render_to_texture");let l=null,c=null,h=null,u=null,d=!1,p=null;const m=e.getContextAttributes();let f=null,g=null;const v=[],y=new Map,M=new ai;M.layers.enable(1),M.viewport=new jt;const b=new ai;b.layers.enable(2),b.viewport=new jt;const w=[M,b],R=new $s;R.layers.enable(1),R.layers.enable(2);let L=null,C=null;function P(t){const e=y.get(t.inputSource);e&&e.dispatchEvent({type:t.type,data:t.inputSource})}function D(){y.forEach((function(t,e){t.disconnect(e)})),y.clear(),L=null,C=null,t.setRenderTarget(f),u=null,h=null,c=null,i=null,g=null,F.stop(),n.isPresenting=!1,n.dispatchEvent({type:"sessionend"})}function I(t){const e=i.inputSources;for(let t=0;t<v.length;t++)y.set(e[t],v[t]);for(let e=0;e<t.removed.length;e++){const n=t.removed[e],i=y.get(n);i&&(i.dispatchEvent({type:"disconnected",data:n}),y.delete(n))}for(let e=0;e<t.added.length;e++){const n=t.added[e],i=y.get(n);i&&i.dispatchEvent({type:"connected",data:n})}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(t){let e=v[t];return void 0===e&&(e=new na,v[t]=e),e.getTargetRaySpace()},this.getControllerGrip=function(t){let e=v[t];return void 0===e&&(e=new na,v[t]=e),e.getGripSpace()},this.getHand=function(t){let e=v[t];return void 0===e&&(e=new na,v[t]=e),e.getHandSpace()},this.setFramebufferScaleFactor=function(t){r=t,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(t){a=t,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return s},this.getBaseLayer=function(){return null!==h?h:u},this.getBinding=function(){return c},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(l){if(i=l,null!==i){if(f=t.getRenderTarget(),i.addEventListener("select",P),i.addEventListener("selectstart",P),i.addEventListener("selectend",P),i.addEventListener("squeeze",P),i.addEventListener("squeezestart",P),i.addEventListener("squeezeend",P),i.addEventListener("end",D),i.addEventListener("inputsourceschange",I),!0!==m.xrCompatible&&await e.makeXRCompatible(),void 0===i.renderState.layers||!1===t.capabilities.isWebGL2){const n={antialias:void 0!==i.renderState.layers||m.antialias,alpha:m.alpha,depth:m.depth,stencil:m.stencil,framebufferScaleFactor:r};u=new XRWebGLLayer(i,e,n),i.updateRenderState({baseLayer:u}),g=new qt(u.framebufferWidth,u.framebufferHeight,{format:T,type:x,encoding:t.outputEncoding})}else{d=m.antialias;let n=null,s=null,a=null;m.depth&&(a=m.stencil?35056:33190,n=m.stencil?A:E,s=m.stencil?S:_);const l={colorFormat:t.outputEncoding===lt?35907:32856,depthFormat:a,scaleFactor:r};c=new XRWebGLBinding(i,e),h=c.createProjectionLayer(l),i.updateRenderState({layers:[h]}),g=d?new Jt(h.textureWidth,h.textureHeight,{format:T,type:x,depthTexture:new ia(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:m.stencil,ignoreDepth:h.ignoreDepthValues,useRenderToTexture:o,encoding:t.outputEncoding}):new qt(h.textureWidth,h.textureHeight,{format:T,type:x,depthTexture:new ia(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:m.stencil,ignoreDepth:h.ignoreDepthValues,encoding:t.outputEncoding})}g.isXRRenderTarget=!0,this.setFoveation(1),s=await i.requestReferenceSpace(a),F.setContext(i),F.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}};const N=new Zt,B=new Zt;function z(t,e){null===e?t.matrixWorld.copy(t.matrix):t.matrixWorld.multiplyMatrices(e.matrixWorld,t.matrix),t.matrixWorldInverse.copy(t.matrixWorld).invert()}this.updateCamera=function(t){if(null===i)return;R.near=b.near=M.near=t.near,R.far=b.far=M.far=t.far,L===R.near&&C===R.far||(i.updateRenderState({depthNear:R.near,depthFar:R.far}),L=R.near,C=R.far);const e=t.parent,n=R.cameras;z(R,e);for(let t=0;t<n.length;t++)z(n[t],e);R.matrixWorld.decompose(R.position,R.quaternion,R.scale),t.position.copy(R.position),t.quaternion.copy(R.quaternion),t.scale.copy(R.scale),t.matrix.copy(R.matrix),t.matrixWorld.copy(R.matrixWorld);const r=t.children;for(let t=0,e=r.length;t<e;t++)r[t].updateMatrixWorld(!0);2===n.length?function(t,e,n){N.setFromMatrixPosition(e.matrixWorld),B.setFromMatrixPosition(n.matrixWorld);const i=N.distanceTo(B),r=e.projectionMatrix.elements,s=n.projectionMatrix.elements,a=r[14]/(r[10]-1),o=r[14]/(r[10]+1),l=(r[9]+1)/r[5],c=(r[9]-1)/r[5],h=(r[8]-1)/r[0],u=(s[8]+1)/s[0],d=a*h,p=a*u,m=i/(-h+u),f=m*-h;e.matrixWorld.decompose(t.position,t.quaternion,t.scale),t.translateX(f),t.translateZ(m),t.matrixWorld.compose(t.position,t.quaternion,t.scale),t.matrixWorldInverse.copy(t.matrixWorld).invert();const g=a+m,v=o+m,y=d-f,x=p+(i-f),_=l*o/v*g,M=c*o/v*g;t.projectionMatrix.makePerspective(y,x,_,M,g,v)}(R,M,b):R.projectionMatrix.copy(M.projectionMatrix)},this.getCamera=function(){return R},this.getFoveation=function(){return null!==h?h.fixedFoveation:null!==u?u.fixedFoveation:void 0},this.setFoveation=function(t){null!==h&&(h.fixedFoveation=t),null!==u&&void 0!==u.fixedFoveation&&(u.fixedFoveation=t)};let O=null;const F=new yi;F.setAnimationLoop((function(e,n){if(l=n.getViewerPose(s),p=n,null!==l){const e=l.views;null!==u&&(t.setRenderTargetFramebuffer(g,u.framebuffer),t.setRenderTarget(g));let n=!1;e.length!==R.cameras.length&&(R.cameras.length=0,n=!0);for(let i=0;i<e.length;i++){const r=e[i];let s=null;if(null!==u)s=u.getViewport(r);else{const e=c.getViewSubImage(h,r);s=e.viewport,0===i&&(t.setRenderTargetTextures(g,e.colorTexture,h.ignoreDepthValues?void 0:e.depthStencilTexture),t.setRenderTarget(g))}const a=w[i];a.matrix.fromArray(r.transform.matrix),a.projectionMatrix.fromArray(r.projectionMatrix),a.viewport.set(s.x,s.y,s.width,s.height),0===i&&R.matrix.copy(a.matrix),!0===n&&R.cameras.push(a)}}const r=i.inputSources;for(let t=0;t<v.length;t++){const e=v[t],i=r[t];e.update(i,n,s)}O&&O(e,n),p=null})),this.setAnimationLoop=function(t){O=t},this.dispose=function(){}}}function sa(t){function e(e,n){e.opacity.value=n.opacity,n.color&&e.diffuse.value.copy(n.color),n.emissive&&e.emissive.value.copy(n.emissive).multiplyScalar(n.emissiveIntensity),n.map&&(e.map.value=n.map),n.alphaMap&&(e.alphaMap.value=n.alphaMap),n.specularMap&&(e.specularMap.value=n.specularMap),n.alphaTest>0&&(e.alphaTest.value=n.alphaTest);const i=t.get(n).envMap;let r,s;i&&(e.envMap.value=i,e.flipEnvMap.value=i.isCubeTexture&&!1===i.isRenderTargetTexture?-1:1,e.reflectivity.value=n.reflectivity,e.ior.value=n.ior,e.refractionRatio.value=n.refractionRatio),n.lightMap&&(e.lightMap.value=n.lightMap,e.lightMapIntensity.value=n.lightMapIntensity),n.aoMap&&(e.aoMap.value=n.aoMap,e.aoMapIntensity.value=n.aoMapIntensity),n.map?r=n.map:n.specularMap?r=n.specularMap:n.displacementMap?r=n.displacementMap:n.normalMap?r=n.normalMap:n.bumpMap?r=n.bumpMap:n.roughnessMap?r=n.roughnessMap:n.metalnessMap?r=n.metalnessMap:n.alphaMap?r=n.alphaMap:n.emissiveMap?r=n.emissiveMap:n.clearcoatMap?r=n.clearcoatMap:n.clearcoatNormalMap?r=n.clearcoatNormalMap:n.clearcoatRoughnessMap?r=n.clearcoatRoughnessMap:n.specularIntensityMap?r=n.specularIntensityMap:n.specularColorMap?r=n.specularColorMap:n.transmissionMap?r=n.transmissionMap:n.thicknessMap?r=n.thicknessMap:n.sheenColorMap?r=n.sheenColorMap:n.sheenRoughnessMap&&(r=n.sheenRoughnessMap),void 0!==r&&(r.isWebGLRenderTarget&&(r=r.texture),!0===r.matrixAutoUpdate&&r.updateMatrix(),e.uvTransform.value.copy(r.matrix)),n.aoMap?s=n.aoMap:n.lightMap&&(s=n.lightMap),void 0!==s&&(s.isWebGLRenderTarget&&(s=s.texture),!0===s.matrixAutoUpdate&&s.updateMatrix(),e.uv2Transform.value.copy(s.matrix))}function n(e,n){e.roughness.value=n.roughness,e.metalness.value=n.metalness,n.roughnessMap&&(e.roughnessMap.value=n.roughnessMap),n.metalnessMap&&(e.metalnessMap.value=n.metalnessMap),n.emissiveMap&&(e.emissiveMap.value=n.emissiveMap),n.bumpMap&&(e.bumpMap.value=n.bumpMap,e.bumpScale.value=n.bumpScale,1===n.side&&(e.bumpScale.value*=-1)),n.normalMap&&(e.normalMap.value=n.normalMap,e.normalScale.value.copy(n.normalScale),1===n.side&&e.normalScale.value.negate()),n.displacementMap&&(e.displacementMap.value=n.displacementMap,e.displacementScale.value=n.displacementScale,e.displacementBias.value=n.displacementBias);t.get(n).envMap&&(e.envMapIntensity.value=n.envMapIntensity)}return{refreshFogUniforms:function(t,e){t.fogColor.value.copy(e.color),e.isFog?(t.fogNear.value=e.near,t.fogFar.value=e.far):e.isFogExp2&&(t.fogDensity.value=e.density)},refreshMaterialUniforms:function(t,i,r,s,a){i.isMeshBasicMaterial?e(t,i):i.isMeshLambertMaterial?(e(t,i),function(t,e){e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap)}(t,i)):i.isMeshToonMaterial?(e(t,i),function(t,e){e.gradientMap&&(t.gradientMap.value=e.gradientMap);e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap);e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale,1===e.side&&(t.bumpScale.value*=-1));e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale),1===e.side&&t.normalScale.value.negate());e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(t,i)):i.isMeshPhongMaterial?(e(t,i),function(t,e){t.specular.value.copy(e.specular),t.shininess.value=Math.max(e.shininess,1e-4),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap);e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale,1===e.side&&(t.bumpScale.value*=-1));e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale),1===e.side&&t.normalScale.value.negate());e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(t,i)):i.isMeshStandardMaterial?(e(t,i),i.isMeshPhysicalMaterial?function(t,e,i){n(t,e),t.ior.value=e.ior,e.sheen>0&&(t.sheenColor.value.copy(e.sheenColor).multiplyScalar(e.sheen),t.sheenRoughness.value=e.sheenRoughness,e.sheenColorMap&&(t.sheenColorMap.value=e.sheenColorMap),e.sheenRoughnessMap&&(t.sheenRoughnessMap.value=e.sheenRoughnessMap));e.clearcoat>0&&(t.clearcoat.value=e.clearcoat,t.clearcoatRoughness.value=e.clearcoatRoughness,e.clearcoatMap&&(t.clearcoatMap.value=e.clearcoatMap),e.clearcoatRoughnessMap&&(t.clearcoatRoughnessMap.value=e.clearcoatRoughnessMap),e.clearcoatNormalMap&&(t.clearcoatNormalScale.value.copy(e.clearcoatNormalScale),t.clearcoatNormalMap.value=e.clearcoatNormalMap,1===e.side&&t.clearcoatNormalScale.value.negate()));e.transmission>0&&(t.transmission.value=e.transmission,t.transmissionSamplerMap.value=i.texture,t.transmissionSamplerSize.value.set(i.width,i.height),e.transmissionMap&&(t.transmissionMap.value=e.transmissionMap),t.thickness.value=e.thickness,e.thicknessMap&&(t.thicknessMap.value=e.thicknessMap),t.attenuationDistance.value=e.attenuationDistance,t.attenuationColor.value.copy(e.attenuationColor));t.specularIntensity.value=e.specularIntensity,t.specularColor.value.copy(e.specularColor),e.specularIntensityMap&&(t.specularIntensityMap.value=e.specularIntensityMap);e.specularColorMap&&(t.specularColorMap.value=e.specularColorMap)}(t,i,a):n(t,i)):i.isMeshMatcapMaterial?(e(t,i),function(t,e){e.matcap&&(t.matcap.value=e.matcap);e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale,1===e.side&&(t.bumpScale.value*=-1));e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale),1===e.side&&t.normalScale.value.negate());e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(t,i)):i.isMeshDepthMaterial?(e(t,i),function(t,e){e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(t,i)):i.isMeshDistanceMaterial?(e(t,i),function(t,e){e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias);t.referencePosition.value.copy(e.referencePosition),t.nearDistance.value=e.nearDistance,t.farDistance.value=e.farDistance}(t,i)):i.isMeshNormalMaterial?(e(t,i),function(t,e){e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale,1===e.side&&(t.bumpScale.value*=-1));e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale),1===e.side&&t.normalScale.value.negate());e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}(t,i)):i.isLineBasicMaterial?(function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity}(t,i),i.isLineDashedMaterial&&function(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}(t,i)):i.isPointsMaterial?function(t,e,n,i){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.size.value=e.size*n,t.scale.value=.5*i,e.map&&(t.map.value=e.map);e.alphaMap&&(t.alphaMap.value=e.alphaMap);e.alphaTest>0&&(t.alphaTest.value=e.alphaTest);let r;e.map?r=e.map:e.alphaMap&&(r=e.alphaMap);void 0!==r&&(!0===r.matrixAutoUpdate&&r.updateMatrix(),t.uvTransform.value.copy(r.matrix))}(t,i,r,s):i.isSpriteMaterial?function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.rotation.value=e.rotation,e.map&&(t.map.value=e.map);e.alphaMap&&(t.alphaMap.value=e.alphaMap);e.alphaTest>0&&(t.alphaTest.value=e.alphaTest);let n;e.map?n=e.map:e.alphaMap&&(n=e.alphaMap);void 0!==n&&(!0===n.matrixAutoUpdate&&n.updateMatrix(),t.uvTransform.value.copy(n.matrix))}(t,i):i.isShadowMaterial?(t.color.value.copy(i.color),t.opacity.value=i.opacity):i.isShaderMaterial&&(i.uniformsNeedUpdate=!1)}}}function aa(t={}){const e=void 0!==t.canvas?t.canvas:function(){const t=Dt("canvas");return t.style.display="block",t}(),n=void 0!==t.context?t.context:null,i=void 0!==t.alpha&&t.alpha,r=void 0===t.depth||t.depth,s=void 0===t.stencil||t.stencil,a=void 0!==t.antialias&&t.antialias,o=void 0===t.premultipliedAlpha||t.premultipliedAlpha,l=void 0!==t.preserveDrawingBuffer&&t.preserveDrawingBuffer,c=void 0!==t.powerPreference?t.powerPreference:"default",h=void 0!==t.failIfMajorPerformanceCaveat&&t.failIfMajorPerformanceCaveat;let d=null,m=null;const f=[],g=[];this.domElement=e,this.debug={checkShaderErrors:!0},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.outputEncoding=ot,this.physicallyCorrectLights=!1,this.toneMapping=0,this.toneMappingExposure=1;const v=this;let _=!1,M=0,S=0,E=null,A=-1,R=null;const L=new jt,C=new jt;let P=null,D=e.width,I=e.height,N=1,B=null,z=null;const O=new jt(0,0,D,I),F=new jt(0,0,D,I);let U=!1;const H=new vi;let G=!1,k=!1,V=null;const W=new Ae,j=new Zt,q={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function X(){return null===E?N:1}let J,Y,Z,K,Q,$,tt,et,nt,it,rt,st,at,lt,ct,ht,ut,dt,pt,mt,ft,gt,vt,yt=n;function xt(t,n){for(let i=0;i<t.length;i++){const r=t[i],s=e.getContext(r,n);if(null!==s)return s}return null}try{const t={alpha:!0,depth:r,stencil:s,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:l,powerPreference:c,failIfMajorPerformanceCaveat:h};if("setAttribute"in e&&e.setAttribute("data-engine","three.js r137"),e.addEventListener("webglcontextlost",bt,!1),e.addEventListener("webglcontextrestored",wt,!1),null===yt){const e=["webgl2","webgl","experimental-webgl"];if(!0===v.isWebGL1Renderer&&e.shift(),yt=xt(e,t),null===yt)throw xt(e)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}void 0===yt.getShaderPrecisionFormat&&(yt.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(t){throw console.error("THREE.WebGLRenderer: "+t.message),t}function _t(){J=new $i(yt),Y=new Ai(yt,J,t),J.init(Y),gt=new Qs(yt,J,Y),Z=new Zs(yt,J,Y),K=new nr(yt),Q=new zs,$=new Ks(yt,J,Z,Q,Y,gt,K),tt=new Li(v),et=new Qi(v),nt=new xi(yt,Y),vt=new Ti(yt,J,nt,Y),it=new tr(yt,nt,K,vt),rt=new lr(yt,it,nt,K),pt=new or(yt,Y,$),ht=new Ri(Q),st=new Bs(v,tt,et,J,Y,vt,ht),at=new sa(Q),lt=new Hs,ct=new qs(J,Y),dt=new Si(v,tt,Z,rt,i,o),ut=new Ys(v,rt,Y),mt=new Ei(yt,J,K,Y),ft=new er(yt,J,K,Y),K.programs=st.programs,v.capabilities=Y,v.extensions=J,v.properties=Q,v.renderLists=lt,v.shadowMap=ut,v.state=Z,v.info=K}_t();const Mt=new ra(v,yt);function bt(t){t.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),_=!0}function wt(){console.log("THREE.WebGLRenderer: Context Restored."),_=!1;const t=K.autoReset,e=ut.enabled,n=ut.autoUpdate,i=ut.needsUpdate,r=ut.type;_t(),K.autoReset=t,ut.enabled=e,ut.autoUpdate=n,ut.needsUpdate=i,ut.type=r}function St(t){const e=t.target;e.removeEventListener("dispose",St),function(t){(function(t){const e=Q.get(t).programs;void 0!==e&&(e.forEach((function(t){st.releaseProgram(t)})),t.isShaderMaterial&&st.releaseShaderCache(t))})(t),Q.remove(t)}(e)}this.xr=Mt,this.getContext=function(){return yt},this.getContextAttributes=function(){return yt.getContextAttributes()},this.forceContextLoss=function(){const t=J.get("WEBGL_lose_context");t&&t.loseContext()},this.forceContextRestore=function(){const t=J.get("WEBGL_lose_context");t&&t.restoreContext()},this.getPixelRatio=function(){return N},this.setPixelRatio=function(t){void 0!==t&&(N=t,this.setSize(D,I,!1))},this.getSize=function(t){return t.set(D,I)},this.setSize=function(t,n,i){Mt.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(D=t,I=n,e.width=Math.floor(t*N),e.height=Math.floor(n*N),!1!==i&&(e.style.width=t+"px",e.style.height=n+"px"),this.setViewport(0,0,t,n))},this.getDrawingBufferSize=function(t){return t.set(D*N,I*N).floor()},this.setDrawingBufferSize=function(t,n,i){D=t,I=n,N=i,e.width=Math.floor(t*i),e.height=Math.floor(n*i),this.setViewport(0,0,t,n)},this.getCurrentViewport=function(t){return t.copy(L)},this.getViewport=function(t){return t.copy(O)},this.setViewport=function(t,e,n,i){t.isVector4?O.set(t.x,t.y,t.z,t.w):O.set(t,e,n,i),Z.viewport(L.copy(O).multiplyScalar(N).floor())},this.getScissor=function(t){return t.copy(F)},this.setScissor=function(t,e,n,i){t.isVector4?F.set(t.x,t.y,t.z,t.w):F.set(t,e,n,i),Z.scissor(C.copy(F).multiplyScalar(N).floor())},this.getScissorTest=function(){return U},this.setScissorTest=function(t){Z.setScissorTest(U=t)},this.setOpaqueSort=function(t){B=t},this.setTransparentSort=function(t){z=t},this.getClearColor=function(t){return t.copy(dt.getClearColor())},this.setClearColor=function(){dt.setClearColor.apply(dt,arguments)},this.getClearAlpha=function(){return dt.getClearAlpha()},this.setClearAlpha=function(){dt.setClearAlpha.apply(dt,arguments)},this.clear=function(t,e,n){let i=0;(void 0===t||t)&&(i|=16384),(void 0===e||e)&&(i|=256),(void 0===n||n)&&(i|=1024),yt.clear(i)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){e.removeEventListener("webglcontextlost",bt,!1),e.removeEventListener("webglcontextrestored",wt,!1),lt.dispose(),ct.dispose(),Q.dispose(),tt.dispose(),et.dispose(),rt.dispose(),vt.dispose(),st.dispose(),Mt.dispose(),Mt.removeEventListener("sessionstart",Et),Mt.removeEventListener("sessionend",At),V&&(V.dispose(),V=null),Rt.stop()},this.renderBufferDirect=function(t,e,n,i,r,s){null===e&&(e=q);const a=r.isMesh&&r.matrixWorld.determinant()<0,o=function(t,e,n,i,r){!0!==e.isScene&&(e=q);$.resetTextureUnits();const s=e.fog,a=i.isMeshStandardMaterial?e.environment:null,o=null===E?v.outputEncoding:!0===E.isXRRenderTarget?E.texture.encoding:ot,l=(i.isMeshStandardMaterial?et:tt).get(i.envMap||a),c=!0===i.vertexColors&&!!n.attributes.color&&4===n.attributes.color.itemSize,h=!!i.normalMap&&!!n.attributes.tangent,u=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=n.morphAttributes.position?n.morphAttributes.position.length:0,f=i.toneMapped?v.toneMapping:0,g=Q.get(i),y=m.state.lights;if(!0===G&&(!0===k||t!==R)){const e=t===R&&i.id===A;ht.setState(i,t,e)}let x=!1;i.version===g.__version?g.needsLights&&g.lightsStateVersion!==y.state.version||g.outputEncoding!==o||r.isInstancedMesh&&!1===g.instancing?x=!0:r.isInstancedMesh||!0!==g.instancing?r.isSkinnedMesh&&!1===g.skinning?x=!0:r.isSkinnedMesh||!0!==g.skinning?g.envMap!==l||i.fog&&g.fog!==s?x=!0:void 0===g.numClippingPlanes||g.numClippingPlanes===ht.numPlanes&&g.numIntersection===ht.numIntersection?(g.vertexAlphas!==c||g.vertexTangents!==h||g.morphTargets!==u||g.morphNormals!==d||g.toneMapping!==f||!0===Y.isWebGL2&&g.morphTargetsCount!==p)&&(x=!0):x=!0:x=!0:x=!0:(x=!0,g.__version=i.version);let _=g.currentProgram;!0===x&&(_=Nt(i,e,r));let M=!1,b=!1,w=!1;const S=_.getUniforms(),T=g.uniforms;Z.useProgram(_.program)&&(M=!0,b=!0,w=!0);i.id!==A&&(A=i.id,b=!0);if(M||R!==t){if(S.setValue(yt,"projectionMatrix",t.projectionMatrix),Y.logarithmicDepthBuffer&&S.setValue(yt,"logDepthBufFC",2/(Math.log(t.far+1)/Math.LN2)),R!==t&&(R=t,b=!0,w=!0),i.isShaderMaterial||i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshStandardMaterial||i.envMap){const e=S.map.cameraPosition;void 0!==e&&e.setValue(yt,j.setFromMatrixPosition(t.matrixWorld))}(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&S.setValue(yt,"isOrthographic",!0===t.isOrthographicCamera),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial||i.isShadowMaterial||r.isSkinnedMesh)&&S.setValue(yt,"viewMatrix",t.matrixWorldInverse)}if(r.isSkinnedMesh){S.setOptional(yt,r,"bindMatrix"),S.setOptional(yt,r,"bindMatrixInverse");const t=r.skeleton;t&&(Y.floatVertexTextures?(null===t.boneTexture&&t.computeBoneTexture(),S.setValue(yt,"boneTexture",t.boneTexture,$),S.setValue(yt,"boneTextureSize",t.boneTextureSize)):S.setOptional(yt,t,"boneMatrices"))}!n||void 0===n.morphAttributes.position&&void 0===n.morphAttributes.normal||pt.update(r,n,i,_);(b||g.receiveShadow!==r.receiveShadow)&&(g.receiveShadow=r.receiveShadow,S.setValue(yt,"receiveShadow",r.receiveShadow));b&&(S.setValue(yt,"toneMappingExposure",v.toneMappingExposure),g.needsLights&&(C=w,(L=T).ambientLightColor.needsUpdate=C,L.lightProbe.needsUpdate=C,L.directionalLights.needsUpdate=C,L.directionalLightShadows.needsUpdate=C,L.pointLights.needsUpdate=C,L.pointLightShadows.needsUpdate=C,L.spotLights.needsUpdate=C,L.spotLightShadows.needsUpdate=C,L.rectAreaLights.needsUpdate=C,L.hemisphereLights.needsUpdate=C),s&&i.fog&&at.refreshFogUniforms(T,s),at.refreshMaterialUniforms(T,i,N,I,V),ps.upload(yt,g.uniformsList,T,$));var L,C;i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(ps.upload(yt,g.uniformsList,T,$),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&S.setValue(yt,"center",r.center);return S.setValue(yt,"modelViewMatrix",r.modelViewMatrix),S.setValue(yt,"normalMatrix",r.normalMatrix),S.setValue(yt,"modelMatrix",r.matrixWorld),_}(t,e,n,i,r);Z.setMaterial(i,a);let l=n.index;const c=n.attributes.position;if(null===l){if(void 0===c||0===c.count)return}else if(0===l.count)return;let h,u=1;!0===i.wireframe&&(l=it.getWireframeAttribute(n),u=2),vt.setup(r,i,o,n,l);let d=mt;null!==l&&(h=nt.get(l),d=ft,d.setIndex(h));const p=null!==l?l.count:c.count,f=n.drawRange.start*u,g=n.drawRange.count*u,y=null!==s?s.start*u:0,x=null!==s?s.count*u:1/0,_=Math.max(f,y),M=Math.min(p,f+g,y+x)-1,b=Math.max(0,M-_+1);if(0!==b){if(r.isMesh)!0===i.wireframe?(Z.setLineWidth(i.wireframeLinewidth*X()),d.setMode(1)):d.setMode(4);else if(r.isLine){let t=i.linewidth;void 0===t&&(t=1),Z.setLineWidth(t*X()),r.isLineSegments?d.setMode(1):r.isLineLoop?d.setMode(2):d.setMode(3)}else r.isPoints?d.setMode(0):r.isSprite&&d.setMode(4);if(r.isInstancedMesh)d.renderInstances(_,b,r.count);else if(n.isInstancedBufferGeometry){const t=Math.min(n.instanceCount,n._maxInstanceCount);d.renderInstances(_,b,t)}else d.render(_,b)}},this.compile=function(t,e){m=ct.get(t),m.init(),g.push(m),t.traverseVisible((function(t){t.isLight&&t.layers.test(e.layers)&&(m.pushLight(t),t.castShadow&&m.pushShadow(t))})),m.setupLights(v.physicallyCorrectLights),t.traverse((function(e){const n=e.material;if(n)if(Array.isArray(n))for(let i=0;i<n.length;i++){Nt(n[i],t,e)}else Nt(n,t,e)})),g.pop(),m=null};let Tt=null;function Et(){Rt.stop()}function At(){Rt.start()}const Rt=new yi;function Lt(t,e,n,i){if(!1===t.visible)return;if(t.layers.test(e.layers))if(t.isGroup)n=t.renderOrder;else if(t.isLOD)!0===t.autoUpdate&&t.update(e);else if(t.isLight)m.pushLight(t),t.castShadow&&m.pushShadow(t);else if(t.isSprite){if(!t.frustumCulled||H.intersectsSprite(t)){i&&j.setFromMatrixPosition(t.matrixWorld).applyMatrix4(W);const e=rt.update(t),r=t.material;r.visible&&d.push(t,e,r,n,j.z,null)}}else if((t.isMesh||t.isLine||t.isPoints)&&(t.isSkinnedMesh&&t.skeleton.frame!==K.render.frame&&(t.skeleton.update(),t.skeleton.frame=K.render.frame),!t.frustumCulled||H.intersectsObject(t))){i&&j.setFromMatrixPosition(t.matrixWorld).applyMatrix4(W);const e=rt.update(t),r=t.material;if(Array.isArray(r)){const i=e.groups;for(let s=0,a=i.length;s<a;s++){const a=i[s],o=r[a.materialIndex];o&&o.visible&&d.push(t,e,o,n,j.z,a)}}else r.visible&&d.push(t,e,r,n,j.z,null)}const r=t.children;for(let t=0,s=r.length;t<s;t++)Lt(r[t],e,n,i)}function Ct(t,e,n,i){const r=t.opaque,s=t.transmissive,o=t.transparent;m.setupLightsView(n),s.length>0&&function(t,e,n){if(null===V){const t=!0===a&&!0===Y.isWebGL2;V=new(t?Jt:qt)(1024,1024,{generateMipmaps:!0,type:null!==gt.convert(w)?w:x,minFilter:y,magFilter:p,wrapS:u,wrapT:u,useRenderToTexture:J.has("WEBGL_multisampled_render_to_texture")})}const i=v.getRenderTarget();v.setRenderTarget(V),v.clear();const r=v.toneMapping;v.toneMapping=0,Pt(t,e,n),v.toneMapping=r,$.updateMultisampleRenderTarget(V),$.updateRenderTargetMipmap(V),v.setRenderTarget(i)}(r,e,n),i&&Z.viewport(L.copy(i)),r.length>0&&Pt(r,e,n),s.length>0&&Pt(s,e,n),o.length>0&&Pt(o,e,n)}function Pt(t,e,n){const i=!0===e.isScene?e.overrideMaterial:null;for(let r=0,s=t.length;r<s;r++){const s=t[r],a=s.object,o=s.geometry,l=null===i?s.material:i,c=s.group;a.layers.test(n.layers)&&It(a,e,n,o,l,c)}}function It(t,e,n,i,r,s){t.onBeforeRender(v,e,n,i,r,s),t.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix),r.onBeforeRender(v,e,n,i,t,s),!0===r.transparent&&2===r.side?(r.side=1,r.needsUpdate=!0,v.renderBufferDirect(n,e,i,r,t,s),r.side=0,r.needsUpdate=!0,v.renderBufferDirect(n,e,i,r,t,s),r.side=2):v.renderBufferDirect(n,e,i,r,t,s),t.onAfterRender(v,e,n,i,r,s)}function Nt(t,e,n){!0!==e.isScene&&(e=q);const i=Q.get(t),r=m.state.lights,s=m.state.shadowsArray,a=r.state.version,o=st.getParameters(t,r.state,s,e,n),l=st.getProgramCacheKey(o);let c=i.programs;i.environment=t.isMeshStandardMaterial?e.environment:null,i.fog=e.fog,i.envMap=(t.isMeshStandardMaterial?et:tt).get(t.envMap||i.environment),void 0===c&&(t.addEventListener("dispose",St),c=new Map,i.programs=c);let h=c.get(l);if(void 0!==h){if(i.currentProgram===h&&i.lightsStateVersion===a)return Bt(t,o),h}else o.uniforms=st.getUniforms(t),t.onBuild(n,o,v),t.onBeforeCompile(o,v),h=st.acquireProgram(o,l),c.set(l,h),i.uniforms=o.uniforms;const u=i.uniforms;(t.isShaderMaterial||t.isRawShaderMaterial)&&!0!==t.clipping||(u.clippingPlanes=ht.uniform),Bt(t,o),i.needsLights=function(t){return t.isMeshLambertMaterial||t.isMeshToonMaterial||t.isMeshPhongMaterial||t.isMeshStandardMaterial||t.isShadowMaterial||t.isShaderMaterial&&!0===t.lights}(t),i.lightsStateVersion=a,i.needsLights&&(u.ambientLightColor.value=r.state.ambient,u.lightProbe.value=r.state.probe,u.directionalLights.value=r.state.directional,u.directionalLightShadows.value=r.state.directionalShadow,u.spotLights.value=r.state.spot,u.spotLightShadows.value=r.state.spotShadow,u.rectAreaLights.value=r.state.rectArea,u.ltc_1.value=r.state.rectAreaLTC1,u.ltc_2.value=r.state.rectAreaLTC2,u.pointLights.value=r.state.point,u.pointLightShadows.value=r.state.pointShadow,u.hemisphereLights.value=r.state.hemi,u.directionalShadowMap.value=r.state.directionalShadowMap,u.directionalShadowMatrix.value=r.state.directionalShadowMatrix,u.spotShadowMap.value=r.state.spotShadowMap,u.spotShadowMatrix.value=r.state.spotShadowMatrix,u.pointShadowMap.value=r.state.pointShadowMap,u.pointShadowMatrix.value=r.state.pointShadowMatrix);const d=h.getUniforms(),p=ps.seqWithValue(d.seq,u);return i.currentProgram=h,i.uniformsList=p,h}function Bt(t,e){const n=Q.get(t);n.outputEncoding=e.outputEncoding,n.instancing=e.instancing,n.skinning=e.skinning,n.morphTargets=e.morphTargets,n.morphNormals=e.morphNormals,n.morphTargetsCount=e.morphTargetsCount,n.numClippingPlanes=e.numClippingPlanes,n.numIntersection=e.numClipIntersection,n.vertexAlphas=e.vertexAlphas,n.vertexTangents=e.vertexTangents,n.toneMapping=e.toneMapping}Rt.setAnimationLoop((function(t){Tt&&Tt(t)})),"undefined"!=typeof window&&Rt.setContext(window),this.setAnimationLoop=function(t){Tt=t,Mt.setAnimationLoop(t),null===t?Rt.stop():Rt.start()},Mt.addEventListener("sessionstart",Et),Mt.addEventListener("sessionend",At),this.render=function(t,e){if(void 0!==e&&!0!==e.isCamera)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");if(!0===_)return;!0===t.autoUpdate&&t.updateMatrixWorld(),null===e.parent&&e.updateMatrixWorld(),!0===Mt.enabled&&!0===Mt.isPresenting&&(!0===Mt.cameraAutoUpdate&&Mt.updateCamera(e),e=Mt.getCamera()),!0===t.isScene&&t.onBeforeRender(v,t,e,E),m=ct.get(t,g.length),m.init(),g.push(m),W.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),H.setFromProjectionMatrix(W),k=this.localClippingEnabled,G=ht.init(this.clippingPlanes,k,e),d=lt.get(t,f.length),d.init(),f.push(d),Lt(t,e,0,v.sortObjects),d.finish(),!0===v.sortObjects&&d.sort(B,z),!0===G&&ht.beginShadows();const n=m.state.shadowsArray;if(ut.render(n,t,e),!0===G&&ht.endShadows(),!0===this.info.autoReset&&this.info.reset(),dt.render(d,t),m.setupLights(v.physicallyCorrectLights),e.isArrayCamera){const n=e.cameras;for(let e=0,i=n.length;e<i;e++){const i=n[e];Ct(d,t,i,i.viewport)}}else Ct(d,t,e);null!==E&&($.updateMultisampleRenderTarget(E),$.updateRenderTargetMipmap(E)),!0===t.isScene&&t.onAfterRender(v,t,e),Z.buffers.depth.setTest(!0),Z.buffers.depth.setMask(!0),Z.buffers.color.setMask(!0),Z.setPolygonOffset(!1),vt.resetDefaultState(),A=-1,R=null,g.pop(),m=g.length>0?g[g.length-1]:null,f.pop(),d=f.length>0?f[f.length-1]:null},this.getActiveCubeFace=function(){return M},this.getActiveMipmapLevel=function(){return S},this.getRenderTarget=function(){return E},this.setRenderTargetTextures=function(t,e,n){Q.get(t.texture).__webglTexture=e,Q.get(t.depthTexture).__webglTexture=n;const i=Q.get(t);i.__hasExternalTextures=!0,i.__hasExternalTextures&&(i.__autoAllocateDepthBuffer=void 0===n,i.__autoAllocateDepthBuffer||t.useRenderToTexture&&(console.warn("render-to-texture extension was disabled because an external texture was provided"),t.useRenderToTexture=!1,t.useRenderbuffer=!0))},this.setRenderTargetFramebuffer=function(t,e){const n=Q.get(t);n.__webglFramebuffer=e,n.__useDefaultFramebuffer=void 0===e},this.setRenderTarget=function(t,e=0,n=0){E=t,M=e,S=n;let i=!0;if(t){const e=Q.get(t);void 0!==e.__useDefaultFramebuffer?(Z.bindFramebuffer(36160,null),i=!1):void 0===e.__webglFramebuffer?$.setupRenderTarget(t):e.__hasExternalTextures&&$.rebindTextures(t,Q.get(t.texture).__webglTexture,Q.get(t.depthTexture).__webglTexture)}let r=null,s=!1,a=!1;if(t){const n=t.texture;(n.isDataTexture3D||n.isDataTexture2DArray)&&(a=!0);const i=Q.get(t).__webglFramebuffer;t.isWebGLCubeRenderTarget?(r=i[e],s=!0):r=t.useRenderbuffer?Q.get(t).__webglMultisampledFramebuffer:i,L.copy(t.viewport),C.copy(t.scissor),P=t.scissorTest}else L.copy(O).multiplyScalar(N).floor(),C.copy(F).multiplyScalar(N).floor(),P=U;if(Z.bindFramebuffer(36160,r)&&Y.drawBuffers&&i&&Z.drawBuffers(t,r),Z.viewport(L),Z.scissor(C),Z.setScissorTest(P),s){const i=Q.get(t.texture);yt.framebufferTexture2D(36160,36064,34069+e,i.__webglTexture,n)}else if(a){const i=Q.get(t.texture),r=e||0;yt.framebufferTextureLayer(36160,36064,i.__webglTexture,n||0,r)}A=-1},this.readRenderTargetPixels=function(t,e,n,i,r,s,a){if(!t||!t.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=Q.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){Z.bindFramebuffer(36160,o);try{const a=t.texture,o=a.format,l=a.type;if(o!==T&&gt.convert(o)!==yt.getParameter(35739))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");const c=l===w&&(J.has("EXT_color_buffer_half_float")||Y.isWebGL2&&J.has("EXT_color_buffer_float"));if(!(l===x||gt.convert(l)===yt.getParameter(35738)||l===b&&(Y.isWebGL2||J.has("OES_texture_float")||J.has("WEBGL_color_buffer_float"))||c))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");36053===yt.checkFramebufferStatus(36160)?e>=0&&e<=t.width-i&&n>=0&&n<=t.height-r&&yt.readPixels(e,n,i,r,gt.convert(o),gt.convert(l),s):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{const t=null!==E?Q.get(E).__webglFramebuffer:null;Z.bindFramebuffer(36160,t)}}},this.copyFramebufferToTexture=function(t,e,n=0){if(!0!==e.isFramebufferTexture)return void console.error("THREE.WebGLRenderer: copyFramebufferToTexture() can only be used with FramebufferTexture.");const i=Math.pow(2,-n),r=Math.floor(e.image.width*i),s=Math.floor(e.image.height*i);$.setTexture2D(e,0),yt.copyTexSubImage2D(3553,n,0,0,t.x,t.y,r,s),Z.unbindTexture()},this.copyTextureToTexture=function(t,e,n,i=0){const r=e.image.width,s=e.image.height,a=gt.convert(n.format),o=gt.convert(n.type);$.setTexture2D(n,0),yt.pixelStorei(37440,n.flipY),yt.pixelStorei(37441,n.premultiplyAlpha),yt.pixelStorei(3317,n.unpackAlignment),e.isDataTexture?yt.texSubImage2D(3553,i,t.x,t.y,r,s,a,o,e.image.data):e.isCompressedTexture?yt.compressedTexSubImage2D(3553,i,t.x,t.y,e.mipmaps[0].width,e.mipmaps[0].height,a,e.mipmaps[0].data):yt.texSubImage2D(3553,i,t.x,t.y,a,o,e.image),0===i&&n.generateMipmaps&&yt.generateMipmap(3553),Z.unbindTexture()},this.copyTextureToTexture3D=function(t,e,n,i,r=0){if(v.isWebGL1Renderer)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");const s=t.max.x-t.min.x+1,a=t.max.y-t.min.y+1,o=t.max.z-t.min.z+1,l=gt.convert(i.format),c=gt.convert(i.type);let h;if(i.isDataTexture3D)$.setTexture3D(i,0),h=32879;else{if(!i.isDataTexture2DArray)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");$.setTexture2DArray(i,0),h=35866}yt.pixelStorei(37440,i.flipY),yt.pixelStorei(37441,i.premultiplyAlpha),yt.pixelStorei(3317,i.unpackAlignment);const u=yt.getParameter(3314),d=yt.getParameter(32878),p=yt.getParameter(3316),m=yt.getParameter(3315),f=yt.getParameter(32877),g=n.isCompressedTexture?n.mipmaps[0]:n.image;yt.pixelStorei(3314,g.width),yt.pixelStorei(32878,g.height),yt.pixelStorei(3316,t.min.x),yt.pixelStorei(3315,t.min.y),yt.pixelStorei(32877,t.min.z),n.isDataTexture||n.isDataTexture3D?yt.texSubImage3D(h,r,e.x,e.y,e.z,s,a,o,l,c,g.data):n.isCompressedTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),yt.compressedTexSubImage3D(h,r,e.x,e.y,e.z,s,a,o,l,g.data)):yt.texSubImage3D(h,r,e.x,e.y,e.z,s,a,o,l,c,g),yt.pixelStorei(3314,u),yt.pixelStorei(32878,d),yt.pixelStorei(3316,p),yt.pixelStorei(3315,m),yt.pixelStorei(32877,f),0===r&&i.generateMipmaps&&yt.generateMipmap(h),Z.unbindTexture()},this.initTexture=function(t){$.setTexture2D(t,0),Z.unbindTexture()},this.resetState=function(){M=0,S=0,E=null,Z.reset(),vt.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}aa.prototype.isWebGLRenderer=!0;class oa extends aa{}oa.prototype.isWebGL1Renderer=!0;class la{constructor(t,e=25e-5){this.name="",this.color=new Ut(t),this.density=e}clone(){return new la(this.color,this.density)}toJSON(){return{type:"FogExp2",color:this.color.getHex(),density:this.density}}}la.prototype.isFogExp2=!0;class ca{constructor(t,e=1,n=1e3){this.name="",this.color=new Ut(t),this.near=e,this.far=n}clone(){return new ca(this.color,this.near,this.far)}toJSON(){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}}}ca.prototype.isFog=!0;class ha extends Qe{constructor(){super(),this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),null!==t.background&&(this.background=t.background.clone()),null!==t.environment&&(this.environment=t.environment.clone()),null!==t.fog&&(this.fog=t.fog.clone()),null!==t.overrideMaterial&&(this.overrideMaterial=t.overrideMaterial.clone()),this.autoUpdate=t.autoUpdate,this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return null!==this.fog&&(e.object.fog=this.fog.toJSON()),e}}ha.prototype.isScene=!0;class ua{constructor(t,e){this.array=t,this.stride=e,this.count=void 0!==t?t.length/e:0,this.usage=ht,this.updateRange={offset:0,count:-1},this.version=0,this.uuid=xt()}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,n){t*=this.stride,n*=e.stride;for(let i=0,r=this.stride;i<r;i++)this.array[t+i]=e.array[n+i];return this}set(t,e=0){return this.array.set(t,e),this}clone(t){void 0===t.arrayBuffers&&(t.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=xt()),void 0===t.arrayBuffers[this.array.buffer._uuid]&&(t.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const e=new this.array.constructor(t.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(e,this.stride);return n.setUsage(this.usage),n}onUpload(t){return this.onUploadCallback=t,this}toJSON(t){return void 0===t.arrayBuffers&&(t.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=xt()),void 0===t.arrayBuffers[this.array.buffer._uuid]&&(t.arrayBuffers[this.array.buffer._uuid]=Array.prototype.slice.call(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}ua.prototype.isInterleavedBuffer=!0;const da=new Zt;class pa{constructor(t,e,n,i=!1){this.name="",this.data=t,this.itemSize=e,this.offset=n,this.normalized=!0===i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(t){this.data.needsUpdate=t}applyMatrix4(t){for(let e=0,n=this.data.count;e<n;e++)da.x=this.getX(e),da.y=this.getY(e),da.z=this.getZ(e),da.applyMatrix4(t),this.setXYZ(e,da.x,da.y,da.z);return this}applyNormalMatrix(t){for(let e=0,n=this.count;e<n;e++)da.x=this.getX(e),da.y=this.getY(e),da.z=this.getZ(e),da.applyNormalMatrix(t),this.setXYZ(e,da.x,da.y,da.z);return this}transformDirection(t){for(let e=0,n=this.count;e<n;e++)da.x=this.getX(e),da.y=this.getY(e),da.z=this.getZ(e),da.transformDirection(t),this.setXYZ(e,da.x,da.y,da.z);return this}setX(t,e){return this.data.array[t*this.data.stride+this.offset]=e,this}setY(t,e){return this.data.array[t*this.data.stride+this.offset+1]=e,this}setZ(t,e){return this.data.array[t*this.data.stride+this.offset+2]=e,this}setW(t,e){return this.data.array[t*this.data.stride+this.offset+3]=e,this}getX(t){return this.data.array[t*this.data.stride+this.offset]}getY(t){return this.data.array[t*this.data.stride+this.offset+1]}getZ(t){return this.data.array[t*this.data.stride+this.offset+2]}getW(t){return this.data.array[t*this.data.stride+this.offset+3]}setXY(t,e,n){return t=t*this.data.stride+this.offset,this.data.array[t+0]=e,this.data.array[t+1]=n,this}setXYZ(t,e,n,i){return t=t*this.data.stride+this.offset,this.data.array[t+0]=e,this.data.array[t+1]=n,this.data.array[t+2]=i,this}setXYZW(t,e,n,i,r){return t=t*this.data.stride+this.offset,this.data.array[t+0]=e,this.data.array[t+1]=n,this.data.array[t+2]=i,this.data.array[t+3]=r,this}clone(t){if(void 0===t){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.");const t=[];for(let e=0;e<this.count;e++){const n=e*this.data.stride+this.offset;for(let e=0;e<this.itemSize;e++)t.push(this.data.array[n+e])}return new gn(new this.array.constructor(t),this.itemSize,this.normalized)}return void 0===t.interleavedBuffers&&(t.interleavedBuffers={}),void 0===t.interleavedBuffers[this.data.uuid]&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new pa(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(t){if(void 0===t){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.");const t=[];for(let e=0;e<this.count;e++){const n=e*this.data.stride+this.offset;for(let e=0;e<this.itemSize;e++)t.push(this.data.array[n+e])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}return void 0===t.interleavedBuffers&&(t.interleavedBuffers={}),void 0===t.interleavedBuffers[this.data.uuid]&&(t.interleavedBuffers[this.data.uuid]=this.data.toJSON(t)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}pa.prototype.isInterleavedBufferAttribute=!0;class ma extends dn{constructor(t){super(),this.type="SpriteMaterial",this.color=new Ut(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!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}}let fa;ma.prototype.isSpriteMaterial=!0;const ga=new Zt,va=new Zt,ya=new Zt,xa=new At,_a=new At,Ma=new Ae,ba=new Zt,wa=new Zt,Sa=new Zt,Ta=new At,Ea=new At,Aa=new At;class Ra extends Qe{constructor(t){if(super(),this.type="Sprite",void 0===fa){fa=new Nn;const t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),e=new ua(t,5);fa.setIndex([0,1,2,0,2,3]),fa.setAttribute("position",new pa(e,3,0,!1)),fa.setAttribute("uv",new pa(e,2,3,!1))}this.geometry=fa,this.material=void 0!==t?t:new ma,this.center=new At(.5,.5)}raycast(t,e){null===t.camera&&console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),va.setFromMatrixScale(this.matrixWorld),Ma.copy(t.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(t.camera.matrixWorldInverse,this.matrixWorld),ya.setFromMatrixPosition(this.modelViewMatrix),t.camera.isPerspectiveCamera&&!1===this.material.sizeAttenuation&&va.multiplyScalar(-ya.z);const n=this.material.rotation;let i,r;0!==n&&(r=Math.cos(n),i=Math.sin(n));const s=this.center;La(ba.set(-.5,-.5,0),ya,s,va,i,r),La(wa.set(.5,-.5,0),ya,s,va,i,r),La(Sa.set(.5,.5,0),ya,s,va,i,r),Ta.set(0,0),Ea.set(1,0),Aa.set(1,1);let a=t.ray.intersectTriangle(ba,wa,Sa,!1,ga);if(null===a&&(La(wa.set(-.5,.5,0),ya,s,va,i,r),Ea.set(0,1),a=t.ray.intersectTriangle(ba,Sa,wa,!1,ga),null===a))return;const o=t.ray.origin.distanceTo(ga);o<t.near||o>t.far||e.push({distance:o,point:ga.clone(),uv:hn.getUV(ga,ba,wa,Sa,Ta,Ea,Aa,new At),face:null,object:this})}copy(t){return super.copy(t),void 0!==t.center&&this.center.copy(t.center),this.material=t.material,this}}function La(t,e,n,i,r,s){xa.subVectors(t,n).addScalar(.5).multiply(i),void 0!==r?(_a.x=s*xa.x-r*xa.y,_a.y=r*xa.x+s*xa.y):_a.copy(xa),t.copy(e),t.x+=_a.x,t.y+=_a.y,t.applyMatrix4(Ma)}Ra.prototype.isSprite=!0;const Ca=new Zt,Pa=new Zt;class Da extends Qe{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(t){super.copy(t,!1);const e=t.levels;for(let t=0,n=e.length;t<n;t++){const n=e[t];this.addLevel(n.object.clone(),n.distance)}return this.autoUpdate=t.autoUpdate,this}addLevel(t,e=0){e=Math.abs(e);const n=this.levels;let i;for(i=0;i<n.length&&!(e<n[i].distance);i++);return n.splice(i,0,{distance:e,object:t}),this.add(t),this}getCurrentLevel(){return this._currentLevel}getObjectForDistance(t){const e=this.levels;if(e.length>0){let n,i;for(n=1,i=e.length;n<i&&!(t<e[n].distance);n++);return e[n-1].object}return null}raycast(t,e){if(this.levels.length>0){Ca.setFromMatrixPosition(this.matrixWorld);const n=t.ray.origin.distanceTo(Ca);this.getObjectForDistance(n).raycast(t,e)}}update(t){const e=this.levels;if(e.length>1){Ca.setFromMatrixPosition(t.matrixWorld),Pa.setFromMatrixPosition(this.matrixWorld);const n=Ca.distanceTo(Pa)/t.zoom;let i,r;for(e[0].object.visible=!0,i=1,r=e.length;i<r&&n>=e[i].distance;i++)e[i-1].object.visible=!1,e[i].object.visible=!0;for(this._currentLevel=i-1;i<r;i++)e[i].object.visible=!1}}toJSON(t){const e=super.toJSON(t);!1===this.autoUpdate&&(e.object.autoUpdate=!1),e.object.levels=[];const n=this.levels;for(let t=0,i=n.length;t<i;t++){const i=n[t];e.object.levels.push({object:i.object.uuid,distance:i.distance})}return e}}const Ia=new Zt,Na=new jt,Ba=new jt,za=new Zt,Oa=new Ae;class Fa extends Qn{constructor(t,e){super(t,e),this.type="SkinnedMesh",this.bindMode="attached",this.bindMatrix=new Ae,this.bindMatrixInverse=new Ae}copy(t){return super.copy(t),this.bindMode=t.bindMode,this.bindMatrix.copy(t.bindMatrix),this.bindMatrixInverse.copy(t.bindMatrixInverse),this.skeleton=t.skeleton,this}bind(t,e){this.skeleton=t,void 0===e&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),e=this.matrixWorld),this.bindMatrix.copy(e),this.bindMatrixInverse.copy(e).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const t=new jt,e=this.geometry.attributes.skinWeight;for(let n=0,i=e.count;n<i;n++){t.x=e.getX(n),t.y=e.getY(n),t.z=e.getZ(n),t.w=e.getW(n);const i=1/t.manhattanLength();i!==1/0?t.multiplyScalar(i):t.set(1,0,0,0),e.setXYZW(n,t.x,t.y,t.z,t.w)}}updateMatrixWorld(t){super.updateMatrixWorld(t),"attached"===this.bindMode?this.bindMatrixInverse.copy(this.matrixWorld).invert():"detached"===this.bindMode?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}boneTransform(t,e){const n=this.skeleton,i=this.geometry;Na.fromBufferAttribute(i.attributes.skinIndex,t),Ba.fromBufferAttribute(i.attributes.skinWeight,t),Ia.copy(e).applyMatrix4(this.bindMatrix),e.set(0,0,0);for(let t=0;t<4;t++){const i=Ba.getComponent(t);if(0!==i){const r=Na.getComponent(t);Oa.multiplyMatrices(n.bones[r].matrixWorld,n.boneInverses[r]),e.addScaledVector(za.copy(Ia).applyMatrix4(Oa),i)}}return e.applyMatrix4(this.bindMatrixInverse)}}Fa.prototype.isSkinnedMesh=!0;class Ua extends Qe{constructor(){super(),this.type="Bone"}}Ua.prototype.isBone=!0;class Ha extends Vt{constructor(t=null,e=1,n=1,i,r,s,a,o,l=1003,c=1003,h,u){super(null,s,a,o,l,c,i,r,h,u),this.image={data:t,width:e,height:n},this.magFilter=l,this.minFilter=c,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}Ha.prototype.isDataTexture=!0;const Ga=new Ae,ka=new Ae;class Va{constructor(t=[],e=[]){this.uuid=xt(),this.bones=t.slice(0),this.boneInverses=e,this.boneMatrices=null,this.boneTexture=null,this.boneTextureSize=0,this.frame=-1,this.init()}init(){const t=this.bones,e=this.boneInverses;if(this.boneMatrices=new Float32Array(16*t.length),0===e.length)this.calculateInverses();else if(t.length!==e.length){console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let t=0,e=this.bones.length;t<e;t++)this.boneInverses.push(new Ae)}}calculateInverses(){this.boneInverses.length=0;for(let t=0,e=this.bones.length;t<e;t++){const e=new Ae;this.bones[t]&&e.copy(this.bones[t].matrixWorld).invert(),this.boneInverses.push(e)}}pose(){for(let t=0,e=this.bones.length;t<e;t++){const e=this.bones[t];e&&e.matrixWorld.copy(this.boneInverses[t]).invert()}for(let t=0,e=this.bones.length;t<e;t++){const e=this.bones[t];e&&(e.parent&&e.parent.isBone?(e.matrix.copy(e.parent.matrixWorld).invert(),e.matrix.multiply(e.matrixWorld)):e.matrix.copy(e.matrixWorld),e.matrix.decompose(e.position,e.quaternion,e.scale))}}update(){const t=this.bones,e=this.boneInverses,n=this.boneMatrices,i=this.boneTexture;for(let i=0,r=t.length;i<r;i++){const r=t[i]?t[i].matrixWorld:ka;Ga.multiplyMatrices(r,e[i]),Ga.toArray(n,16*i)}null!==i&&(i.needsUpdate=!0)}clone(){return new Va(this.bones,this.boneInverses)}computeBoneTexture(){let t=Math.sqrt(4*this.bones.length);t=St(t),t=Math.max(t,4);const e=new Float32Array(t*t*4);e.set(this.boneMatrices);const n=new Ha(e,t,t,T,b);return n.needsUpdate=!0,this.boneMatrices=e,this.boneTexture=n,this.boneTextureSize=t,this}getBoneByName(t){for(let e=0,n=this.bones.length;e<n;e++){const n=this.bones[e];if(n.name===t)return n}}dispose(){null!==this.boneTexture&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(t,e){this.uuid=t.uuid;for(let n=0,i=t.bones.length;n<i;n++){const i=t.bones[n];let r=e[i];void 0===r&&(console.warn("THREE.Skeleton: No bone found with UUID:",i),r=new Ua),this.bones.push(r),this.boneInverses.push((new Ae).fromArray(t.boneInverses[n]))}return this.init(),this}toJSON(){const t={metadata:{version:4.5,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};t.uuid=this.uuid;const e=this.bones,n=this.boneInverses;for(let i=0,r=e.length;i<r;i++){const r=e[i];t.bones.push(r.uuid);const s=n[i];t.boneInverses.push(s.toArray())}return t}}class Wa extends gn{constructor(t,e,n,i=1){"number"==typeof n&&(i=n,n=!1,console.error("THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.")),super(t,e,n),this.meshPerAttribute=i}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}toJSON(){const t=super.toJSON();return t.meshPerAttribute=this.meshPerAttribute,t.isInstancedBufferAttribute=!0,t}}Wa.prototype.isInstancedBufferAttribute=!0;const ja=new Ae,qa=new Ae,Xa=[],Ja=new Qn;class Ya extends Qn{constructor(t,e,n){super(t,e),this.instanceMatrix=new Wa(new Float32Array(16*n),16),this.instanceColor=null,this.count=n,this.frustumCulled=!1}copy(t){return super.copy(t),this.instanceMatrix.copy(t.instanceMatrix),null!==t.instanceColor&&(this.instanceColor=t.instanceColor.clone()),this.count=t.count,this}getColorAt(t,e){e.fromArray(this.instanceColor.array,3*t)}getMatrixAt(t,e){e.fromArray(this.instanceMatrix.array,16*t)}raycast(t,e){const n=this.matrixWorld,i=this.count;if(Ja.geometry=this.geometry,Ja.material=this.material,void 0!==Ja.material)for(let r=0;r<i;r++){this.getMatrixAt(r,ja),qa.multiplyMatrices(n,ja),Ja.matrixWorld=qa,Ja.raycast(t,Xa);for(let t=0,n=Xa.length;t<n;t++){const n=Xa[t];n.instanceId=r,n.object=this,e.push(n)}Xa.length=0}}setColorAt(t,e){null===this.instanceColor&&(this.instanceColor=new Wa(new Float32Array(3*this.instanceMatrix.count),3)),e.toArray(this.instanceColor.array,3*t)}setMatrixAt(t,e){e.toArray(this.instanceMatrix.array,16*t)}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"})}}Ya.prototype.isInstancedMesh=!0;class Za extends dn{constructor(t){super(),this.type="LineBasicMaterial",this.color=new Ut(16777215),this.linewidth=1,this.linecap="round",this.linejoin="round",this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.linewidth=t.linewidth,this.linecap=t.linecap,this.linejoin=t.linejoin,this}}Za.prototype.isLineBasicMaterial=!0;const Ka=new Zt,Qa=new Zt,$a=new Ae,to=new Ee,eo=new ye;class no extends Qe{constructor(t=new Nn,e=new Za){super(),this.type="Line",this.geometry=t,this.material=e,this.updateMorphTargets()}copy(t){return super.copy(t),this.material=t.material,this.geometry=t.geometry,this}computeLineDistances(){const t=this.geometry;if(t.isBufferGeometry)if(null===t.index){const e=t.attributes.position,n=[0];for(let t=1,i=e.count;t<i;t++)Ka.fromBufferAttribute(e,t-1),Qa.fromBufferAttribute(e,t),n[t]=n[t-1],n[t]+=Ka.distanceTo(Qa);t.setAttribute("lineDistance",new Tn(n,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");else t.isGeometry&&console.error("THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.");return this}raycast(t,e){const n=this.geometry,i=this.matrixWorld,r=t.params.Line.threshold,s=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),eo.copy(n.boundingSphere),eo.applyMatrix4(i),eo.radius+=r,!1===t.ray.intersectsSphere(eo))return;$a.copy(i).invert(),to.copy(t.ray).applyMatrix4($a);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=new Zt,c=new Zt,h=new Zt,u=new Zt,d=this.isLineSegments?2:1;if(n.isBufferGeometry){const i=n.index,r=n.attributes.position;if(null!==i){for(let n=Math.max(0,s.start),a=Math.min(i.count,s.start+s.count)-1;n<a;n+=d){const s=i.getX(n),a=i.getX(n+1);l.fromBufferAttribute(r,s),c.fromBufferAttribute(r,a);if(to.distanceSqToSegment(l,c,u,h)>o)continue;u.applyMatrix4(this.matrixWorld);const d=t.ray.origin.distanceTo(u);d<t.near||d>t.far||e.push({distance:d,point:h.clone().applyMatrix4(this.matrixWorld),index:n,face:null,faceIndex:null,object:this})}}else{for(let n=Math.max(0,s.start),i=Math.min(r.count,s.start+s.count)-1;n<i;n+=d){l.fromBufferAttribute(r,n),c.fromBufferAttribute(r,n+1);if(to.distanceSqToSegment(l,c,u,h)>o)continue;u.applyMatrix4(this.matrixWorld);const i=t.ray.origin.distanceTo(u);i<t.near||i>t.far||e.push({distance:i,point:h.clone().applyMatrix4(this.matrixWorld),index:n,face:null,faceIndex:null,object:this})}}}else n.isGeometry&&console.error("THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}updateMorphTargets(){const t=this.geometry;if(t.isBufferGeometry){const e=t.morphAttributes,n=Object.keys(e);if(n.length>0){const t=e[n[0]];if(void 0!==t){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,n=t.length;e<n;e++){const n=t[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[n]=e}}}}else{const e=t.morphTargets;void 0!==e&&e.length>0&&console.error("THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.")}}}no.prototype.isLine=!0;const io=new Zt,ro=new Zt;class so extends no{constructor(t,e){super(t,e),this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(t.isBufferGeometry)if(null===t.index){const e=t.attributes.position,n=[];for(let t=0,i=e.count;t<i;t+=2)io.fromBufferAttribute(e,t),ro.fromBufferAttribute(e,t+1),n[t]=0===t?0:n[t-1],n[t+1]=n[t]+io.distanceTo(ro);t.setAttribute("lineDistance",new Tn(n,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");else t.isGeometry&&console.error("THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.");return this}}so.prototype.isLineSegments=!0;class ao extends no{constructor(t,e){super(t,e),this.type="LineLoop"}}ao.prototype.isLineLoop=!0;class oo extends dn{constructor(t){super(),this.type="PointsMaterial",this.color=new Ut(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this}}oo.prototype.isPointsMaterial=!0;const lo=new Ae,co=new Ee,ho=new ye,uo=new Zt;class po extends Qe{constructor(t=new Nn,e=new oo){super(),this.type="Points",this.geometry=t,this.material=e,this.updateMorphTargets()}copy(t){return super.copy(t),this.material=t.material,this.geometry=t.geometry,this}raycast(t,e){const n=this.geometry,i=this.matrixWorld,r=t.params.Points.threshold,s=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),ho.copy(n.boundingSphere),ho.applyMatrix4(i),ho.radius+=r,!1===t.ray.intersectsSphere(ho))return;lo.copy(i).invert(),co.copy(t.ray).applyMatrix4(lo);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a;if(n.isBufferGeometry){const r=n.index,a=n.attributes.position;if(null!==r){for(let n=Math.max(0,s.start),l=Math.min(r.count,s.start+s.count);n<l;n++){const s=r.getX(n);uo.fromBufferAttribute(a,s),mo(uo,s,o,i,t,e,this)}}else{for(let n=Math.max(0,s.start),r=Math.min(a.count,s.start+s.count);n<r;n++)uo.fromBufferAttribute(a,n),mo(uo,n,o,i,t,e,this)}}else console.error("THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}updateMorphTargets(){const t=this.geometry;if(t.isBufferGeometry){const e=t.morphAttributes,n=Object.keys(e);if(n.length>0){const t=e[n[0]];if(void 0!==t){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,n=t.length;e<n;e++){const n=t[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[n]=e}}}}else{const e=t.morphTargets;void 0!==e&&e.length>0&&console.error("THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.")}}}function mo(t,e,n,i,r,s,a){const o=co.distanceSqToPoint(t);if(o<n){const n=new Zt;co.closestPointToPoint(t,n),n.applyMatrix4(i);const l=r.ray.origin.distanceTo(n);if(l<r.near||l>r.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:n,index:e,face:null,object:a})}}po.prototype.isPoints=!0;class fo extends Vt{constructor(t,e,n,i,r,s,a,o,l){super(t,e,n,i,r,s,a,o,l),this.minFilter=void 0!==s?s:g,this.magFilter=void 0!==r?r:g,this.generateMipmaps=!1;const c=this;"requestVideoFrameCallback"in t&&t.requestVideoFrameCallback((function e(){c.needsUpdate=!0,t.requestVideoFrameCallback(e)}))}clone(){return new this.constructor(this.image).copy(this)}update(){const t=this.image;!1==="requestVideoFrameCallback"in t&&t.readyState>=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}fo.prototype.isVideoTexture=!0;class go extends Vt{constructor(t,e,n){super({width:t,height:e}),this.format=n,this.magFilter=p,this.minFilter=p,this.generateMipmaps=!1,this.needsUpdate=!0}}go.prototype.isFramebufferTexture=!0;class vo extends Vt{constructor(t,e,n,i,r,s,a,o,l,c,h,u){super(null,s,a,o,l,c,i,r,h,u),this.image={width:e,height:n},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}}vo.prototype.isCompressedTexture=!0;class yo extends Vt{constructor(t,e,n,i,r,s,a,o,l){super(t,e,n,i,r,s,a,o,l),this.needsUpdate=!0}}yo.prototype.isCanvasTexture=!0;class xo extends Nn{constructor(t=1,e=8,n=0,i=2*Math.PI){super(),this.type="CircleGeometry",this.parameters={radius:t,segments:e,thetaStart:n,thetaLength:i},e=Math.max(3,e);const r=[],s=[],a=[],o=[],l=new Zt,c=new At;s.push(0,0,0),a.push(0,0,1),o.push(.5,.5);for(let r=0,h=3;r<=e;r++,h+=3){const u=n+r/e*i;l.x=t*Math.cos(u),l.y=t*Math.sin(u),s.push(l.x,l.y,l.z),a.push(0,0,1),c.x=(s[h]/t+1)/2,c.y=(s[h+1]/t+1)/2,o.push(c.x,c.y)}for(let t=1;t<=e;t++)r.push(t,t+1,0);this.setIndex(r),this.setAttribute("position",new Tn(s,3)),this.setAttribute("normal",new Tn(a,3)),this.setAttribute("uv",new Tn(o,2))}static fromJSON(t){return new xo(t.radius,t.segments,t.thetaStart,t.thetaLength)}}class _o extends Nn{constructor(t=1,e=1,n=1,i=8,r=1,s=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:t,radiusBottom:e,height:n,radialSegments:i,heightSegments:r,openEnded:s,thetaStart:a,thetaLength:o};const l=this;i=Math.floor(i),r=Math.floor(r);const c=[],h=[],u=[],d=[];let p=0;const m=[],f=n/2;let g=0;function v(n){const r=p,s=new At,m=new Zt;let v=0;const y=!0===n?t:e,x=!0===n?1:-1;for(let t=1;t<=i;t++)h.push(0,f*x,0),u.push(0,x,0),d.push(.5,.5),p++;const _=p;for(let t=0;t<=i;t++){const e=t/i*o+a,n=Math.cos(e),r=Math.sin(e);m.x=y*r,m.y=f*x,m.z=y*n,h.push(m.x,m.y,m.z),u.push(0,x,0),s.x=.5*n+.5,s.y=.5*r*x+.5,d.push(s.x,s.y),p++}for(let t=0;t<i;t++){const e=r+t,i=_+t;!0===n?c.push(i,i+1,e):c.push(i+1,i,e),v+=3}l.addGroup(g,v,!0===n?1:2),g+=v}!function(){const s=new Zt,v=new Zt;let y=0;const x=(e-t)/n;for(let l=0;l<=r;l++){const c=[],g=l/r,y=g*(e-t)+t;for(let t=0;t<=i;t++){const e=t/i,r=e*o+a,l=Math.sin(r),m=Math.cos(r);v.x=y*l,v.y=-g*n+f,v.z=y*m,h.push(v.x,v.y,v.z),s.set(l,x,m).normalize(),u.push(s.x,s.y,s.z),d.push(e,1-g),c.push(p++)}m.push(c)}for(let t=0;t<i;t++)for(let e=0;e<r;e++){const n=m[e][t],i=m[e+1][t],r=m[e+1][t+1],s=m[e][t+1];c.push(n,i,s),c.push(i,r,s),y+=6}l.addGroup(g,y,0),g+=y}(),!1===s&&(t>0&&v(!0),e>0&&v(!1)),this.setIndex(c),this.setAttribute("position",new Tn(h,3)),this.setAttribute("normal",new Tn(u,3)),this.setAttribute("uv",new Tn(d,2))}static fromJSON(t){return new _o(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class Mo extends _o{constructor(t=1,e=1,n=8,i=1,r=!1,s=0,a=2*Math.PI){super(0,t,e,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(t){return new Mo(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class bo extends Nn{constructor(t=[],e=[],n=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:e,radius:n,detail:i};const r=[],s=[];function a(t,e,n,i){const r=i+1,s=[];for(let i=0;i<=r;i++){s[i]=[];const a=t.clone().lerp(n,i/r),o=e.clone().lerp(n,i/r),l=r-i;for(let t=0;t<=l;t++)s[i][t]=0===t&&i===r?a:a.clone().lerp(o,t/l)}for(let t=0;t<r;t++)for(let e=0;e<2*(r-t)-1;e++){const n=Math.floor(e/2);e%2==0?(o(s[t][n+1]),o(s[t+1][n]),o(s[t][n])):(o(s[t][n+1]),o(s[t+1][n+1]),o(s[t+1][n]))}}function o(t){r.push(t.x,t.y,t.z)}function l(e,n){const i=3*e;n.x=t[i+0],n.y=t[i+1],n.z=t[i+2]}function c(t,e,n,i){i<0&&1===t.x&&(s[e]=t.x-1),0===n.x&&0===n.z&&(s[e]=i/2/Math.PI+.5)}function h(t){return Math.atan2(t.z,-t.x)}!function(t){const n=new Zt,i=new Zt,r=new Zt;for(let s=0;s<e.length;s+=3)l(e[s+0],n),l(e[s+1],i),l(e[s+2],r),a(n,i,r,t)}(i),function(t){const e=new Zt;for(let n=0;n<r.length;n+=3)e.x=r[n+0],e.y=r[n+1],e.z=r[n+2],e.normalize().multiplyScalar(t),r[n+0]=e.x,r[n+1]=e.y,r[n+2]=e.z}(n),function(){const t=new Zt;for(let n=0;n<r.length;n+=3){t.x=r[n+0],t.y=r[n+1],t.z=r[n+2];const i=h(t)/2/Math.PI+.5,a=(e=t,Math.atan2(-e.y,Math.sqrt(e.x*e.x+e.z*e.z))/Math.PI+.5);s.push(i,1-a)}var e;(function(){const t=new Zt,e=new Zt,n=new Zt,i=new Zt,a=new At,o=new At,l=new At;for(let u=0,d=0;u<r.length;u+=9,d+=6){t.set(r[u+0],r[u+1],r[u+2]),e.set(r[u+3],r[u+4],r[u+5]),n.set(r[u+6],r[u+7],r[u+8]),a.set(s[d+0],s[d+1]),o.set(s[d+2],s[d+3]),l.set(s[d+4],s[d+5]),i.copy(t).add(e).add(n).divideScalar(3);const p=h(i);c(a,d+0,t,p),c(o,d+2,e,p),c(l,d+4,n,p)}})(),function(){for(let t=0;t<s.length;t+=6){const e=s[t+0],n=s[t+2],i=s[t+4],r=Math.max(e,n,i),a=Math.min(e,n,i);r>.9&&a<.1&&(e<.2&&(s[t+0]+=1),n<.2&&(s[t+2]+=1),i<.2&&(s[t+4]+=1))}}()}(),this.setAttribute("position",new Tn(r,3)),this.setAttribute("normal",new Tn(r.slice(),3)),this.setAttribute("uv",new Tn(s,2)),0===i?this.computeVertexNormals():this.normalizeNormals()}static fromJSON(t){return new bo(t.vertices,t.indices,t.radius,t.details)}}class wo extends bo{constructor(t=1,e=0){const n=(1+Math.sqrt(5))/2,i=1/n;super([-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,-i,-n,0,-i,n,0,i,-n,0,i,n,-i,-n,0,-i,n,0,i,-n,0,i,n,0,-n,0,-i,n,0,-i,-n,0,i,n,0,i],[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],t,e),this.type="DodecahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new wo(t.radius,t.detail)}}const So=new Zt,To=new Zt,Eo=new Zt,Ao=new hn;class Ro extends Nn{constructor(t=null,e=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:t,thresholdAngle:e},null!==t){const n=4,i=Math.pow(10,n),r=Math.cos(vt*e),s=t.getIndex(),a=t.getAttribute("position"),o=s?s.count:a.count,l=[0,0,0],c=["a","b","c"],h=new Array(3),u={},d=[];for(let t=0;t<o;t+=3){s?(l[0]=s.getX(t),l[1]=s.getX(t+1),l[2]=s.getX(t+2)):(l[0]=t,l[1]=t+1,l[2]=t+2);const{a:e,b:n,c:o}=Ao;if(e.fromBufferAttribute(a,l[0]),n.fromBufferAttribute(a,l[1]),o.fromBufferAttribute(a,l[2]),Ao.getNormal(Eo),h[0]=`${Math.round(e.x*i)},${Math.round(e.y*i)},${Math.round(e.z*i)}`,h[1]=`${Math.round(n.x*i)},${Math.round(n.y*i)},${Math.round(n.z*i)}`,h[2]=`${Math.round(o.x*i)},${Math.round(o.y*i)},${Math.round(o.z*i)}`,h[0]!==h[1]&&h[1]!==h[2]&&h[2]!==h[0])for(let t=0;t<3;t++){const e=(t+1)%3,n=h[t],i=h[e],s=Ao[c[t]],a=Ao[c[e]],o=`${n}_${i}`,p=`${i}_${n}`;p in u&&u[p]?(Eo.dot(u[p].normal)<=r&&(d.push(s.x,s.y,s.z),d.push(a.x,a.y,a.z)),u[p]=null):o in u||(u[o]={index0:l[t],index1:l[e],normal:Eo.clone()})}}for(const t in u)if(u[t]){const{index0:e,index1:n}=u[t];So.fromBufferAttribute(a,e),To.fromBufferAttribute(a,n),d.push(So.x,So.y,So.z),d.push(To.x,To.y,To.z)}this.setAttribute("position",new Tn(d,3))}}}class Lo{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(t,e){const n=this.getUtoTmapping(t);return this.getPoint(n,e)}getPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPoint(n/t));return e}getSpacedPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPointAt(n/t));return e}getLength(){const t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const e=[];let n,i=this.getPoint(0),r=0;e.push(0);for(let s=1;s<=t;s++)n=this.getPoint(s/t),r+=n.distanceTo(i),e.push(r),i=n;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e){const n=this.getLengths();let i=0;const r=n.length;let s;s=e||t*n[r-1];let a,o=0,l=r-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),a=n[i]-s,a<0)o=i+1;else{if(!(a>0)){l=i;break}l=i-1}if(i=l,n[i]===s)return i/(r-1);const c=n[i];return(i+(s-c)/(n[i+1]-c))/(r-1)}getTangent(t,e){const n=1e-4;let i=t-n,r=t+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=e||(s.isVector2?new At:new Zt);return o.copy(a).sub(s).normalize(),o}getTangentAt(t,e){const n=this.getUtoTmapping(t);return this.getTangent(n,e)}computeFrenetFrames(t,e){const n=new Zt,i=[],r=[],s=[],a=new Zt,o=new Ae;for(let e=0;e<=t;e++){const n=e/t;i[e]=this.getTangentAt(n,new Zt)}r[0]=new Zt,s[0]=new Zt;let l=Number.MAX_VALUE;const c=Math.abs(i[0].x),h=Math.abs(i[0].y),u=Math.abs(i[0].z);c<=l&&(l=c,n.set(1,0,0)),h<=l&&(l=h,n.set(0,1,0)),u<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),s[0].crossVectors(i[0],r[0]);for(let e=1;e<=t;e++){if(r[e]=r[e-1].clone(),s[e]=s[e-1].clone(),a.crossVectors(i[e-1],i[e]),a.length()>Number.EPSILON){a.normalize();const t=Math.acos(_t(i[e-1].dot(i[e]),-1,1));r[e].applyMatrix4(o.makeRotationAxis(a,t))}s[e].crossVectors(i[e],r[e])}if(!0===e){let e=Math.acos(_t(r[0].dot(r[t]),-1,1));e/=t,i[0].dot(a.crossVectors(r[0],r[t]))>0&&(e=-e);for(let n=1;n<=t;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],e*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.5,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class Co extends Lo{constructor(t=0,e=0,n=1,i=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(t,e){const n=e||new At,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)<Number.EPSILON;for(;r<0;)r+=i;for(;r>i;)r-=i;r<Number.EPSILON&&(r=s?0:i),!0!==this.aClockwise||s||(r===i?r=-i:r-=i);const a=this.aStartAngle+t*r;let o=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(0!==this.aRotation){const t=Math.cos(this.aRotation),e=Math.sin(this.aRotation),n=o-this.aX,i=l-this.aY;o=n*t-i*e+this.aX,l=n*e+i*t+this.aY}return n.set(o,l)}copy(t){return super.copy(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}toJSON(){const t=super.toJSON();return t.aX=this.aX,t.aY=this.aY,t.xRadius=this.xRadius,t.yRadius=this.yRadius,t.aStartAngle=this.aStartAngle,t.aEndAngle=this.aEndAngle,t.aClockwise=this.aClockwise,t.aRotation=this.aRotation,t}fromJSON(t){return super.fromJSON(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}}Co.prototype.isEllipseCurve=!0;class Po extends Co{constructor(t,e,n,i,r,s){super(t,e,n,n,i,r,s),this.type="ArcCurve"}}function Do(){let t=0,e=0,n=0,i=0;function r(r,s,a,o){t=r,e=a,n=-3*r+3*s-2*a-o,i=2*r-2*s+a+o}return{initCatmullRom:function(t,e,n,i,s){r(e,n,s*(n-t),s*(i-e))},initNonuniformCatmullRom:function(t,e,n,i,s,a,o){let l=(e-t)/s-(n-t)/(s+a)+(n-e)/a,c=(n-e)/a-(i-e)/(a+o)+(i-n)/o;l*=a,c*=a,r(e,n,l,c)},calc:function(r){const s=r*r;return t+e*r+n*s+i*(s*r)}}}Po.prototype.isArcCurve=!0;const Io=new Zt,No=new Do,Bo=new Do,zo=new Do;class Oo extends Lo{constructor(t=[],e=!1,n="centripetal",i=.5){super(),this.type="CatmullRomCurve3",this.points=t,this.closed=e,this.curveType=n,this.tension=i}getPoint(t,e=new Zt){const n=e,i=this.points,r=i.length,s=(r-(this.closed?0:1))*t;let a,o,l=Math.floor(s),c=s-l;this.closed?l+=l>0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===c&&l===r-1&&(l=r-2,c=1),this.closed||l>0?a=i[(l-1)%r]:(Io.subVectors(i[0],i[1]).add(i[0]),a=Io);const h=i[l%r],u=i[(l+1)%r];if(this.closed||l+2<r?o=i[(l+2)%r]:(Io.subVectors(i[r-1],i[r-2]).add(i[r-1]),o=Io),"centripetal"===this.curveType||"chordal"===this.curveType){const t="chordal"===this.curveType?.5:.25;let e=Math.pow(a.distanceToSquared(h),t),n=Math.pow(h.distanceToSquared(u),t),i=Math.pow(u.distanceToSquared(o),t);n<1e-4&&(n=1),e<1e-4&&(e=n),i<1e-4&&(i=n),No.initNonuniformCatmullRom(a.x,h.x,u.x,o.x,e,n,i),Bo.initNonuniformCatmullRom(a.y,h.y,u.y,o.y,e,n,i),zo.initNonuniformCatmullRom(a.z,h.z,u.z,o.z,e,n,i)}else"catmullrom"===this.curveType&&(No.initCatmullRom(a.x,h.x,u.x,o.x,this.tension),Bo.initCatmullRom(a.y,h.y,u.y,o.y,this.tension),zo.initCatmullRom(a.z,h.z,u.z,o.z,this.tension));return n.set(No.calc(c),Bo.calc(c),zo.calc(c)),n}copy(t){super.copy(t),this.points=[];for(let e=0,n=t.points.length;e<n;e++){const n=t.points[e];this.points.push(n.clone())}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,n=this.points.length;e<n;e++){const n=this.points[e];t.points.push(n.toArray())}return t.closed=this.closed,t.curveType=this.curveType,t.tension=this.tension,t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,n=t.points.length;e<n;e++){const n=t.points[e];this.points.push((new Zt).fromArray(n))}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}}function Fo(t,e,n,i,r){const s=.5*(i-e),a=.5*(r-n),o=t*t;return(2*n-2*i+s+a)*(t*o)+(-3*n+3*i-2*s-a)*o+s*t+n}function Uo(t,e,n,i){return function(t,e){const n=1-t;return n*n*e}(t,e)+function(t,e){return 2*(1-t)*t*e}(t,n)+function(t,e){return t*t*e}(t,i)}function Ho(t,e,n,i,r){return function(t,e){const n=1-t;return n*n*n*e}(t,e)+function(t,e){const n=1-t;return 3*n*n*t*e}(t,n)+function(t,e){return 3*(1-t)*t*t*e}(t,i)+function(t,e){return t*t*t*e}(t,r)}Oo.prototype.isCatmullRomCurve3=!0;class Go extends Lo{constructor(t=new At,e=new At,n=new At,i=new At){super(),this.type="CubicBezierCurve",this.v0=t,this.v1=e,this.v2=n,this.v3=i}getPoint(t,e=new At){const n=e,i=this.v0,r=this.v1,s=this.v2,a=this.v3;return n.set(Ho(t,i.x,r.x,s.x,a.x),Ho(t,i.y,r.y,s.y,a.y)),n}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}Go.prototype.isCubicBezierCurve=!0;class ko extends Lo{constructor(t=new Zt,e=new Zt,n=new Zt,i=new Zt){super(),this.type="CubicBezierCurve3",this.v0=t,this.v1=e,this.v2=n,this.v3=i}getPoint(t,e=new Zt){const n=e,i=this.v0,r=this.v1,s=this.v2,a=this.v3;return n.set(Ho(t,i.x,r.x,s.x,a.x),Ho(t,i.y,r.y,s.y,a.y),Ho(t,i.z,r.z,s.z,a.z)),n}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}ko.prototype.isCubicBezierCurve3=!0;class Vo extends Lo{constructor(t=new At,e=new At){super(),this.type="LineCurve",this.v1=t,this.v2=e}getPoint(t,e=new At){const n=e;return 1===t?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(t).add(this.v1)),n}getPointAt(t,e){return this.getPoint(t,e)}getTangent(t,e){const n=e||new At;return n.copy(this.v2).sub(this.v1).normalize(),n}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}Vo.prototype.isLineCurve=!0;class Wo extends Lo{constructor(t=new Zt,e=new Zt){super(),this.type="LineCurve3",this.isLineCurve3=!0,this.v1=t,this.v2=e}getPoint(t,e=new Zt){const n=e;return 1===t?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(t).add(this.v1)),n}getPointAt(t,e){return this.getPoint(t,e)}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class jo extends Lo{constructor(t=new At,e=new At,n=new At){super(),this.type="QuadraticBezierCurve",this.v0=t,this.v1=e,this.v2=n}getPoint(t,e=new At){const n=e,i=this.v0,r=this.v1,s=this.v2;return n.set(Uo(t,i.x,r.x,s.x),Uo(t,i.y,r.y,s.y)),n}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}jo.prototype.isQuadraticBezierCurve=!0;class qo extends Lo{constructor(t=new Zt,e=new Zt,n=new Zt){super(),this.type="QuadraticBezierCurve3",this.v0=t,this.v1=e,this.v2=n}getPoint(t,e=new Zt){const n=e,i=this.v0,r=this.v1,s=this.v2;return n.set(Uo(t,i.x,r.x,s.x),Uo(t,i.y,r.y,s.y),Uo(t,i.z,r.z,s.z)),n}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}qo.prototype.isQuadraticBezierCurve3=!0;class Xo extends Lo{constructor(t=[]){super(),this.type="SplineCurve",this.points=t}getPoint(t,e=new At){const n=e,i=this.points,r=(i.length-1)*t,s=Math.floor(r),a=r-s,o=i[0===s?s:s-1],l=i[s],c=i[s>i.length-2?i.length-1:s+1],h=i[s>i.length-3?i.length-1:s+2];return n.set(Fo(a,o.x,l.x,c.x,h.x),Fo(a,o.y,l.y,c.y,h.y)),n}copy(t){super.copy(t),this.points=[];for(let e=0,n=t.points.length;e<n;e++){const n=t.points[e];this.points.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,n=this.points.length;e<n;e++){const n=this.points[e];t.points.push(n.toArray())}return t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,n=t.points.length;e<n;e++){const n=t.points[e];this.points.push((new At).fromArray(n))}return this}}Xo.prototype.isSplineCurve=!0;var Jo=Object.freeze({__proto__:null,ArcCurve:Po,CatmullRomCurve3:Oo,CubicBezierCurve:Go,CubicBezierCurve3:ko,EllipseCurve:Co,LineCurve:Vo,LineCurve3:Wo,QuadraticBezierCurve:jo,QuadraticBezierCurve3:qo,SplineCurve:Xo});class Yo extends Lo{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(t){this.curves.push(t)}closePath(){const t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);t.equals(e)||this.curves.push(new Vo(e,t))}getPoint(t,e){const n=t*this.getLength(),i=this.getCurveLengths();let r=0;for(;r<i.length;){if(i[r]>=n){const t=i[r]-n,s=this.curves[r],a=s.getLength(),o=0===a?0:1-t/a;return s.getPointAt(o,e)}r++}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;n<i;n++)e+=this.curves[n].getLength(),t.push(e);return this.cacheLengths=t,t}getSpacedPoints(t=40){const e=[];for(let n=0;n<=t;n++)e.push(this.getPoint(n/t));return this.autoClose&&e.push(e[0]),e}getPoints(t=12){const e=[];let n;for(let i=0,r=this.curves;i<r.length;i++){const s=r[i],a=s&&s.isEllipseCurve?2*t:s&&(s.isLineCurve||s.isLineCurve3)?1:s&&s.isSplineCurve?t*s.points.length:t,o=s.getPoints(a);for(let t=0;t<o.length;t++){const i=o[t];n&&n.equals(i)||(e.push(i),n=i)}}return this.autoClose&&e.length>1&&!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;e<n;e++){const n=t.curves[e];this.curves.push(n.clone())}return this.autoClose=t.autoClose,this}toJSON(){const t=super.toJSON();t.autoClose=this.autoClose,t.curves=[];for(let e=0,n=this.curves.length;e<n;e++){const n=this.curves[e];t.curves.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.autoClose=t.autoClose,this.curves=[];for(let e=0,n=t.curves.length;e<n;e++){const n=t.curves[e];this.curves.push((new Jo[n.type]).fromJSON(n))}return this}}class Zo extends Yo{constructor(t){super(),this.type="Path",this.currentPoint=new At,t&&this.setFromPoints(t)}setFromPoints(t){this.moveTo(t[0].x,t[0].y);for(let e=1,n=t.length;e<n;e++)this.lineTo(t[e].x,t[e].y);return this}moveTo(t,e){return this.currentPoint.set(t,e),this}lineTo(t,e){const n=new Vo(this.currentPoint.clone(),new At(t,e));return this.curves.push(n),this.currentPoint.set(t,e),this}quadraticCurveTo(t,e,n,i){const r=new jo(this.currentPoint.clone(),new At(t,e),new At(n,i));return this.curves.push(r),this.currentPoint.set(n,i),this}bezierCurveTo(t,e,n,i,r,s){const a=new Go(this.currentPoint.clone(),new At(t,e),new At(n,i),new At(r,s));return this.curves.push(a),this.currentPoint.set(r,s),this}splineThru(t){const e=[this.currentPoint.clone()].concat(t),n=new Xo(e);return this.curves.push(n),this.currentPoint.copy(t[t.length-1]),this}arc(t,e,n,i,r,s){const a=this.currentPoint.x,o=this.currentPoint.y;return this.absarc(t+a,e+o,n,i,r,s),this}absarc(t,e,n,i,r,s){return this.absellipse(t,e,n,n,i,r,s),this}ellipse(t,e,n,i,r,s,a,o){const l=this.currentPoint.x,c=this.currentPoint.y;return this.absellipse(t+l,e+c,n,i,r,s,a,o),this}absellipse(t,e,n,i,r,s,a,o){const l=new Co(t,e,n,i,r,s,a,o);if(this.curves.length>0){const t=l.getPoint(0);t.equals(this.currentPoint)||this.lineTo(t.x,t.y)}this.curves.push(l);const c=l.getPoint(1);return this.currentPoint.copy(c),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 Ko extends Zo{constructor(t){super(t),this.uuid=xt(),this.type="Shape",this.holes=[]}getPointsHoles(t){const e=[];for(let n=0,i=this.holes.length;n<i;n++)e[n]=this.holes[n].getPoints(t);return e}extractPoints(t){return{shape:this.getPoints(t),holes:this.getPointsHoles(t)}}copy(t){super.copy(t),this.holes=[];for(let e=0,n=t.holes.length;e<n;e++){const n=t.holes[e];this.holes.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.uuid=this.uuid,t.holes=[];for(let e=0,n=this.holes.length;e<n;e++){const n=this.holes[e];t.holes.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.uuid=t.uuid,this.holes=[];for(let e=0,n=t.holes.length;e<n;e++){const n=t.holes[e];this.holes.push((new Zo).fromJSON(n))}return this}}const Qo=function(t,e,n=2){const i=e&&e.length,r=i?e[0]*n:t.length;let s=$o(t,0,r,n,!0);const a=[];if(!s||s.next===s.prev)return a;let o,l,c,h,u,d,p;if(i&&(s=function(t,e,n,i){const r=[];let s,a,o,l,c;for(s=0,a=e.length;s<a;s++)o=e[s]*i,l=s<a-1?e[s+1]*i:t.length,c=$o(t,o,l,i,!1),c===c.next&&(c.steiner=!0),r.push(hl(c));for(r.sort(al),s=0;s<r.length;s++)ol(r[s],n),n=tl(n,n.next);return n}(t,e,s,n)),t.length>80*n){o=c=t[0],l=h=t[1];for(let e=n;e<r;e+=n)u=t[e],d=t[e+1],u<o&&(o=u),d<l&&(l=d),u>c&&(c=u),d>h&&(h=d);p=Math.max(c-o,h-l),p=0!==p?1/p:0}return el(s,a,n,o,l,p),a};function $o(t,e,n,i,r){let s,a;if(r===function(t,e,n,i){let r=0;for(let s=e,a=n-i;s<n;s+=i)r+=(t[a]-t[s])*(t[s+1]+t[a+1]),a=s;return r}(t,e,n,i)>0)for(s=e;s<n;s+=i)a=_l(s,t[s],t[s+1],a);else for(s=n-i;s>=e;s-=i)a=_l(s,t[s],t[s+1],a);return a&&ml(a,a.next)&&(Ml(a),a=a.next),a}function tl(t,e){if(!t)return t;e||(e=t);let n,i=t;do{if(n=!1,i.steiner||!ml(i,i.next)&&0!==pl(i.prev,i,i.next))i=i.next;else{if(Ml(i),i=e=i.prev,i===i.next)break;n=!0}}while(n||i!==e);return e}function el(t,e,n,i,r,s,a){if(!t)return;!a&&s&&function(t,e,n,i){let r=t;do{null===r.z&&(r.z=cl(r.x,r.y,e,n,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){let e,n,i,r,s,a,o,l,c=1;do{for(n=t,t=null,s=null,a=0;n;){for(a++,i=n,o=0,e=0;e<c&&(o++,i=i.nextZ,i);e++);for(l=c;o>0||l>0&&i;)0!==o&&(0===l||!i||n.z<=i.z)?(r=n,n=n.nextZ,o--):(r=i,i=i.nextZ,l--),s?s.nextZ=r:t=r,r.prevZ=s,s=r;n=i}s.nextZ=null,c*=2}while(a>1)}(r)}(t,i,r,s);let o,l,c=t;for(;t.prev!==t.next;)if(o=t.prev,l=t.next,s?il(t,i,r,s):nl(t))e.push(o.i/n),e.push(t.i/n),e.push(l.i/n),Ml(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?el(t=rl(tl(t),e,n),e,n,i,r,s,2):2===a&&sl(t,e,n,i,r,s):el(tl(t),e,n,i,r,s,1);break}}function nl(t){const e=t.prev,n=t,i=t.next;if(pl(e,n,i)>=0)return!1;let r=t.next.next;for(;r!==t.prev;){if(ul(e.x,e.y,n.x,n.y,i.x,i.y,r.x,r.y)&&pl(r.prev,r,r.next)>=0)return!1;r=r.next}return!0}function il(t,e,n,i){const r=t.prev,s=t,a=t.next;if(pl(r,s,a)>=0)return!1;const o=r.x<s.x?r.x<a.x?r.x:a.x:s.x<a.x?s.x:a.x,l=r.y<s.y?r.y<a.y?r.y:a.y:s.y<a.y?s.y:a.y,c=r.x>s.x?r.x>a.x?r.x:a.x:s.x>a.x?s.x:a.x,h=r.y>s.y?r.y>a.y?r.y:a.y:s.y>a.y?s.y:a.y,u=cl(o,l,e,n,i),d=cl(c,h,e,n,i);let p=t.prevZ,m=t.nextZ;for(;p&&p.z>=u&&m&&m.z<=d;){if(p!==t.prev&&p!==t.next&&ul(r.x,r.y,s.x,s.y,a.x,a.y,p.x,p.y)&&pl(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,m!==t.prev&&m!==t.next&&ul(r.x,r.y,s.x,s.y,a.x,a.y,m.x,m.y)&&pl(m.prev,m,m.next)>=0)return!1;m=m.nextZ}for(;p&&p.z>=u;){if(p!==t.prev&&p!==t.next&&ul(r.x,r.y,s.x,s.y,a.x,a.y,p.x,p.y)&&pl(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;m&&m.z<=d;){if(m!==t.prev&&m!==t.next&&ul(r.x,r.y,s.x,s.y,a.x,a.y,m.x,m.y)&&pl(m.prev,m,m.next)>=0)return!1;m=m.nextZ}return!0}function rl(t,e,n){let i=t;do{const r=i.prev,s=i.next.next;!ml(r,s)&&fl(r,i,i.next,s)&&yl(r,s)&&yl(s,r)&&(e.push(r.i/n),e.push(i.i/n),e.push(s.i/n),Ml(i),Ml(i.next),i=t=s),i=i.next}while(i!==t);return tl(i)}function sl(t,e,n,i,r,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&dl(a,t)){let o=xl(a,t);return a=tl(a,a.next),o=tl(o,o.next),el(a,e,n,i,r,s),void el(o,e,n,i,r,s)}t=t.next}a=a.next}while(a!==t)}function al(t,e){return t.x-e.x}function ol(t,e){if(e=function(t,e){let n=e;const i=t.x,r=t.y;let s,a=-1/0;do{if(r<=n.y&&r>=n.next.y&&n.next.y!==n.y){const t=n.x+(r-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(t<=i&&t>a){if(a=t,t===i){if(r===n.y)return n;if(r===n.next.y)return n.next}s=n.x<n.next.x?n:n.next}}n=n.next}while(n!==e);if(!s)return null;if(i===a)return s;const o=s,l=s.x,c=s.y;let h,u=1/0;n=s;do{i>=n.x&&n.x>=l&&i!==n.x&&ul(r<c?i:a,r,l,c,r<c?a:i,r,n.x,n.y)&&(h=Math.abs(r-n.y)/(i-n.x),yl(n,t)&&(h<u||h===u&&(n.x>s.x||n.x===s.x&&ll(s,n)))&&(s=n,u=h)),n=n.next}while(n!==o);return s}(t,e),e){const n=xl(e,t);tl(e,e.next),tl(n,n.next)}}function ll(t,e){return pl(t.prev,t,e.prev)<0&&pl(e.next,t,t.next)<0}function cl(t,e,n,i,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-n)*r)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*r)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function hl(t){let e=t,n=t;do{(e.x<n.x||e.x===n.x&&e.y<n.y)&&(n=e),e=e.next}while(e!==t);return n}function ul(t,e,n,i,r,s,a,o){return(r-a)*(e-o)-(t-a)*(s-o)>=0&&(t-a)*(i-o)-(n-a)*(e-o)>=0&&(n-a)*(s-o)-(r-a)*(i-o)>=0}function dl(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&fl(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(yl(t,e)&&yl(e,t)&&function(t,e){let n=t,i=!1;const r=(t.x+e.x)/2,s=(t.y+e.y)/2;do{n.y>s!=n.next.y>s&&n.next.y!==n.y&&r<(n.next.x-n.x)*(s-n.y)/(n.next.y-n.y)+n.x&&(i=!i),n=n.next}while(n!==t);return i}(t,e)&&(pl(t.prev,t,e.prev)||pl(t,e.prev,e))||ml(t,e)&&pl(t.prev,t,t.next)>0&&pl(e.prev,e,e.next)>0)}function pl(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function ml(t,e){return t.x===e.x&&t.y===e.y}function fl(t,e,n,i){const r=vl(pl(t,e,n)),s=vl(pl(t,e,i)),a=vl(pl(n,i,t)),o=vl(pl(n,i,e));return r!==s&&a!==o||(!(0!==r||!gl(t,n,e))||(!(0!==s||!gl(t,i,e))||(!(0!==a||!gl(n,t,i))||!(0!==o||!gl(n,e,i)))))}function gl(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function vl(t){return t>0?1:t<0?-1:0}function yl(t,e){return pl(t.prev,t,t.next)<0?pl(t,e,t.next)>=0&&pl(t,t.prev,e)>=0:pl(t,e,t.prev)<0||pl(t,t.next,e)<0}function xl(t,e){const n=new bl(t.i,t.x,t.y),i=new bl(e.i,e.x,e.y),r=t.next,s=e.prev;return t.next=e,e.prev=t,n.next=r,r.prev=n,i.next=n,n.prev=i,s.next=i,i.prev=s,i}function _l(t,e,n,i){const r=new bl(t,e,n);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function Ml(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function bl(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}class wl{static area(t){const e=t.length;let n=0;for(let i=e-1,r=0;r<e;i=r++)n+=t[i].x*t[r].y-t[r].x*t[i].y;return.5*n}static isClockWise(t){return wl.area(t)<0}static triangulateShape(t,e){const n=[],i=[],r=[];Sl(t),Tl(n,t);let s=t.length;e.forEach(Sl);for(let t=0;t<e.length;t++)i.push(s),s+=e[t].length,Tl(n,e[t]);const a=Qo(n,i);for(let t=0;t<a.length;t+=3)r.push(a.slice(t,t+3));return r}}function Sl(t){const e=t.length;e>2&&t[e-1].equals(t[0])&&t.pop()}function Tl(t,e){for(let n=0;n<e.length;n++)t.push(e[n].x),t.push(e[n].y)}class El extends Nn{constructor(t=new Ko([new At(.5,.5),new At(-.5,.5),new At(-.5,-.5),new At(.5,-.5)]),e={}){super(),this.type="ExtrudeGeometry",this.parameters={shapes:t,options:e},t=Array.isArray(t)?t:[t];const n=this,i=[],r=[];for(let e=0,n=t.length;e<n;e++){s(t[e])}function s(t){const s=[],a=void 0!==e.curveSegments?e.curveSegments:12,o=void 0!==e.steps?e.steps:1;let l=void 0!==e.depth?e.depth:1,c=void 0===e.bevelEnabled||e.bevelEnabled,h=void 0!==e.bevelThickness?e.bevelThickness:.2,u=void 0!==e.bevelSize?e.bevelSize:h-.1,d=void 0!==e.bevelOffset?e.bevelOffset:0,p=void 0!==e.bevelSegments?e.bevelSegments:3;const m=e.extrudePath,f=void 0!==e.UVGenerator?e.UVGenerator:Al;void 0!==e.amount&&(console.warn("THREE.ExtrudeBufferGeometry: amount has been renamed to depth."),l=e.amount);let g,v,y,x,_,M=!1;m&&(g=m.getSpacedPoints(o),M=!0,c=!1,v=m.computeFrenetFrames(o,!1),y=new Zt,x=new Zt,_=new Zt),c||(p=0,h=0,u=0,d=0);const b=t.extractPoints(a);let w=b.shape;const S=b.holes;if(!wl.isClockWise(w)){w=w.reverse();for(let t=0,e=S.length;t<e;t++){const e=S[t];wl.isClockWise(e)&&(S[t]=e.reverse())}}const T=wl.triangulateShape(w,S),E=w;for(let t=0,e=S.length;t<e;t++){const e=S[t];w=w.concat(e)}function A(t,e,n){return e||console.error("THREE.ExtrudeGeometry: vec does not exist"),e.clone().multiplyScalar(n).add(t)}const R=w.length,L=T.length;function C(t,e,n){let i,r,s;const a=t.x-e.x,o=t.y-e.y,l=n.x-t.x,c=n.y-t.y,h=a*a+o*o,u=a*c-o*l;if(Math.abs(u)>Number.EPSILON){const u=Math.sqrt(h),d=Math.sqrt(l*l+c*c),p=e.x-o/u,m=e.y+a/u,f=((n.x-c/d-p)*c-(n.y+l/d-m)*l)/(a*c-o*l);i=p+a*f-t.x,r=m+o*f-t.y;const g=i*i+r*r;if(g<=2)return new At(i,r);s=Math.sqrt(g/2)}else{let t=!1;a>Number.EPSILON?l>Number.EPSILON&&(t=!0):a<-Number.EPSILON?l<-Number.EPSILON&&(t=!0):Math.sign(o)===Math.sign(c)&&(t=!0),t?(i=-o,r=a,s=Math.sqrt(h)):(i=a,r=o,s=Math.sqrt(h/2))}return new At(i/s,r/s)}const P=[];for(let t=0,e=E.length,n=e-1,i=t+1;t<e;t++,n++,i++)n===e&&(n=0),i===e&&(i=0),P[t]=C(E[t],E[n],E[i]);const D=[];let I,N=P.concat();for(let t=0,e=S.length;t<e;t++){const e=S[t];I=[];for(let t=0,n=e.length,i=n-1,r=t+1;t<n;t++,i++,r++)i===n&&(i=0),r===n&&(r=0),I[t]=C(e[t],e[i],e[r]);D.push(I),N=N.concat(I)}for(let t=0;t<p;t++){const e=t/p,n=h*Math.cos(e*Math.PI/2),i=u*Math.sin(e*Math.PI/2)+d;for(let t=0,e=E.length;t<e;t++){const e=A(E[t],P[t],i);O(e.x,e.y,-n)}for(let t=0,e=S.length;t<e;t++){const e=S[t];I=D[t];for(let t=0,r=e.length;t<r;t++){const r=A(e[t],I[t],i);O(r.x,r.y,-n)}}}const B=u+d;for(let t=0;t<R;t++){const e=c?A(w[t],N[t],B):w[t];M?(x.copy(v.normals[0]).multiplyScalar(e.x),y.copy(v.binormals[0]).multiplyScalar(e.y),_.copy(g[0]).add(x).add(y),O(_.x,_.y,_.z)):O(e.x,e.y,0)}for(let t=1;t<=o;t++)for(let e=0;e<R;e++){const n=c?A(w[e],N[e],B):w[e];M?(x.copy(v.normals[t]).multiplyScalar(n.x),y.copy(v.binormals[t]).multiplyScalar(n.y),_.copy(g[t]).add(x).add(y),O(_.x,_.y,_.z)):O(n.x,n.y,l/o*t)}for(let t=p-1;t>=0;t--){const e=t/p,n=h*Math.cos(e*Math.PI/2),i=u*Math.sin(e*Math.PI/2)+d;for(let t=0,e=E.length;t<e;t++){const e=A(E[t],P[t],i);O(e.x,e.y,l+n)}for(let t=0,e=S.length;t<e;t++){const e=S[t];I=D[t];for(let t=0,r=e.length;t<r;t++){const r=A(e[t],I[t],i);M?O(r.x,r.y+g[o-1].y,g[o-1].x+n):O(r.x,r.y,l+n)}}}function z(t,e){let n=t.length;for(;--n>=0;){const i=n;let r=n-1;r<0&&(r=t.length-1);for(let t=0,n=o+2*p;t<n;t++){const n=R*t,s=R*(t+1);U(e+i+n,e+r+n,e+r+s,e+i+s)}}}function O(t,e,n){s.push(t),s.push(e),s.push(n)}function F(t,e,r){H(t),H(e),H(r);const s=i.length/3,a=f.generateTopUV(n,i,s-3,s-2,s-1);G(a[0]),G(a[1]),G(a[2])}function U(t,e,r,s){H(t),H(e),H(s),H(e),H(r),H(s);const a=i.length/3,o=f.generateSideWallUV(n,i,a-6,a-3,a-2,a-1);G(o[0]),G(o[1]),G(o[3]),G(o[1]),G(o[2]),G(o[3])}function H(t){i.push(s[3*t+0]),i.push(s[3*t+1]),i.push(s[3*t+2])}function G(t){r.push(t.x),r.push(t.y)}!function(){const t=i.length/3;if(c){let t=0,e=R*t;for(let t=0;t<L;t++){const n=T[t];F(n[2]+e,n[1]+e,n[0]+e)}t=o+2*p,e=R*t;for(let t=0;t<L;t++){const n=T[t];F(n[0]+e,n[1]+e,n[2]+e)}}else{for(let t=0;t<L;t++){const e=T[t];F(e[2],e[1],e[0])}for(let t=0;t<L;t++){const e=T[t];F(e[0]+R*o,e[1]+R*o,e[2]+R*o)}}n.addGroup(t,i.length/3-t,0)}(),function(){const t=i.length/3;let e=0;z(E,e),e+=E.length;for(let t=0,n=S.length;t<n;t++){const n=S[t];z(n,e),e+=n.length}n.addGroup(t,i.length/3-t,1)}()}this.setAttribute("position",new Tn(i,3)),this.setAttribute("uv",new Tn(r,2)),this.computeVertexNormals()}toJSON(){const t=super.toJSON();return function(t,e,n){if(n.shapes=[],Array.isArray(t))for(let e=0,i=t.length;e<i;e++){const i=t[e];n.shapes.push(i.uuid)}else n.shapes.push(t.uuid);void 0!==e.extrudePath&&(n.options.extrudePath=e.extrudePath.toJSON());return n}(this.parameters.shapes,this.parameters.options,t)}static fromJSON(t,e){const n=[];for(let i=0,r=t.shapes.length;i<r;i++){const r=e[t.shapes[i]];n.push(r)}const i=t.options.extrudePath;return void 0!==i&&(t.options.extrudePath=(new Jo[i.type]).fromJSON(i)),new El(n,t.options)}}const Al={generateTopUV:function(t,e,n,i,r){const s=e[3*n],a=e[3*n+1],o=e[3*i],l=e[3*i+1],c=e[3*r],h=e[3*r+1];return[new At(s,a),new At(o,l),new At(c,h)]},generateSideWallUV:function(t,e,n,i,r,s){const a=e[3*n],o=e[3*n+1],l=e[3*n+2],c=e[3*i],h=e[3*i+1],u=e[3*i+2],d=e[3*r],p=e[3*r+1],m=e[3*r+2],f=e[3*s],g=e[3*s+1],v=e[3*s+2];return Math.abs(o-h)<Math.abs(a-c)?[new At(a,1-l),new At(c,1-u),new At(d,1-m),new At(f,1-v)]:[new At(o,1-l),new At(h,1-u),new At(p,1-m),new At(g,1-v)]}};class Rl extends bo{constructor(t=1,e=0){const n=(1+Math.sqrt(5))/2;super([-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],t,e),this.type="IcosahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new Rl(t.radius,t.detail)}}class Ll extends Nn{constructor(t=[new At(0,.5),new At(.5,0),new At(0,-.5)],e=12,n=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:t,segments:e,phiStart:n,phiLength:i},e=Math.floor(e),i=_t(i,0,2*Math.PI);const r=[],s=[],a=[],o=[],l=[],c=1/e,h=new Zt,u=new At,d=new Zt,p=new Zt,m=new Zt;let f=0,g=0;for(let e=0;e<=t.length-1;e++)switch(e){case 0:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,m.copy(d),d.normalize(),o.push(d.x,d.y,d.z);break;case t.length-1:o.push(m.x,m.y,m.z);break;default:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),o.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=e;r++){const d=n+r*c*i,p=Math.sin(d),m=Math.cos(d);for(let n=0;n<=t.length-1;n++){h.x=t[n].x*p,h.y=t[n].y,h.z=t[n].x*m,s.push(h.x,h.y,h.z),u.x=r/e,u.y=n/(t.length-1),a.push(u.x,u.y);const i=o[3*n+0]*p,c=o[3*n+1],d=o[3*n+0]*m;l.push(i,c,d)}}for(let n=0;n<e;n++)for(let e=0;e<t.length-1;e++){const i=e+n*t.length,s=i,a=i+t.length,o=i+t.length+1,l=i+1;r.push(s,a,l),r.push(o,l,a)}this.setIndex(r),this.setAttribute("position",new Tn(s,3)),this.setAttribute("uv",new Tn(a,2)),this.setAttribute("normal",new Tn(l,3))}static fromJSON(t){return new Ll(t.points,t.segments,t.phiStart,t.phiLength)}}class Cl extends bo{constructor(t=1,e=0){super([1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],t,e),this.type="OctahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new Cl(t.radius,t.detail)}}class Pl extends Nn{constructor(t=.5,e=1,n=8,i=1,r=0,s=2*Math.PI){super(),this.type="RingGeometry",this.parameters={innerRadius:t,outerRadius:e,thetaSegments:n,phiSegments:i,thetaStart:r,thetaLength:s},n=Math.max(3,n);const a=[],o=[],l=[],c=[];let h=t;const u=(e-t)/(i=Math.max(1,i)),d=new Zt,p=new At;for(let t=0;t<=i;t++){for(let t=0;t<=n;t++){const i=r+t/n*s;d.x=h*Math.cos(i),d.y=h*Math.sin(i),o.push(d.x,d.y,d.z),l.push(0,0,1),p.x=(d.x/e+1)/2,p.y=(d.y/e+1)/2,c.push(p.x,p.y)}h+=u}for(let t=0;t<i;t++){const e=t*(n+1);for(let t=0;t<n;t++){const i=t+e,r=i,s=i+n+1,o=i+n+2,l=i+1;a.push(r,s,l),a.push(s,o,l)}}this.setIndex(a),this.setAttribute("position",new Tn(o,3)),this.setAttribute("normal",new Tn(l,3)),this.setAttribute("uv",new Tn(c,2))}static fromJSON(t){return new Pl(t.innerRadius,t.outerRadius,t.thetaSegments,t.phiSegments,t.thetaStart,t.thetaLength)}}class Dl extends Nn{constructor(t=new Ko([new At(0,.5),new At(-.5,-.5),new At(.5,-.5)]),e=12){super(),this.type="ShapeGeometry",this.parameters={shapes:t,curveSegments:e};const n=[],i=[],r=[],s=[];let a=0,o=0;if(!1===Array.isArray(t))l(t);else for(let e=0;e<t.length;e++)l(t[e]),this.addGroup(a,o,e),a+=o,o=0;function l(t){const a=i.length/3,l=t.extractPoints(e);let c=l.shape;const h=l.holes;!1===wl.isClockWise(c)&&(c=c.reverse());for(let t=0,e=h.length;t<e;t++){const e=h[t];!0===wl.isClockWise(e)&&(h[t]=e.reverse())}const u=wl.triangulateShape(c,h);for(let t=0,e=h.length;t<e;t++){const e=h[t];c=c.concat(e)}for(let t=0,e=c.length;t<e;t++){const e=c[t];i.push(e.x,e.y,0),r.push(0,0,1),s.push(e.x,e.y)}for(let t=0,e=u.length;t<e;t++){const e=u[t],i=e[0]+a,r=e[1]+a,s=e[2]+a;n.push(i,r,s),o+=3}}this.setIndex(n),this.setAttribute("position",new Tn(i,3)),this.setAttribute("normal",new Tn(r,3)),this.setAttribute("uv",new Tn(s,2))}toJSON(){const t=super.toJSON();return function(t,e){if(e.shapes=[],Array.isArray(t))for(let n=0,i=t.length;n<i;n++){const i=t[n];e.shapes.push(i.uuid)}else e.shapes.push(t.uuid);return e}(this.parameters.shapes,t)}static fromJSON(t,e){const n=[];for(let i=0,r=t.shapes.length;i<r;i++){const r=e[t.shapes[i]];n.push(r)}return new Dl(n,t.curveSegments)}}class Il extends Nn{constructor(t=1,e=32,n=16,i=0,r=2*Math.PI,s=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:n,phiStart:i,phiLength:r,thetaStart:s,thetaLength:a},e=Math.max(3,Math.floor(e)),n=Math.max(2,Math.floor(n));const o=Math.min(s+a,Math.PI);let l=0;const c=[],h=new Zt,u=new Zt,d=[],p=[],m=[],f=[];for(let d=0;d<=n;d++){const g=[],v=d/n;let y=0;0==d&&0==s?y=.5/e:d==n&&o==Math.PI&&(y=-.5/e);for(let n=0;n<=e;n++){const o=n/e;h.x=-t*Math.cos(i+o*r)*Math.sin(s+v*a),h.y=t*Math.cos(s+v*a),h.z=t*Math.sin(i+o*r)*Math.sin(s+v*a),p.push(h.x,h.y,h.z),u.copy(h).normalize(),m.push(u.x,u.y,u.z),f.push(o+y,1-v),g.push(l++)}c.push(g)}for(let t=0;t<n;t++)for(let i=0;i<e;i++){const e=c[t][i+1],r=c[t][i],a=c[t+1][i],l=c[t+1][i+1];(0!==t||s>0)&&d.push(e,r,l),(t!==n-1||o<Math.PI)&&d.push(r,a,l)}this.setIndex(d),this.setAttribute("position",new Tn(p,3)),this.setAttribute("normal",new Tn(m,3)),this.setAttribute("uv",new Tn(f,2))}static fromJSON(t){return new Il(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}}class Nl extends bo{constructor(t=1,e=0){super([1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],t,e),this.type="TetrahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new Nl(t.radius,t.detail)}}class Bl extends Nn{constructor(t=1,e=.4,n=8,i=6,r=2*Math.PI){super(),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:n,tubularSegments:i,arc:r},n=Math.floor(n),i=Math.floor(i);const s=[],a=[],o=[],l=[],c=new Zt,h=new Zt,u=new Zt;for(let s=0;s<=n;s++)for(let d=0;d<=i;d++){const p=d/i*r,m=s/n*Math.PI*2;h.x=(t+e*Math.cos(m))*Math.cos(p),h.y=(t+e*Math.cos(m))*Math.sin(p),h.z=e*Math.sin(m),a.push(h.x,h.y,h.z),c.x=t*Math.cos(p),c.y=t*Math.sin(p),u.subVectors(h,c).normalize(),o.push(u.x,u.y,u.z),l.push(d/i),l.push(s/n)}for(let t=1;t<=n;t++)for(let e=1;e<=i;e++){const n=(i+1)*t+e-1,r=(i+1)*(t-1)+e-1,a=(i+1)*(t-1)+e,o=(i+1)*t+e;s.push(n,r,o),s.push(r,a,o)}this.setIndex(s),this.setAttribute("position",new Tn(a,3)),this.setAttribute("normal",new Tn(o,3)),this.setAttribute("uv",new Tn(l,2))}static fromJSON(t){return new Bl(t.radius,t.tube,t.radialSegments,t.tubularSegments,t.arc)}}class zl extends Nn{constructor(t=1,e=.4,n=64,i=8,r=2,s=3){super(),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:e,tubularSegments:n,radialSegments:i,p:r,q:s},n=Math.floor(n),i=Math.floor(i);const a=[],o=[],l=[],c=[],h=new Zt,u=new Zt,d=new Zt,p=new Zt,m=new Zt,f=new Zt,g=new Zt;for(let a=0;a<=n;++a){const y=a/n*r*Math.PI*2;v(y,r,s,t,d),v(y+.01,r,s,t,p),f.subVectors(p,d),g.addVectors(p,d),m.crossVectors(f,g),g.crossVectors(m,f),m.normalize(),g.normalize();for(let t=0;t<=i;++t){const r=t/i*Math.PI*2,s=-e*Math.cos(r),p=e*Math.sin(r);h.x=d.x+(s*g.x+p*m.x),h.y=d.y+(s*g.y+p*m.y),h.z=d.z+(s*g.z+p*m.z),o.push(h.x,h.y,h.z),u.subVectors(h,d).normalize(),l.push(u.x,u.y,u.z),c.push(a/n),c.push(t/i)}}for(let t=1;t<=n;t++)for(let e=1;e<=i;e++){const n=(i+1)*(t-1)+(e-1),r=(i+1)*t+(e-1),s=(i+1)*t+e,o=(i+1)*(t-1)+e;a.push(n,r,o),a.push(r,s,o)}function v(t,e,n,i,r){const s=Math.cos(t),a=Math.sin(t),o=n/e*t,l=Math.cos(o);r.x=i*(2+l)*.5*s,r.y=i*(2+l)*a*.5,r.z=i*Math.sin(o)*.5}this.setIndex(a),this.setAttribute("position",new Tn(o,3)),this.setAttribute("normal",new Tn(l,3)),this.setAttribute("uv",new Tn(c,2))}static fromJSON(t){return new zl(t.radius,t.tube,t.tubularSegments,t.radialSegments,t.p,t.q)}}class Ol extends Nn{constructor(t=new qo(new Zt(-1,-1,0),new Zt(-1,1,0),new Zt(1,1,0)),e=64,n=1,i=8,r=!1){super(),this.type="TubeGeometry",this.parameters={path:t,tubularSegments:e,radius:n,radialSegments:i,closed:r};const s=t.computeFrenetFrames(e,r);this.tangents=s.tangents,this.normals=s.normals,this.binormals=s.binormals;const a=new Zt,o=new Zt,l=new At;let c=new Zt;const h=[],u=[],d=[],p=[];function m(r){c=t.getPointAt(r/e,c);const l=s.normals[r],d=s.binormals[r];for(let t=0;t<=i;t++){const e=t/i*Math.PI*2,r=Math.sin(e),s=-Math.cos(e);o.x=s*l.x+r*d.x,o.y=s*l.y+r*d.y,o.z=s*l.z+r*d.z,o.normalize(),u.push(o.x,o.y,o.z),a.x=c.x+n*o.x,a.y=c.y+n*o.y,a.z=c.z+n*o.z,h.push(a.x,a.y,a.z)}}!function(){for(let t=0;t<e;t++)m(t);m(!1===r?e:0),function(){for(let t=0;t<=e;t++)for(let n=0;n<=i;n++)l.x=t/e,l.y=n/i,d.push(l.x,l.y)}(),function(){for(let t=1;t<=e;t++)for(let e=1;e<=i;e++){const n=(i+1)*(t-1)+(e-1),r=(i+1)*t+(e-1),s=(i+1)*t+e,a=(i+1)*(t-1)+e;p.push(n,r,a),p.push(r,s,a)}}()}(),this.setIndex(p),this.setAttribute("position",new Tn(h,3)),this.setAttribute("normal",new Tn(u,3)),this.setAttribute("uv",new Tn(d,2))}toJSON(){const t=super.toJSON();return t.path=this.parameters.path.toJSON(),t}static fromJSON(t){return new Ol((new Jo[t.path.type]).fromJSON(t.path),t.tubularSegments,t.radius,t.radialSegments,t.closed)}}class Fl extends Nn{constructor(t=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:t},null!==t){const e=[],n=new Set,i=new Zt,r=new Zt;if(null!==t.index){const s=t.attributes.position,a=t.index;let o=t.groups;0===o.length&&(o=[{start:0,count:a.count,materialIndex:0}]);for(let t=0,l=o.length;t<l;++t){const l=o[t],c=l.start;for(let t=c,o=c+l.count;t<o;t+=3)for(let o=0;o<3;o++){const l=a.getX(t+o),c=a.getX(t+(o+1)%3);i.fromBufferAttribute(s,l),r.fromBufferAttribute(s,c),!0===Ul(i,r,n)&&(e.push(i.x,i.y,i.z),e.push(r.x,r.y,r.z))}}}else{const s=t.attributes.position;for(let t=0,a=s.count/3;t<a;t++)for(let a=0;a<3;a++){const o=3*t+a,l=3*t+(a+1)%3;i.fromBufferAttribute(s,o),r.fromBufferAttribute(s,l),!0===Ul(i,r,n)&&(e.push(i.x,i.y,i.z),e.push(r.x,r.y,r.z))}}this.setAttribute("position",new Tn(e,3))}}}function Ul(t,e,n){const i=`${t.x},${t.y},${t.z}-${e.x},${e.y},${e.z}`,r=`${e.x},${e.y},${e.z}-${t.x},${t.y},${t.z}`;return!0!==n.has(i)&&!0!==n.has(r)&&(n.add(i,r),!0)}var Hl=Object.freeze({__proto__:null,BoxGeometry:ti,BoxBufferGeometry:ti,CircleGeometry:xo,CircleBufferGeometry:xo,ConeGeometry:Mo,ConeBufferGeometry:Mo,CylinderGeometry:_o,CylinderBufferGeometry:_o,DodecahedronGeometry:wo,DodecahedronBufferGeometry:wo,EdgesGeometry:Ro,ExtrudeGeometry:El,ExtrudeBufferGeometry:El,IcosahedronGeometry:Rl,IcosahedronBufferGeometry:Rl,LatheGeometry:Ll,LatheBufferGeometry:Ll,OctahedronGeometry:Cl,OctahedronBufferGeometry:Cl,PlaneGeometry:_i,PlaneBufferGeometry:_i,PolyhedronGeometry:bo,PolyhedronBufferGeometry:bo,RingGeometry:Pl,RingBufferGeometry:Pl,ShapeGeometry:Dl,ShapeBufferGeometry:Dl,SphereGeometry:Il,SphereBufferGeometry:Il,TetrahedronGeometry:Nl,TetrahedronBufferGeometry:Nl,TorusGeometry:Bl,TorusBufferGeometry:Bl,TorusKnotGeometry:zl,TorusKnotBufferGeometry:zl,TubeGeometry:Ol,TubeBufferGeometry:Ol,WireframeGeometry:Fl});class Gl extends dn{constructor(t){super(),this.type="ShadowMaterial",this.color=new Ut(0),this.transparent=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this}}Gl.prototype.isShadowMaterial=!0;class kl extends dn{constructor(t){super(),this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new Ut(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 Ut(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new At(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,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.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}}kl.prototype.isMeshStandardMaterial=!0;class Vl extends kl{constructor(t){super(),this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new At(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return _t(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.sheenColor=new Ut(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=0,this.attenuationColor=new Ut(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Ut(1,1,1),this.specularColorMap=null,this._sheen=0,this._clearcoat=0,this._transmission=0,this.setValues(t)}get sheen(){return this._sheen}set sheen(t){this._sheen>0!=t>0&&this.version++,this._sheen=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=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.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.ior=t.ior,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}}Vl.prototype.isMeshPhysicalMaterial=!0;class Wl extends dn{constructor(t){super(),this.type="MeshPhongMaterial",this.color=new Ut(16777215),this.specular=new Ut(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ut(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new At(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,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.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.flatShading=t.flatShading,this}}Wl.prototype.isMeshPhongMaterial=!0;class jl extends dn{constructor(t){super(),this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Ut(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ut(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new At(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.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}}jl.prototype.isMeshToonMaterial=!0;class ql extends dn{constructor(t){super(),this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new At(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!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}}ql.prototype.isMeshNormalMaterial=!0;class Xl extends dn{constructor(t){super(),this.type="MeshLambertMaterial",this.color=new Ut(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ut(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",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.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,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}}Xl.prototype.isMeshLambertMaterial=!0;class Jl extends dn{constructor(t){super(),this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Ut(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new At(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,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.flatShading=t.flatShading,this}}Jl.prototype.isMeshMatcapMaterial=!0;class Yl extends Za{constructor(t){super(),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}}Yl.prototype.isLineDashedMaterial=!0;var Zl=Object.freeze({__proto__:null,ShadowMaterial:Gl,SpriteMaterial:ma,RawShaderMaterial:Pi,ShaderMaterial:ri,PointsMaterial:oo,MeshPhysicalMaterial:Vl,MeshStandardMaterial:kl,MeshPhongMaterial:Wl,MeshToonMaterial:jl,MeshNormalMaterial:ql,MeshLambertMaterial:Xl,MeshDepthMaterial:Xs,MeshDistanceMaterial:Js,MeshBasicMaterial:pn,MeshMatcapMaterial:Jl,LineDashedMaterial:Yl,LineBasicMaterial:Za,Material:dn});const Kl={arraySlice:function(t,e,n){return Kl.isTypedArray(t)?new t.constructor(t.subarray(e,void 0!==n?n:t.length)):t.slice(e,n)},convertArray:function(t,e,n){return!t||!n&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)},isTypedArray:function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)},getKeyframeOrder:function(t){const e=t.length,n=new Array(e);for(let t=0;t!==e;++t)n[t]=t;return n.sort((function(e,n){return t[e]-t[n]})),n},sortedArray:function(t,e,n){const i=t.length,r=new t.constructor(i);for(let s=0,a=0;a!==i;++s){const i=n[s]*e;for(let n=0;n!==e;++n)r[a++]=t[i+n]}return r},flattenJSON:function(t,e,n,i){let r=1,s=t[0];for(;void 0!==s&&void 0===s[i];)s=t[r++];if(void 0===s)return;let a=s[i];if(void 0!==a)if(Array.isArray(a))do{a=s[i],void 0!==a&&(e.push(s.time),n.push.apply(n,a)),s=t[r++]}while(void 0!==s);else if(void 0!==a.toArray)do{a=s[i],void 0!==a&&(e.push(s.time),a.toArray(n,n.length)),s=t[r++]}while(void 0!==s);else do{a=s[i],void 0!==a&&(e.push(s.time),n.push(a)),s=t[r++]}while(void 0!==s)},subclip:function(t,e,n,i,r=30){const s=t.clone();s.name=e;const a=[];for(let t=0;t<s.tracks.length;++t){const e=s.tracks[t],o=e.getValueSize(),l=[],c=[];for(let t=0;t<e.times.length;++t){const s=e.times[t]*r;if(!(s<n||s>=i)){l.push(e.times[t]);for(let n=0;n<o;++n)c.push(e.values[t*o+n])}}0!==l.length&&(e.times=Kl.convertArray(l,e.times.constructor),e.values=Kl.convertArray(c,e.values.constructor),a.push(e))}s.tracks=a;let o=1/0;for(let t=0;t<s.tracks.length;++t)o>s.tracks[t].times[0]&&(o=s.tracks[t].times[0]);for(let t=0;t<s.tracks.length;++t)s.tracks[t].shift(-1*o);return s.resetDuration(),s},makeClipAdditive:function(t,e=0,n=t,i=30){i<=0&&(i=30);const r=n.tracks.length,s=e/i;for(let e=0;e<r;++e){const i=n.tracks[e],r=i.ValueTypeName;if("bool"===r||"string"===r)continue;const a=t.tracks.find((function(t){return t.name===i.name&&t.ValueTypeName===r}));if(void 0===a)continue;let o=0;const l=i.getValueSize();i.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(o=l/3);let c=0;const h=a.getValueSize();a.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(c=h/3);const u=i.times.length-1;let d;if(s<=i.times[0]){const t=o,e=l-o;d=Kl.arraySlice(i.values,t,e)}else if(s>=i.times[u]){const t=u*l+o,e=t+l-o;d=Kl.arraySlice(i.values,t,e)}else{const t=i.createInterpolant(),e=o,n=l-o;t.evaluate(s),d=Kl.arraySlice(t.resultBuffer,e,n)}if("quaternion"===r){(new Yt).fromArray(d).normalize().conjugate().toArray(d)}const p=a.times.length;for(let t=0;t<p;++t){const e=t*h+c;if("quaternion"===r)Yt.multiplyQuaternionsFlat(a.values,e,d,0,a.values,e);else{const t=h-2*c;for(let n=0;n<t;++n)a.values[e+n]-=d[n]}}}return t.blendMode=at,t}};class Ql{constructor(t,e,n,i){this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=void 0!==i?i:new e.constructor(n),this.sampleValues=e,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(t){const e=this.parameterPositions;let n=this._cachedIndex,i=e[n],r=e[n-1];t:{e:{let s;n:{i:if(!(t<i)){for(let s=n+2;;){if(void 0===i){if(t<r)break i;return n=e.length,this._cachedIndex=n,this.afterEnd_(n-1,t,r)}if(n===s)break;if(r=i,i=e[++n],t<i)break e}s=e.length;break n}if(t>=r)break t;{const a=e[1];t<a&&(n=2,r=a);for(let s=n-2;;){if(void 0===r)return this._cachedIndex=0,this.beforeStart_(0,t,i);if(n===s)break;if(i=r,r=e[--n-1],t>=r)break e}s=n,n=0}}for(;n<s;){const i=n+s>>>1;t<e[i]?s=i:n=i+1}if(i=e[n],r=e[n-1],void 0===r)return this._cachedIndex=0,this.beforeStart_(0,t,i);if(void 0===i)return n=e.length,this._cachedIndex=n,this.afterEnd_(n-1,r,t)}this._cachedIndex=n,this.intervalChanged_(n,r,i)}return this.interpolate_(n,r,t,i)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(t){const e=this.resultBuffer,n=this.sampleValues,i=this.valueSize,r=t*i;for(let t=0;t!==i;++t)e[t]=n[r+t];return e}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}}Ql.prototype.beforeStart_=Ql.prototype.copySampleValue_,Ql.prototype.afterEnd_=Ql.prototype.copySampleValue_;class $l extends Ql{constructor(t,e,n,i){super(t,e,n,i),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:nt,endingEnd:nt}}intervalChanged_(t,e,n){const i=this.parameterPositions;let r=t-2,s=t+1,a=i[r],o=i[s];if(void 0===a)switch(this.getSettings_().endingStart){case it:r=t,a=2*e-n;break;case rt:r=i.length-2,a=e+i[r]-i[r+1];break;default:r=t,a=n}if(void 0===o)switch(this.getSettings_().endingEnd){case it:s=t,o=2*n-e;break;case rt:s=1,o=n+i[1]-i[0];break;default:s=t-1,o=e}const l=.5*(n-e),c=this.valueSize;this._weightPrev=l/(e-a),this._weightNext=l/(o-n),this._offsetPrev=r*c,this._offsetNext=s*c}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=t*a,l=o-a,c=this._offsetPrev,h=this._offsetNext,u=this._weightPrev,d=this._weightNext,p=(n-e)/(i-e),m=p*p,f=m*p,g=-u*f+2*u*m-u*p,v=(1+u)*f+(-1.5-2*u)*m+(-.5+u)*p+1,y=(-1-d)*f+(1.5+d)*m+.5*p,x=d*f-d*m;for(let t=0;t!==a;++t)r[t]=g*s[c+t]+v*s[l+t]+y*s[o+t]+x*s[h+t];return r}}class tc extends Ql{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=t*a,l=o-a,c=(n-e)/(i-e),h=1-c;for(let t=0;t!==a;++t)r[t]=s[l+t]*h+s[o+t]*c;return r}}class ec extends Ql{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t){return this.copySampleValue_(t-1)}}class nc{constructor(t,e,n,i){if(void 0===t)throw new Error("THREE.KeyframeTrack: track name is undefined");if(void 0===e||0===e.length)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+t);this.name=t,this.times=Kl.convertArray(e,this.TimeBufferType),this.values=Kl.convertArray(n,this.ValueBufferType),this.setInterpolation(i||this.DefaultInterpolation)}static toJSON(t){const e=t.constructor;let n;if(e.toJSON!==this.toJSON)n=e.toJSON(t);else{n={name:t.name,times:Kl.convertArray(t.times,Array),values:Kl.convertArray(t.values,Array)};const e=t.getInterpolation();e!==t.DefaultInterpolation&&(n.interpolation=e)}return n.type=t.ValueTypeName,n}InterpolantFactoryMethodDiscrete(t){return new ec(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodLinear(t){return new tc(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodSmooth(t){return new $l(this.times,this.values,this.getValueSize(),t)}setInterpolation(t){let e;switch(t){case $:e=this.InterpolantFactoryMethodDiscrete;break;case tt:e=this.InterpolantFactoryMethodLinear;break;case et:e=this.InterpolantFactoryMethodSmooth}if(void 0===e){const e="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(void 0===this.createInterpolant){if(t===this.DefaultInterpolation)throw new Error(e);this.setInterpolation(this.DefaultInterpolation)}return console.warn("THREE.KeyframeTrack:",e),this}return this.createInterpolant=e,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return $;case this.InterpolantFactoryMethodLinear:return tt;case this.InterpolantFactoryMethodSmooth:return et}}getValueSize(){return this.values.length/this.times.length}shift(t){if(0!==t){const e=this.times;for(let n=0,i=e.length;n!==i;++n)e[n]+=t}return this}scale(t){if(1!==t){const e=this.times;for(let n=0,i=e.length;n!==i;++n)e[n]*=t}return this}trim(t,e){const n=this.times,i=n.length;let r=0,s=i-1;for(;r!==i&&n[r]<t;)++r;for(;-1!==s&&n[s]>e;)--s;if(++s,0!==r||s!==i){r>=s&&(s=Math.max(s,1),r=s-1);const t=this.getValueSize();this.times=Kl.arraySlice(n,r,s),this.values=Kl.arraySlice(this.values,r*t,s*t)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);const n=this.times,i=this.values,r=n.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),t=!1);let s=null;for(let e=0;e!==r;e++){const i=n[e];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,e,i),t=!1;break}if(null!==s&&s>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,e,i,s),t=!1;break}s=i}if(void 0!==i&&Kl.isTypedArray(i))for(let e=0,n=i.length;e!==n;++e){const n=i[e];if(isNaN(n)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,e,n),t=!1;break}}return t}optimize(){const t=Kl.arraySlice(this.times),e=Kl.arraySlice(this.values),n=this.getValueSize(),i=this.getInterpolation()===et,r=t.length-1;let s=1;for(let a=1;a<r;++a){let r=!1;const o=t[a];if(o!==t[a+1]&&(1!==a||o!==t[0]))if(i)r=!0;else{const t=a*n,i=t-n,s=t+n;for(let a=0;a!==n;++a){const n=e[t+a];if(n!==e[i+a]||n!==e[s+a]){r=!0;break}}}if(r){if(a!==s){t[s]=t[a];const i=a*n,r=s*n;for(let t=0;t!==n;++t)e[r+t]=e[i+t]}++s}}if(r>0){t[s]=t[r];for(let t=r*n,i=s*n,a=0;a!==n;++a)e[i+a]=e[t+a];++s}return s!==t.length?(this.times=Kl.arraySlice(t,0,s),this.values=Kl.arraySlice(e,0,s*n)):(this.times=t,this.values=e),this}clone(){const t=Kl.arraySlice(this.times,0),e=Kl.arraySlice(this.values,0),n=new(0,this.constructor)(this.name,t,e);return n.createInterpolant=this.createInterpolant,n}}nc.prototype.TimeBufferType=Float32Array,nc.prototype.ValueBufferType=Float32Array,nc.prototype.DefaultInterpolation=tt;class ic extends nc{}ic.prototype.ValueTypeName="bool",ic.prototype.ValueBufferType=Array,ic.prototype.DefaultInterpolation=$,ic.prototype.InterpolantFactoryMethodLinear=void 0,ic.prototype.InterpolantFactoryMethodSmooth=void 0;class rc extends nc{}rc.prototype.ValueTypeName="color";class sc extends nc{}sc.prototype.ValueTypeName="number";class ac extends Ql{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(n-e)/(i-e);let l=t*a;for(let t=l+a;l!==t;l+=4)Yt.slerpFlat(r,0,s,l-a,s,l,o);return r}}class oc extends nc{InterpolantFactoryMethodLinear(t){return new ac(this.times,this.values,this.getValueSize(),t)}}oc.prototype.ValueTypeName="quaternion",oc.prototype.DefaultInterpolation=tt,oc.prototype.InterpolantFactoryMethodSmooth=void 0;class lc extends nc{}lc.prototype.ValueTypeName="string",lc.prototype.ValueBufferType=Array,lc.prototype.DefaultInterpolation=$,lc.prototype.InterpolantFactoryMethodLinear=void 0,lc.prototype.InterpolantFactoryMethodSmooth=void 0;class cc extends nc{}cc.prototype.ValueTypeName="vector";class hc{constructor(t,e=-1,n,i=2500){this.name=t,this.tracks=n,this.duration=e,this.blendMode=i,this.uuid=xt(),this.duration<0&&this.resetDuration()}static parse(t){const e=[],n=t.tracks,i=1/(t.fps||1);for(let t=0,r=n.length;t!==r;++t)e.push(uc(n[t]).scale(i));const r=new this(t.name,t.duration,e,t.blendMode);return r.uuid=t.uuid,r}static toJSON(t){const e=[],n=t.tracks,i={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode};for(let t=0,i=n.length;t!==i;++t)e.push(nc.toJSON(n[t]));return i}static CreateFromMorphTargetSequence(t,e,n,i){const r=e.length,s=[];for(let t=0;t<r;t++){let a=[],o=[];a.push((t+r-1)%r,t,(t+1)%r),o.push(0,1,0);const l=Kl.getKeyframeOrder(a);a=Kl.sortedArray(a,1,l),o=Kl.sortedArray(o,1,l),i||0!==a[0]||(a.push(r),o.push(o[0])),s.push(new sc(".morphTargetInfluences["+e[t].name+"]",a,o).scale(1/n))}return new this(t,-1,s)}static findByName(t,e){let n=t;if(!Array.isArray(t)){const e=t;n=e.geometry&&e.geometry.animations||e.animations}for(let t=0;t<n.length;t++)if(n[t].name===e)return n[t];return null}static CreateClipsFromMorphTargetSequences(t,e,n){const i={},r=/^([\w-]*?)([\d]+)$/;for(let e=0,n=t.length;e<n;e++){const n=t[e],s=n.name.match(r);if(s&&s.length>1){const t=s[1];let e=i[t];e||(i[t]=e=[]),e.push(n)}}const s=[];for(const t in i)s.push(this.CreateFromMorphTargetSequence(t,i[t],e,n));return s}static parseAnimation(t,e){if(!t)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(t,e,n,i,r){if(0!==n.length){const s=[],a=[];Kl.flattenJSON(n,s,a,i),0!==s.length&&r.push(new t(e,s,a))}},i=[],r=t.name||"default",s=t.fps||30,a=t.blendMode;let o=t.length||-1;const l=t.hierarchy||[];for(let t=0;t<l.length;t++){const r=l[t].keys;if(r&&0!==r.length)if(r[0].morphTargets){const t={};let e;for(e=0;e<r.length;e++)if(r[e].morphTargets)for(let n=0;n<r[e].morphTargets.length;n++)t[r[e].morphTargets[n]]=-1;for(const n in t){const t=[],s=[];for(let i=0;i!==r[e].morphTargets.length;++i){const i=r[e];t.push(i.time),s.push(i.morphTarget===n?1:0)}i.push(new sc(".morphTargetInfluence["+n+"]",t,s))}o=t.length*(s||1)}else{const s=".bones["+e[t].name+"]";n(cc,s+".position",r,"pos",i),n(oc,s+".quaternion",r,"rot",i),n(cc,s+".scale",r,"scl",i)}}if(0===i.length)return null;return new this(r,o,i,a)}resetDuration(){let t=0;for(let e=0,n=this.tracks.length;e!==n;++e){const n=this.tracks[e];t=Math.max(t,n.times[n.times.length-1])}return this.duration=t,this}trim(){for(let t=0;t<this.tracks.length;t++)this.tracks[t].trim(0,this.duration);return this}validate(){let t=!0;for(let e=0;e<this.tracks.length;e++)t=t&&this.tracks[e].validate();return t}optimize(){for(let t=0;t<this.tracks.length;t++)this.tracks[t].optimize();return this}clone(){const t=[];for(let e=0;e<this.tracks.length;e++)t.push(this.tracks[e].clone());return new this.constructor(this.name,this.duration,t,this.blendMode)}toJSON(){return this.constructor.toJSON(this)}}function uc(t){if(void 0===t.type)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const e=function(t){switch(t.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return sc;case"vector":case"vector2":case"vector3":case"vector4":return cc;case"color":return rc;case"quaternion":return oc;case"bool":case"boolean":return ic;case"string":return lc}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+t)}(t.type);if(void 0===t.times){const e=[],n=[];Kl.flattenJSON(t.keys,e,n,"value"),t.times=e,t.values=n}return void 0!==e.parse?e.parse(t):new e(t.name,t.times,t.values,t.interpolation)}const dc={enabled:!1,files:{},add:function(t,e){!1!==this.enabled&&(this.files[t]=e)},get:function(t){if(!1!==this.enabled)return this.files[t]},remove:function(t){delete this.files[t]},clear:function(){this.files={}}};class pc{constructor(t,e,n){const i=this;let r,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=n,this.itemStart=function(t){o++,!1===s&&void 0!==i.onStart&&i.onStart(t,a,o),s=!0},this.itemEnd=function(t){a++,void 0!==i.onProgress&&i.onProgress(t,a,o),a===o&&(s=!1,void 0!==i.onLoad&&i.onLoad())},this.itemError=function(t){void 0!==i.onError&&i.onError(t)},this.resolveURL=function(t){return r?r(t):t},this.setURLModifier=function(t){return r=t,this},this.addHandler=function(t,e){return l.push(t,e),this},this.removeHandler=function(t){const e=l.indexOf(t);return-1!==e&&l.splice(e,2),this},this.getHandler=function(t){for(let e=0,n=l.length;e<n;e+=2){const n=l[e],i=l[e+1];if(n.global&&(n.lastIndex=0),n.test(t))return i}return null}}}const mc=new pc;class fc{constructor(t){this.manager=void 0!==t?t:mc,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(t,e){const n=this;return new Promise((function(i,r){n.load(t,i,e,r)}))}parse(){}setCrossOrigin(t){return this.crossOrigin=t,this}setWithCredentials(t){return this.withCredentials=t,this}setPath(t){return this.path=t,this}setResourcePath(t){return this.resourcePath=t,this}setRequestHeader(t){return this.requestHeader=t,this}}const gc={};class vc extends fc{constructor(t){super(t)}load(t,e,n,i){void 0===t&&(t=""),void 0!==this.path&&(t=this.path+t),t=this.manager.resolveURL(t);const r=dc.get(t);if(void 0!==r)return this.manager.itemStart(t),setTimeout((()=>{e&&e(r),this.manager.itemEnd(t)}),0),r;if(void 0!==gc[t])return void gc[t].push({onLoad:e,onProgress:n,onError:i});gc[t]=[],gc[t].push({onLoad:e,onProgress:n,onError:i});const s=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(s).then((e=>{if(200===e.status||0===e.status){if(0===e.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===e.body.getReader)return e;const n=gc[t],i=e.body.getReader(),r=e.headers.get("Content-Length"),s=r?parseInt(r):0,a=0!==s;let o=0;const l=new ReadableStream({start(t){!function e(){i.read().then((({done:i,value:r})=>{if(i)t.close();else{o+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:s});for(let t=0,e=n.length;t<e;t++){const e=n[t];e.onProgress&&e.onProgress(i)}t.enqueue(r),e()}}))}()}});return new Response(l)}throw Error(`fetch for "${e.url}" responded with ${e.status}: ${e.statusText}`)})).then((t=>{switch(o){case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"document":return t.text().then((t=>(new DOMParser).parseFromString(t,a)));case"json":return t.json();default:if(void 0===a)return t.text();{const e=/charset="?([^;"\s]*)"?/i.exec(a),n=e&&e[1]?e[1].toLowerCase():void 0,i=new TextDecoder(n);return t.arrayBuffer().then((t=>i.decode(t)))}}})).then((e=>{dc.add(t,e);const n=gc[t];delete gc[t];for(let t=0,i=n.length;t<i;t++){const i=n[t];i.onLoad&&i.onLoad(e)}})).catch((e=>{const n=gc[t];if(void 0===n)throw this.manager.itemError(t),e;delete gc[t];for(let t=0,i=n.length;t<i;t++){const i=n[t];i.onError&&i.onError(e)}this.manager.itemError(t)})).finally((()=>{this.manager.itemEnd(t)})),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}}class yc extends fc{constructor(t){super(t)}load(t,e,n,i){void 0!==this.path&&(t=this.path+t),t=this.manager.resolveURL(t);const r=this,s=dc.get(t);if(void 0!==s)return r.manager.itemStart(t),setTimeout((function(){e&&e(s),r.manager.itemEnd(t)}),0),s;const a=Dt("img");function o(){c(),dc.add(t,this),e&&e(this),r.manager.itemEnd(t)}function l(e){c(),i&&i(e),r.manager.itemError(t),r.manager.itemEnd(t)}function c(){a.removeEventListener("load",o,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",o,!1),a.addEventListener("error",l,!1),"data:"!==t.substr(0,5)&&void 0!==this.crossOrigin&&(a.crossOrigin=this.crossOrigin),r.manager.itemStart(t),a.src=t,a}}class xc extends fc{constructor(t){super(t)}load(t,e,n,i){const r=new ci,s=new yc(this.manager);s.setCrossOrigin(this.crossOrigin),s.setPath(this.path);let a=0;function o(n){s.load(t[n],(function(t){r.images[n]=t,a++,6===a&&(r.needsUpdate=!0,e&&e(r))}),void 0,i)}for(let e=0;e<t.length;++e)o(e);return r}}class _c extends fc{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new Ha,a=new vc(this.manager);return a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setPath(this.path),a.setWithCredentials(r.withCredentials),a.load(t,(function(t){const n=r.parse(t);n&&(void 0!==n.image?s.image=n.image:void 0!==n.data&&(s.image.width=n.width,s.image.height=n.height,s.image.data=n.data),s.wrapS=void 0!==n.wrapS?n.wrapS:u,s.wrapT=void 0!==n.wrapT?n.wrapT:u,s.magFilter=void 0!==n.magFilter?n.magFilter:g,s.minFilter=void 0!==n.minFilter?n.minFilter:g,s.anisotropy=void 0!==n.anisotropy?n.anisotropy:1,void 0!==n.encoding&&(s.encoding=n.encoding),void 0!==n.flipY&&(s.flipY=n.flipY),void 0!==n.format&&(s.format=n.format),void 0!==n.type&&(s.type=n.type),void 0!==n.mipmaps&&(s.mipmaps=n.mipmaps,s.minFilter=y),1===n.mipmapCount&&(s.minFilter=g),void 0!==n.generateMipmaps&&(s.generateMipmaps=n.generateMipmaps),s.needsUpdate=!0,e&&e(s,n))}),n,i),s}}class Mc extends fc{constructor(t){super(t)}load(t,e,n,i){const r=new Vt,s=new yc(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(t,(function(t){r.image=t,r.needsUpdate=!0,void 0!==e&&e(r)}),n,i),r}}class bc extends Qe{constructor(t,e=1){super(),this.type="Light",this.color=new Ut(t),this.intensity=e}dispose(){}copy(t){return super.copy(t),this.color.copy(t.color),this.intensity=t.intensity,this}toJSON(t){const e=super.toJSON(t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),void 0!==this.shadow&&(e.object.shadow=this.shadow.toJSON()),e}}bc.prototype.isLight=!0;class wc extends bc{constructor(t,e,n){super(t,n),this.type="HemisphereLight",this.position.copy(Qe.DefaultUp),this.updateMatrix(),this.groundColor=new Ut(e)}copy(t){return bc.prototype.copy.call(this,t),this.groundColor.copy(t.groundColor),this}}wc.prototype.isHemisphereLight=!0;const Sc=new Ae,Tc=new Zt,Ec=new Zt;class Ac{constructor(t){this.camera=t,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new At(512,512),this.map=null,this.mapPass=null,this.matrix=new Ae,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new vi,this._frameExtents=new At(1,1),this._viewportCount=1,this._viewports=[new jt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(t){const e=this.camera,n=this.matrix;Tc.setFromMatrixPosition(t.matrixWorld),e.position.copy(Tc),Ec.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(Ec),e.updateMatrixWorld(),Sc.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Sc),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(e.projectionMatrix),n.multiply(e.matrixWorldInverse)}getViewport(t){return this._viewports[t]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(t){return this.camera=t.camera.clone(),this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this}clone(){return(new this.constructor).copy(this)}toJSON(){const t={};return 0!==this.bias&&(t.bias=this.bias),0!==this.normalBias&&(t.normalBias=this.normalBias),1!==this.radius&&(t.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(t.mapSize=this.mapSize.toArray()),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}}class Rc extends Ac{constructor(){super(new ai(50,1,.5,500)),this.focus=1}updateMatrices(t){const e=this.camera,n=2*yt*t.angle*this.focus,i=this.mapSize.width/this.mapSize.height,r=t.distance||e.far;n===e.fov&&i===e.aspect&&r===e.far||(e.fov=n,e.aspect=i,e.far=r,e.updateProjectionMatrix()),super.updateMatrices(t)}copy(t){return super.copy(t),this.focus=t.focus,this}}Rc.prototype.isSpotLightShadow=!0;class Lc extends bc{constructor(t,e,n=0,i=Math.PI/3,r=0,s=1){super(t,e),this.type="SpotLight",this.position.copy(Qe.DefaultUp),this.updateMatrix(),this.target=new Qe,this.distance=n,this.angle=i,this.penumbra=r,this.decay=s,this.shadow=new Rc}get power(){return this.intensity*Math.PI}set power(t){this.intensity=t/Math.PI}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}Lc.prototype.isSpotLight=!0;const Cc=new Ae,Pc=new Zt,Dc=new Zt;class Ic extends Ac{constructor(){super(new ai(90,1,.5,500)),this._frameExtents=new At(4,2),this._viewportCount=6,this._viewports=[new jt(2,1,1,1),new jt(0,1,1,1),new jt(3,1,1,1),new jt(1,1,1,1),new jt(3,0,1,1),new jt(1,0,1,1)],this._cubeDirections=[new Zt(1,0,0),new Zt(-1,0,0),new Zt(0,0,1),new Zt(0,0,-1),new Zt(0,1,0),new Zt(0,-1,0)],this._cubeUps=[new Zt(0,1,0),new Zt(0,1,0),new Zt(0,1,0),new Zt(0,1,0),new Zt(0,0,1),new Zt(0,0,-1)]}updateMatrices(t,e=0){const n=this.camera,i=this.matrix,r=t.distance||n.far;r!==n.far&&(n.far=r,n.updateProjectionMatrix()),Pc.setFromMatrixPosition(t.matrixWorld),n.position.copy(Pc),Dc.copy(n.position),Dc.add(this._cubeDirections[e]),n.up.copy(this._cubeUps[e]),n.lookAt(Dc),n.updateMatrixWorld(),i.makeTranslation(-Pc.x,-Pc.y,-Pc.z),Cc.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Cc)}}Ic.prototype.isPointLightShadow=!0;class Nc extends bc{constructor(t,e,n=0,i=1){super(t,e),this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new Ic}get power(){return 4*this.intensity*Math.PI}set power(t){this.intensity=t/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}Nc.prototype.isPointLight=!0;class Bc extends Ac{constructor(){super(new Ci(-5,5,5,-5,.5,500))}}Bc.prototype.isDirectionalLightShadow=!0;class zc extends bc{constructor(t,e){super(t,e),this.type="DirectionalLight",this.position.copy(Qe.DefaultUp),this.updateMatrix(),this.target=new Qe,this.shadow=new Bc}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}zc.prototype.isDirectionalLight=!0;class Oc extends bc{constructor(t,e){super(t,e),this.type="AmbientLight"}}Oc.prototype.isAmbientLight=!0;class Fc extends bc{constructor(t,e,n=10,i=10){super(t,e),this.type="RectAreaLight",this.width=n,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(t){this.intensity=t/(this.width*this.height*Math.PI)}copy(t){return super.copy(t),this.width=t.width,this.height=t.height,this}toJSON(t){const e=super.toJSON(t);return e.object.width=this.width,e.object.height=this.height,e}}Fc.prototype.isRectAreaLight=!0;class Uc{constructor(){this.coefficients=[];for(let t=0;t<9;t++)this.coefficients.push(new Zt)}set(t){for(let e=0;e<9;e++)this.coefficients[e].copy(t[e]);return this}zero(){for(let t=0;t<9;t++)this.coefficients[t].set(0,0,0);return this}getAt(t,e){const n=t.x,i=t.y,r=t.z,s=this.coefficients;return e.copy(s[0]).multiplyScalar(.282095),e.addScaledVector(s[1],.488603*i),e.addScaledVector(s[2],.488603*r),e.addScaledVector(s[3],.488603*n),e.addScaledVector(s[4],n*i*1.092548),e.addScaledVector(s[5],i*r*1.092548),e.addScaledVector(s[6],.315392*(3*r*r-1)),e.addScaledVector(s[7],n*r*1.092548),e.addScaledVector(s[8],.546274*(n*n-i*i)),e}getIrradianceAt(t,e){const n=t.x,i=t.y,r=t.z,s=this.coefficients;return e.copy(s[0]).multiplyScalar(.886227),e.addScaledVector(s[1],1.023328*i),e.addScaledVector(s[2],1.023328*r),e.addScaledVector(s[3],1.023328*n),e.addScaledVector(s[4],.858086*n*i),e.addScaledVector(s[5],.858086*i*r),e.addScaledVector(s[6],.743125*r*r-.247708),e.addScaledVector(s[7],.858086*n*r),e.addScaledVector(s[8],.429043*(n*n-i*i)),e}add(t){for(let e=0;e<9;e++)this.coefficients[e].add(t.coefficients[e]);return this}addScaledSH(t,e){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(t.coefficients[n],e);return this}scale(t){for(let e=0;e<9;e++)this.coefficients[e].multiplyScalar(t);return this}lerp(t,e){for(let n=0;n<9;n++)this.coefficients[n].lerp(t.coefficients[n],e);return this}equals(t){for(let e=0;e<9;e++)if(!this.coefficients[e].equals(t.coefficients[e]))return!1;return!0}copy(t){return this.set(t.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(t,e=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].fromArray(t,e+3*i);return this}toArray(t=[],e=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].toArray(t,e+3*i);return t}static getBasisAt(t,e){const n=t.x,i=t.y,r=t.z;e[0]=.282095,e[1]=.488603*i,e[2]=.488603*r,e[3]=.488603*n,e[4]=1.092548*n*i,e[5]=1.092548*i*r,e[6]=.315392*(3*r*r-1),e[7]=1.092548*n*r,e[8]=.546274*(n*n-i*i)}}Uc.prototype.isSphericalHarmonics3=!0;class Hc extends bc{constructor(t=new Uc,e=1){super(void 0,e),this.sh=t}copy(t){return super.copy(t),this.sh.copy(t.sh),this}fromJSON(t){return this.intensity=t.intensity,this.sh.fromArray(t.sh),this}toJSON(t){const e=super.toJSON(t);return e.object.sh=this.sh.toArray(),e}}Hc.prototype.isLightProbe=!0;class Gc extends fc{constructor(t){super(t),this.textures={}}load(t,e,n,i){const r=this,s=new vc(r.manager);s.setPath(r.path),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(t,(function(n){try{e(r.parse(JSON.parse(n)))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}parse(t){const e=this.textures;function n(t){return void 0===e[t]&&console.warn("THREE.MaterialLoader: Undefined texture",t),e[t]}const i=new Zl[t.type];if(void 0!==t.uuid&&(i.uuid=t.uuid),void 0!==t.name&&(i.name=t.name),void 0!==t.color&&void 0!==i.color&&i.color.setHex(t.color),void 0!==t.roughness&&(i.roughness=t.roughness),void 0!==t.metalness&&(i.metalness=t.metalness),void 0!==t.sheen&&(i.sheen=t.sheen),void 0!==t.sheenColor&&(i.sheenColor=(new Ut).setHex(t.sheenColor)),void 0!==t.sheenRoughness&&(i.sheenRoughness=t.sheenRoughness),void 0!==t.emissive&&void 0!==i.emissive&&i.emissive.setHex(t.emissive),void 0!==t.specular&&void 0!==i.specular&&i.specular.setHex(t.specular),void 0!==t.specularIntensity&&(i.specularIntensity=t.specularIntensity),void 0!==t.specularColor&&void 0!==i.specularColor&&i.specularColor.setHex(t.specularColor),void 0!==t.shininess&&(i.shininess=t.shininess),void 0!==t.clearcoat&&(i.clearcoat=t.clearcoat),void 0!==t.clearcoatRoughness&&(i.clearcoatRoughness=t.clearcoatRoughness),void 0!==t.transmission&&(i.transmission=t.transmission),void 0!==t.thickness&&(i.thickness=t.thickness),void 0!==t.attenuationDistance&&(i.attenuationDistance=t.attenuationDistance),void 0!==t.attenuationColor&&void 0!==i.attenuationColor&&i.attenuationColor.setHex(t.attenuationColor),void 0!==t.fog&&(i.fog=t.fog),void 0!==t.flatShading&&(i.flatShading=t.flatShading),void 0!==t.blending&&(i.blending=t.blending),void 0!==t.combine&&(i.combine=t.combine),void 0!==t.side&&(i.side=t.side),void 0!==t.shadowSide&&(i.shadowSide=t.shadowSide),void 0!==t.opacity&&(i.opacity=t.opacity),void 0!==t.transparent&&(i.transparent=t.transparent),void 0!==t.alphaTest&&(i.alphaTest=t.alphaTest),void 0!==t.depthTest&&(i.depthTest=t.depthTest),void 0!==t.depthWrite&&(i.depthWrite=t.depthWrite),void 0!==t.colorWrite&&(i.colorWrite=t.colorWrite),void 0!==t.alphaWrite&&(i.alphaWrite=t.alphaWrite),void 0!==t.stencilWrite&&(i.stencilWrite=t.stencilWrite),void 0!==t.stencilWriteMask&&(i.stencilWriteMask=t.stencilWriteMask),void 0!==t.stencilFunc&&(i.stencilFunc=t.stencilFunc),void 0!==t.stencilRef&&(i.stencilRef=t.stencilRef),void 0!==t.stencilFuncMask&&(i.stencilFuncMask=t.stencilFuncMask),void 0!==t.stencilFail&&(i.stencilFail=t.stencilFail),void 0!==t.stencilZFail&&(i.stencilZFail=t.stencilZFail),void 0!==t.stencilZPass&&(i.stencilZPass=t.stencilZPass),void 0!==t.wireframe&&(i.wireframe=t.wireframe),void 0!==t.wireframeLinewidth&&(i.wireframeLinewidth=t.wireframeLinewidth),void 0!==t.wireframeLinecap&&(i.wireframeLinecap=t.wireframeLinecap),void 0!==t.wireframeLinejoin&&(i.wireframeLinejoin=t.wireframeLinejoin),void 0!==t.rotation&&(i.rotation=t.rotation),1!==t.linewidth&&(i.linewidth=t.linewidth),void 0!==t.dashSize&&(i.dashSize=t.dashSize),void 0!==t.gapSize&&(i.gapSize=t.gapSize),void 0!==t.scale&&(i.scale=t.scale),void 0!==t.polygonOffset&&(i.polygonOffset=t.polygonOffset),void 0!==t.polygonOffsetFactor&&(i.polygonOffsetFactor=t.polygonOffsetFactor),void 0!==t.polygonOffsetUnits&&(i.polygonOffsetUnits=t.polygonOffsetUnits),void 0!==t.dithering&&(i.dithering=t.dithering),void 0!==t.alphaToCoverage&&(i.alphaToCoverage=t.alphaToCoverage),void 0!==t.premultipliedAlpha&&(i.premultipliedAlpha=t.premultipliedAlpha),void 0!==t.visible&&(i.visible=t.visible),void 0!==t.toneMapped&&(i.toneMapped=t.toneMapped),void 0!==t.userData&&(i.userData=t.userData),void 0!==t.vertexColors&&("number"==typeof t.vertexColors?i.vertexColors=t.vertexColors>0:i.vertexColors=t.vertexColors),void 0!==t.uniforms)for(const e in t.uniforms){const r=t.uniforms[e];switch(i.uniforms[e]={},r.type){case"t":i.uniforms[e].value=n(r.value);break;case"c":i.uniforms[e].value=(new Ut).setHex(r.value);break;case"v2":i.uniforms[e].value=(new At).fromArray(r.value);break;case"v3":i.uniforms[e].value=(new Zt).fromArray(r.value);break;case"v4":i.uniforms[e].value=(new jt).fromArray(r.value);break;case"m3":i.uniforms[e].value=(new Rt).fromArray(r.value);break;case"m4":i.uniforms[e].value=(new Ae).fromArray(r.value);break;default:i.uniforms[e].value=r.value}}if(void 0!==t.defines&&(i.defines=t.defines),void 0!==t.vertexShader&&(i.vertexShader=t.vertexShader),void 0!==t.fragmentShader&&(i.fragmentShader=t.fragmentShader),void 0!==t.extensions)for(const e in t.extensions)i.extensions[e]=t.extensions[e];if(void 0!==t.shading&&(i.flatShading=1===t.shading),void 0!==t.size&&(i.size=t.size),void 0!==t.sizeAttenuation&&(i.sizeAttenuation=t.sizeAttenuation),void 0!==t.map&&(i.map=n(t.map)),void 0!==t.matcap&&(i.matcap=n(t.matcap)),void 0!==t.alphaMap&&(i.alphaMap=n(t.alphaMap)),void 0!==t.bumpMap&&(i.bumpMap=n(t.bumpMap)),void 0!==t.bumpScale&&(i.bumpScale=t.bumpScale),void 0!==t.normalMap&&(i.normalMap=n(t.normalMap)),void 0!==t.normalMapType&&(i.normalMapType=t.normalMapType),void 0!==t.normalScale){let e=t.normalScale;!1===Array.isArray(e)&&(e=[e,e]),i.normalScale=(new At).fromArray(e)}return void 0!==t.displacementMap&&(i.displacementMap=n(t.displacementMap)),void 0!==t.displacementScale&&(i.displacementScale=t.displacementScale),void 0!==t.displacementBias&&(i.displacementBias=t.displacementBias),void 0!==t.roughnessMap&&(i.roughnessMap=n(t.roughnessMap)),void 0!==t.metalnessMap&&(i.metalnessMap=n(t.metalnessMap)),void 0!==t.emissiveMap&&(i.emissiveMap=n(t.emissiveMap)),void 0!==t.emissiveIntensity&&(i.emissiveIntensity=t.emissiveIntensity),void 0!==t.specularMap&&(i.specularMap=n(t.specularMap)),void 0!==t.specularIntensityMap&&(i.specularIntensityMap=n(t.specularIntensityMap)),void 0!==t.specularColorMap&&(i.specularColorMap=n(t.specularColorMap)),void 0!==t.envMap&&(i.envMap=n(t.envMap)),void 0!==t.envMapIntensity&&(i.envMapIntensity=t.envMapIntensity),void 0!==t.reflectivity&&(i.reflectivity=t.reflectivity),void 0!==t.refractionRatio&&(i.refractionRatio=t.refractionRatio),void 0!==t.lightMap&&(i.lightMap=n(t.lightMap)),void 0!==t.lightMapIntensity&&(i.lightMapIntensity=t.lightMapIntensity),void 0!==t.aoMap&&(i.aoMap=n(t.aoMap)),void 0!==t.aoMapIntensity&&(i.aoMapIntensity=t.aoMapIntensity),void 0!==t.gradientMap&&(i.gradientMap=n(t.gradientMap)),void 0!==t.clearcoatMap&&(i.clearcoatMap=n(t.clearcoatMap)),void 0!==t.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=n(t.clearcoatRoughnessMap)),void 0!==t.clearcoatNormalMap&&(i.clearcoatNormalMap=n(t.clearcoatNormalMap)),void 0!==t.clearcoatNormalScale&&(i.clearcoatNormalScale=(new At).fromArray(t.clearcoatNormalScale)),void 0!==t.transmissionMap&&(i.transmissionMap=n(t.transmissionMap)),void 0!==t.thicknessMap&&(i.thicknessMap=n(t.thicknessMap)),void 0!==t.sheenColorMap&&(i.sheenColorMap=n(t.sheenColorMap)),void 0!==t.sheenRoughnessMap&&(i.sheenRoughnessMap=n(t.sheenRoughnessMap)),i}setTextures(t){return this.textures=t,this}}class kc{static decodeText(t){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(t);let e="";for(let n=0,i=t.length;n<i;n++)e+=String.fromCharCode(t[n]);try{return decodeURIComponent(escape(e))}catch(t){return e}}static extractUrlBase(t){const e=t.lastIndexOf("/");return-1===e?"./":t.substr(0,e+1)}static resolveURL(t,e){return"string"!=typeof t||""===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 Vc extends Nn{constructor(){super(),this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(t){return super.copy(t),this.instanceCount=t.instanceCount,this}clone(){return(new this.constructor).copy(this)}toJSON(){const t=super.toJSON(this);return t.instanceCount=this.instanceCount,t.isInstancedBufferGeometry=!0,t}}Vc.prototype.isInstancedBufferGeometry=!0;class Wc extends fc{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new vc(r.manager);s.setPath(r.path),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(t,(function(n){try{e(r.parse(JSON.parse(n)))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}parse(t){const e={},n={};function i(t,i){if(void 0!==e[i])return e[i];const r=t.interleavedBuffers[i],s=function(t,e){if(void 0!==n[e])return n[e];const i=t.arrayBuffers[e],r=new Uint32Array(i).buffer;return n[e]=r,r}(t,r.buffer),a=Pt(r.type,s),o=new ua(a,r.stride);return o.uuid=r.uuid,e[i]=o,o}const r=t.isInstancedBufferGeometry?new Vc:new Nn,s=t.data.index;if(void 0!==s){const t=Pt(s.type,s.array);r.setIndex(new gn(t,1))}const a=t.data.attributes;for(const e in a){const n=a[e];let s;if(n.isInterleavedBufferAttribute){const e=i(t.data,n.data);s=new pa(e,n.itemSize,n.offset,n.normalized)}else{const t=Pt(n.type,n.array);s=new(n.isInstancedBufferAttribute?Wa:gn)(t,n.itemSize,n.normalized)}void 0!==n.name&&(s.name=n.name),void 0!==n.usage&&s.setUsage(n.usage),void 0!==n.updateRange&&(s.updateRange.offset=n.updateRange.offset,s.updateRange.count=n.updateRange.count),r.setAttribute(e,s)}const o=t.data.morphAttributes;if(o)for(const e in o){const n=o[e],s=[];for(let e=0,r=n.length;e<r;e++){const r=n[e];let a;if(r.isInterleavedBufferAttribute){const e=i(t.data,r.data);a=new pa(e,r.itemSize,r.offset,r.normalized)}else{const t=Pt(r.type,r.array);a=new gn(t,r.itemSize,r.normalized)}void 0!==r.name&&(a.name=r.name),s.push(a)}r.morphAttributes[e]=s}t.data.morphTargetsRelative&&(r.morphTargetsRelative=!0);const l=t.data.groups||t.data.drawcalls||t.data.offsets;if(void 0!==l)for(let t=0,e=l.length;t!==e;++t){const e=l[t];r.addGroup(e.start,e.count,e.materialIndex)}const c=t.data.boundingSphere;if(void 0!==c){const t=new Zt;void 0!==c.center&&t.fromArray(c.center),r.boundingSphere=new ye(t,c.radius)}return t.name&&(r.name=t.name),t.userData&&(r.userData=t.userData),r}}const jc={UVMapping:i,CubeReflectionMapping:r,CubeRefractionMapping:s,EquirectangularReflectionMapping:a,EquirectangularRefractionMapping:o,CubeUVReflectionMapping:l,CubeUVRefractionMapping:c},qc={RepeatWrapping:h,ClampToEdgeWrapping:u,MirroredRepeatWrapping:d},Xc={NearestFilter:p,NearestMipmapNearestFilter:m,NearestMipmapLinearFilter:f,LinearFilter:g,LinearMipmapNearestFilter:v,LinearMipmapLinearFilter:y};class Jc extends fc{constructor(t){super(t),"undefined"==typeof createImageBitmap&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),"undefined"==typeof fetch&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"}}setOptions(t){return this.options=t,this}load(t,e,n,i){void 0===t&&(t=""),void 0!==this.path&&(t=this.path+t),t=this.manager.resolveURL(t);const r=this,s=dc.get(t);if(void 0!==s)return r.manager.itemStart(t),setTimeout((function(){e&&e(s),r.manager.itemEnd(t)}),0),s;const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader,fetch(t,a).then((function(t){return t.blob()})).then((function(t){return createImageBitmap(t,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(n){dc.add(t,n),e&&e(n),r.manager.itemEnd(t)})).catch((function(e){i&&i(e),r.manager.itemError(t),r.manager.itemEnd(t)})),r.manager.itemStart(t)}}let Yc;Jc.prototype.isImageBitmapLoader=!0;const Zc={getContext:function(){return void 0===Yc&&(Yc=new(window.AudioContext||window.webkitAudioContext)),Yc},setContext:function(t){Yc=t}};class Kc extends fc{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new vc(this.manager);s.setResponseType("arraybuffer"),s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(t,(function(n){try{const t=n.slice(0);Zc.getContext().decodeAudioData(t,(function(t){e(t)}))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}}class Qc extends Hc{constructor(t,e,n=1){super(void 0,n);const i=(new Ut).set(t),r=(new Ut).set(e),s=new Zt(i.r,i.g,i.b),a=new Zt(r.r,r.g,r.b),o=Math.sqrt(Math.PI),l=o*Math.sqrt(.75);this.sh.coefficients[0].copy(s).add(a).multiplyScalar(o),this.sh.coefficients[1].copy(s).sub(a).multiplyScalar(l)}}Qc.prototype.isHemisphereLightProbe=!0;class $c extends Hc{constructor(t,e=1){super(void 0,e);const n=(new Ut).set(t);this.sh.coefficients[0].set(n.r,n.g,n.b).multiplyScalar(2*Math.sqrt(Math.PI))}}$c.prototype.isAmbientLightProbe=!0;const th=new Ae,eh=new Ae,nh=new Ae;class ih{constructor(t=!0){this.autoStart=t,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=rh(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let t=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const e=rh();t=(e-this.oldTime)/1e3,this.oldTime=e,this.elapsedTime+=t}return t}}function rh(){return("undefined"==typeof performance?Date:performance).now()}const sh=new Zt,ah=new Yt,oh=new Zt,lh=new Zt;class ch extends Qe{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(!0===this.isPlaying)return void console.warn("THREE.Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void console.warn("THREE.Audio: this Audio has no playback control.");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(!1!==this.hasPlaybackControl)return!0===this.isPlaying&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,!0===this.loop&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this;console.warn("THREE.Audio: this Audio has no playback control.")}stop(){if(!1!==this.hasPlaybackControl)return this._progress=0,this.source.stop(),this.source.onended=null,this.isPlaying=!1,this;console.warn("THREE.Audio: this Audio has no playback control.")}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let t=1,e=this.filters.length;t<e;t++)this.filters[t-1].connect(this.filters[t]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this._connected=!0,this}disconnect(){if(this.filters.length>0){this.source.disconnect(this.filters[0]);for(let t=1,e=this.filters.length;t<e;t++)this.filters[t-1].disconnect(this.filters[t]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this._connected=!1,this}getFilters(){return this.filters}setFilters(t){return t||(t=[]),!0===this._connected?(this.disconnect(),this.filters=t.slice(),this.connect()):this.filters=t.slice(),this}setDetune(t){if(this.detune=t,void 0!==this.source.detune)return!0===this.isPlaying&&this.source.detune.setTargetAtTime(this.detune,this.context.currentTime,.01),this}getDetune(){return this.detune}getFilter(){return this.getFilters()[0]}setFilter(t){return this.setFilters(t?[t]:[])}setPlaybackRate(t){if(!1!==this.hasPlaybackControl)return this.playbackRate=t,!0===this.isPlaying&&this.source.playbackRate.setTargetAtTime(this.playbackRate,this.context.currentTime,.01),this;console.warn("THREE.Audio: this Audio has no playback control.")}getPlaybackRate(){return this.playbackRate}onEnded(){this.isPlaying=!1}getLoop(){return!1===this.hasPlaybackControl?(console.warn("THREE.Audio: this Audio has no playback control."),!1):this.loop}setLoop(t){if(!1!==this.hasPlaybackControl)return this.loop=t,!0===this.isPlaying&&(this.source.loop=this.loop),this;console.warn("THREE.Audio: this Audio has no playback control.")}setLoopStart(t){return this.loopStart=t,this}setLoopEnd(t){return this.loopEnd=t,this}getVolume(){return this.gain.gain.value}setVolume(t){return this.gain.gain.setTargetAtTime(t,this.context.currentTime,.01),this}}const hh=new Zt,uh=new Yt,dh=new Zt,ph=new Zt;class mh{constructor(t,e=2048){this.analyser=t.context.createAnalyser(),this.analyser.fftSize=e,this.data=new Uint8Array(this.analyser.frequencyBinCount),t.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let t=0;const e=this.getFrequencyData();for(let n=0;n<e.length;n++)t+=e[n];return t/e.length}}class fh{constructor(t,e,n){let i,r,s;switch(this.binding=t,this.valueSize=n,e){case"quaternion":i=this._slerp,r=this._slerpAdditive,s=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(6*n),this._workIndex=5;break;case"string":case"bool":i=this._select,r=this._select,s=this._setAdditiveIdentityOther,this.buffer=new Array(5*n);break;default:i=this._lerp,r=this._lerpAdditive,s=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(5*n)}this._mixBufferRegion=i,this._mixBufferRegionAdditive=r,this._setIdentity=s,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(t,e){const n=this.buffer,i=this.valueSize,r=t*i+i;let s=this.cumulativeWeight;if(0===s){for(let t=0;t!==i;++t)n[r+t]=n[t];s=e}else{s+=e;const t=e/s;this._mixBufferRegion(n,r,0,t,i)}this.cumulativeWeight=s}accumulateAdditive(t){const e=this.buffer,n=this.valueSize,i=n*this._addIndex;0===this.cumulativeWeightAdditive&&this._setIdentity(),this._mixBufferRegionAdditive(e,i,0,t,n),this.cumulativeWeightAdditive+=t}apply(t){const e=this.valueSize,n=this.buffer,i=t*e+e,r=this.cumulativeWeight,s=this.cumulativeWeightAdditive,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,r<1){const t=e*this._origIndex;this._mixBufferRegion(n,i,t,1-r,e)}s>0&&this._mixBufferRegionAdditive(n,i,this._addIndex*e,1,e);for(let t=e,r=e+e;t!==r;++t)if(n[t]!==n[t+e]){a.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 t=n,r=i;t!==r;++t)e[t]=e[i+t%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const t=3*this.valueSize;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){const t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let n=t;n<e;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){const t=this._origIndex*this.valueSize,e=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[e+n]=this.buffer[t+n]}_select(t,e,n,i,r){if(i>=.5)for(let i=0;i!==r;++i)t[e+i]=t[n+i]}_slerp(t,e,n,i){Yt.slerpFlat(t,e,t,e,t,n,i)}_slerpAdditive(t,e,n,i,r){const s=this._workIndex*r;Yt.multiplyQuaternionsFlat(t,s,t,e,t,n),Yt.slerpFlat(t,e,t,e,t,s,i)}_lerp(t,e,n,i,r){const s=1-i;for(let a=0;a!==r;++a){const r=e+a;t[r]=t[r]*s+t[n+a]*i}}_lerpAdditive(t,e,n,i,r){for(let s=0;s!==r;++s){const r=e+s;t[r]=t[r]+t[n+s]*i}}}const gh="\\[\\]\\.:\\/",vh=new RegExp("[\\[\\]\\.:\\/]","g"),yh="[^\\[\\]\\.:\\/]",xh="[^"+gh.replace("\\.","")+"]",_h=/((?:WC+[\/:])*)/.source.replace("WC",yh),Mh=/(WCOD+)?/.source.replace("WCOD",xh),bh=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",yh),wh=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",yh),Sh=new RegExp("^"+_h+Mh+bh+wh+"$"),Th=["material","materials","bones"];class Eh{constructor(t,e,n){this.path=e,this.parsedPath=n||Eh.parseTrackName(e),this.node=Eh.findNode(t,this.parsedPath.nodeName)||t,this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,n){return t&&t.isAnimationObjectGroup?new Eh.Composite(t,e,n):new Eh(t,e,n)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(vh,"")}static parseTrackName(t){const e=Sh.exec(t);if(!e)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(void 0!==i&&-1!==i){const t=n.nodeName.substring(i+1);-1!==Th.indexOf(t)&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=t)}if(null===n.propertyName||0===n.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return n}static findNode(t,e){if(!e||""===e||"."===e||-1===e||e===t.name||e===t.uuid)return t;if(t.skeleton){const n=t.skeleton.getBoneByName(e);if(void 0!==n)return n}if(t.children){const n=function(t){for(let i=0;i<t.length;i++){const r=t[i];if(r.name===e||r.uuid===e)return r;const s=n(r.children);if(s)return s}return null},i=n(t.children);if(i)return i}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(t,e){t[e]=this.targetObject[this.propertyName]}_getValue_array(t,e){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)t[e++]=n[i]}_getValue_arrayElement(t,e){t[e]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(t,e){this.resolvedProperty.toArray(t,e)}_setValue_direct(t,e){this.targetObject[this.propertyName]=t[e]}_setValue_direct_setNeedsUpdate(t,e){this.targetObject[this.propertyName]=t[e],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(t,e){this.targetObject[this.propertyName]=t[e],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(t,e){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=t[e++]}_setValue_array_setNeedsUpdate(t,e){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=t[e++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(t,e){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=t[e++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(t,e){this.resolvedProperty[this.propertyIndex]=t[e]}_setValue_arrayElement_setNeedsUpdate(t,e){this.resolvedProperty[this.propertyIndex]=t[e],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(t,e){this.resolvedProperty[this.propertyIndex]=t[e],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(t,e){this.resolvedProperty.fromArray(t,e)}_setValue_fromArray_setNeedsUpdate(t,e){this.resolvedProperty.fromArray(t,e),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(t,e){this.resolvedProperty.fromArray(t,e),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(t,e){this.bind(),this.getValue(t,e)}_setValue_unbound(t,e){this.bind(),this.setValue(t,e)}bind(){let t=this.node;const e=this.parsedPath,n=e.objectName,i=e.propertyName;let r=e.propertyIndex;if(t||(t=Eh.findNode(this.rootNode,e.nodeName)||this.rootNode,this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t)return void console.error("THREE.PropertyBinding: Trying to update node for track: "+this.path+" but it wasn't found.");if(n){let i=e.objectIndex;switch(n){case"materials":if(!t.material)return void console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);if(!t.material.materials)return void console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);t=t.material.materials;break;case"bones":if(!t.skeleton)return void console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);t=t.skeleton.bones;for(let e=0;e<t.length;e++)if(t[e].name===i){i=e;break}break;default:if(void 0===t[n])return void console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);t=t[n]}if(void 0!==i){if(void 0===t[i])return void console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,t);t=t[i]}}const s=t[i];if(void 0===s){const n=e.nodeName;return void console.error("THREE.PropertyBinding: Trying to update property for track: "+n+"."+i+" but it wasn't found.",t)}let a=this.Versioning.None;this.targetObject=t,void 0!==t.needsUpdate?a=this.Versioning.NeedsUpdate:void 0!==t.matrixWorldNeedsUpdate&&(a=this.Versioning.MatrixWorldNeedsUpdate);let o=this.BindingType.Direct;if(void 0!==r){if("morphTargetInfluences"===i){if(!t.geometry)return void console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);if(!t.geometry.isBufferGeometry)return void console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.",this);if(!t.geometry.morphAttributes)return void console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);void 0!==t.morphTargetDictionary[r]&&(r=t.morphTargetDictionary[r])}o=this.BindingType.ArrayElement,this.resolvedProperty=s,this.propertyIndex=r}else void 0!==s.fromArray&&void 0!==s.toArray?(o=this.BindingType.HasFromToArray,this.resolvedProperty=s):Array.isArray(s)?(o=this.BindingType.EntireArray,this.resolvedProperty=s):this.propertyName=i;this.getValue=this.GetterByBindingType[o],this.setValue=this.SetterByBindingTypeAndVersioning[o][a]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}Eh.Composite=class{constructor(t,e,n){const i=n||Eh.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];void 0!==i&&i.getValue(t,e)}setValue(t,e){const n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,r=n.length;i!==r;++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()}},Eh.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Eh.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},Eh.prototype.GetterByBindingType=[Eh.prototype._getValue_direct,Eh.prototype._getValue_array,Eh.prototype._getValue_arrayElement,Eh.prototype._getValue_toArray],Eh.prototype.SetterByBindingTypeAndVersioning=[[Eh.prototype._setValue_direct,Eh.prototype._setValue_direct_setNeedsUpdate,Eh.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Eh.prototype._setValue_array,Eh.prototype._setValue_array_setNeedsUpdate,Eh.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Eh.prototype._setValue_arrayElement,Eh.prototype._setValue_arrayElement_setNeedsUpdate,Eh.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Eh.prototype._setValue_fromArray,Eh.prototype._setValue_fromArray_setNeedsUpdate,Eh.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class Ah{constructor(){this.uuid=xt(),this._objects=Array.prototype.slice.call(arguments),this.nCachedObjects_=0;const t={};this._indicesByUUID=t;for(let e=0,n=arguments.length;e!==n;++e)t[arguments[e].uuid]=e;this._paths=[],this._parsedPaths=[],this._bindings=[],this._bindingsIndicesByPath={};const e=this;this.stats={objects:{get total(){return e._objects.length},get inUse(){return this.total-e.nCachedObjects_}},get bindingsPerObject(){return e._bindings.length}}}add(){const t=this._objects,e=this._indicesByUUID,n=this._paths,i=this._parsedPaths,r=this._bindings,s=r.length;let a,o=t.length,l=this.nCachedObjects_;for(let c=0,h=arguments.length;c!==h;++c){const h=arguments[c],u=h.uuid;let d=e[u];if(void 0===d){d=o++,e[u]=d,t.push(h);for(let t=0,e=s;t!==e;++t)r[t].push(new Eh(h,n[t],i[t]))}else if(d<l){a=t[d];const o=--l,c=t[o];e[c.uuid]=d,t[d]=c,e[u]=o,t[o]=h;for(let t=0,e=s;t!==e;++t){const e=r[t],s=e[o];let a=e[d];e[d]=s,void 0===a&&(a=new Eh(h,n[t],i[t])),e[o]=a}}else t[d]!==a&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=l}remove(){const t=this._objects,e=this._indicesByUUID,n=this._bindings,i=n.length;let r=this.nCachedObjects_;for(let s=0,a=arguments.length;s!==a;++s){const a=arguments[s],o=a.uuid,l=e[o];if(void 0!==l&&l>=r){const s=r++,c=t[s];e[c.uuid]=l,t[l]=c,e[o]=s,t[s]=a;for(let t=0,e=i;t!==e;++t){const e=n[t],i=e[s],r=e[l];e[l]=i,e[s]=r}}}this.nCachedObjects_=r}uncache(){const t=this._objects,e=this._indicesByUUID,n=this._bindings,i=n.length;let r=this.nCachedObjects_,s=t.length;for(let a=0,o=arguments.length;a!==o;++a){const o=arguments[a].uuid,l=e[o];if(void 0!==l)if(delete e[o],l<r){const a=--r,o=t[a],c=--s,h=t[c];e[o.uuid]=l,t[l]=o,e[h.uuid]=a,t[a]=h,t.pop();for(let t=0,e=i;t!==e;++t){const e=n[t],i=e[a],r=e[c];e[l]=i,e[a]=r,e.pop()}}else{const r=--s,a=t[r];r>0&&(e[a.uuid]=l),t[l]=a,t.pop();for(let t=0,e=i;t!==e;++t){const e=n[t];e[l]=e[r],e.pop()}}}this.nCachedObjects_=r}subscribe_(t,e){const n=this._bindingsIndicesByPath;let i=n[t];const r=this._bindings;if(void 0!==i)return r[i];const s=this._paths,a=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,h=new Array(l);i=r.length,n[t]=i,s.push(t),a.push(e),r.push(h);for(let n=c,i=o.length;n!==i;++n){const i=o[n];h[n]=new Eh(i,t,e)}return h}unsubscribe_(t){const e=this._bindingsIndicesByPath,n=e[t];if(void 0!==n){const i=this._paths,r=this._parsedPaths,s=this._bindings,a=s.length-1,o=s[a];e[t[a]]=n,s[n]=o,s.pop(),r[n]=r[a],r.pop(),i[n]=i[a],i.pop()}}}Ah.prototype.isAnimationObjectGroup=!0;class Rh{constructor(t,e,n=null,i=e.blendMode){this._mixer=t,this._clip=e,this._localRoot=n,this.blendMode=i;const r=e.tracks,s=r.length,a=new Array(s),o={endingStart:nt,endingEnd:nt};for(let t=0;t!==s;++t){const e=r[t].createInterpolant(null);a[t]=e,e.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(s),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,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&&0!==this.timeScale&&null===this._startTime&&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){if(t.fadeOut(e),this.fadeIn(e),n){const n=this._clip.duration,i=t._clip.duration,r=i/n,s=n/i;t.warp(1,r,e),this.warp(s,1,e)}return this}crossFadeTo(t,e,n){return t.crossFadeFrom(this,e,n)}stopFading(){const t=this._weightInterpolant;return null!==t&&(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,r=i.time,s=this.timeScale;let a=this._timeScaleInterpolant;null===a&&(a=i._lendControlInterpolant(),this._timeScaleInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=r,o[1]=r+n,l[0]=t/s,l[1]=e/s,this}stopWarping(){const t=this._timeScaleInterpolant;return null!==t&&(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)return void this._updateWeight(t);const r=this._startTime;if(null!==r){const i=(t-r)*n;if(i<0||0===n)return;this._startTime=null,e=n*i}e*=this._updateTimeScale(t);const s=this._updateTime(e),a=this._updateWeight(t);if(a>0){const t=this._interpolants,e=this._propertyBindings;if(this.blendMode===at)for(let n=0,i=t.length;n!==i;++n)t[n].evaluate(s),e[n].accumulateAdditive(a);else for(let n=0,r=t.length;n!==r;++n)t[n].evaluate(s),e[n].accumulate(i,a)}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;const n=this._weightInterpolant;if(null!==n){const i=n.evaluate(t)[0];e*=i,t>n.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;const n=this._timeScaleInterpolant;if(null!==n){e*=n.evaluate(t)[0],t>n.parameterPositions[1]&&(this.stopWarping(),0===e?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,r=this._loopCount;const s=2202===n;if(0===t)return-1===r?i:s&&1==(1&r)?e-i:i;if(2200===n){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(i>=e)i=e;else{if(!(i<0)){this.time=i;break t}i=0}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(-1===r&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,s)):this._setEndings(0===this.repetitions,!0,s)),i>=e||i<0){const n=Math.floor(i/e);i-=e*n,r+=Math.abs(n);const a=this.repetitions-r;if(a<=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(1===a){const e=t<0;this._setEndings(e,!e,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:n})}}else this.time=i;if(s&&1==(1&r))return e-i}return i}_setEndings(t,e,n){const i=this._interpolantSettings;n?(i.endingStart=it,i.endingEnd=it):(i.endingStart=t?this.zeroSlopeAtStart?it:nt:rt,i.endingEnd=e?this.zeroSlopeAtEnd?it:nt:rt)}_scheduleFading(t,e,n){const i=this._mixer,r=i.time;let s=this._weightInterpolant;null===s&&(s=i._lendControlInterpolant(),this._weightInterpolant=s);const a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=e,a[1]=r+t,o[1]=n,this}}class Lh extends mt{constructor(t){super(),this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(t,e){const n=t._localRoot||this._root,i=t._clip.tracks,r=i.length,s=t._propertyBindings,a=t._interpolants,o=n.uuid,l=this._bindingsByRootAndName;let c=l[o];void 0===c&&(c={},l[o]=c);for(let t=0;t!==r;++t){const r=i[t],l=r.name;let h=c[l];if(void 0!==h)++h.referenceCount,s[t]=h;else{if(h=s[t],void 0!==h){null===h._cacheIndex&&(++h.referenceCount,this._addInactiveBinding(h,o,l));continue}const i=e&&e._propertyBindings[t].binding.parsedPath;h=new fh(Eh.create(n,l,i),r.ValueTypeName,r.getValueSize()),++h.referenceCount,this._addInactiveBinding(h,o,l),s[t]=h}a[t].resultBuffer=h.buffer}}_activateAction(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){const e=(t._localRoot||this._root).uuid,n=t._clip.uuid,i=this._actionsByClip[n];this._bindAction(t,i&&i.knownActions[0]),this._addInactiveAction(t,n,e)}const e=t._propertyBindings;for(let t=0,n=e.length;t!==n;++t){const n=e[t];0==n.useCount++&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(t)}}_deactivateAction(t){if(this._isActiveAction(t)){const e=t._propertyBindings;for(let t=0,n=e.length;t!==n;++t){const n=e[t];0==--n.useCount&&(n.restoreOriginalState(),this._takeBackBinding(n))}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 null!==e&&e<this._nActiveActions}_addInactiveAction(t,e,n){const i=this._actions,r=this._actionsByClip;let s=r[e];if(void 0===s)s={knownActions:[t],actionByRoot:{}},t._byClipCacheIndex=0,r[e]=s;else{const e=s.knownActions;t._byClipCacheIndex=e.length,e.push(t)}t._cacheIndex=i.length,i.push(t),s.actionByRoot[n]=t}_removeInactiveAction(t){const e=this._actions,n=e[e.length-1],i=t._cacheIndex;n._cacheIndex=i,e[i]=n,e.pop(),t._cacheIndex=null;const r=t._clip.uuid,s=this._actionsByClip,a=s[r],o=a.knownActions,l=o[o.length-1],c=t._byClipCacheIndex;l._byClipCacheIndex=c,o[c]=l,o.pop(),t._byClipCacheIndex=null;delete a.actionByRoot[(t._localRoot||this._root).uuid],0===o.length&&delete s[r],this._removeInactiveBindingsForAction(t)}_removeInactiveBindingsForAction(t){const e=t._propertyBindings;for(let t=0,n=e.length;t!==n;++t){const n=e[t];0==--n.referenceCount&&this._removeInactiveBinding(n)}}_lendAction(t){const e=this._actions,n=t._cacheIndex,i=this._nActiveActions++,r=e[i];t._cacheIndex=i,e[i]=t,r._cacheIndex=n,e[n]=r}_takeBackAction(t){const e=this._actions,n=t._cacheIndex,i=--this._nActiveActions,r=e[i];t._cacheIndex=i,e[i]=t,r._cacheIndex=n,e[n]=r}_addInactiveBinding(t,e,n){const i=this._bindingsByRootAndName,r=this._bindings;let s=i[e];void 0===s&&(s={},i[e]=s),s[n]=t,t._cacheIndex=r.length,r.push(t)}_removeInactiveBinding(t){const e=this._bindings,n=t.binding,i=n.rootNode.uuid,r=n.path,s=this._bindingsByRootAndName,a=s[i],o=e[e.length-1],l=t._cacheIndex;o._cacheIndex=l,e[l]=o,e.pop(),delete a[r],0===Object.keys(a).length&&delete s[i]}_lendBinding(t){const e=this._bindings,n=t._cacheIndex,i=this._nActiveBindings++,r=e[i];t._cacheIndex=i,e[i]=t,r._cacheIndex=n,e[n]=r}_takeBackBinding(t){const e=this._bindings,n=t._cacheIndex,i=--this._nActiveBindings,r=e[i];t._cacheIndex=i,e[i]=t,r._cacheIndex=n,e[n]=r}_lendControlInterpolant(){const t=this._controlInterpolants,e=this._nActiveControlInterpolants++;let n=t[e];return void 0===n&&(n=new tc(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer),n.__cacheIndex=e,t[e]=n),n}_takeBackControlInterpolant(t){const e=this._controlInterpolants,n=t.__cacheIndex,i=--this._nActiveControlInterpolants,r=e[i];t.__cacheIndex=i,e[i]=t,r.__cacheIndex=n,e[n]=r}clipAction(t,e,n){const i=e||this._root,r=i.uuid;let s="string"==typeof t?hc.findByName(i,t):t;const a=null!==s?s.uuid:t,o=this._actionsByClip[a];let l=null;if(void 0===n&&(n=null!==s?s.blendMode:st),void 0!==o){const t=o.actionByRoot[r];if(void 0!==t&&t.blendMode===n)return t;l=o.knownActions[0],null===s&&(s=l._clip)}if(null===s)return null;const c=new Rh(this,s,e,n);return this._bindAction(c,l),this._addInactiveAction(c,a,r),c}existingAction(t,e){const n=e||this._root,i=n.uuid,r="string"==typeof t?hc.findByName(n,t):t,s=r?r.uuid:t,a=this._actionsByClip[s];return void 0!==a&&a.actionByRoot[i]||null}stopAllAction(){const t=this._actions;for(let e=this._nActiveActions-1;e>=0;--e)t[e].stop();return this}update(t){t*=this.timeScale;const e=this._actions,n=this._nActiveActions,i=this.time+=t,r=Math.sign(t),s=this._accuIndex^=1;for(let a=0;a!==n;++a){e[a]._update(i,t,r,s)}const a=this._bindings,o=this._nActiveBindings;for(let t=0;t!==o;++t)a[t].apply(s);return this}setTime(t){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(t)}getRoot(){return this._root}uncacheClip(t){const e=this._actions,n=t.uuid,i=this._actionsByClip,r=i[n];if(void 0!==r){const t=r.knownActions;for(let n=0,i=t.length;n!==i;++n){const i=t[n];this._deactivateAction(i);const r=i._cacheIndex,s=e[e.length-1];i._cacheIndex=null,i._byClipCacheIndex=null,s._cacheIndex=r,e[r]=s,e.pop(),this._removeInactiveBindingsForAction(i)}delete i[n]}}uncacheRoot(t){const e=t.uuid,n=this._actionsByClip;for(const t in n){const i=n[t].actionByRoot[e];void 0!==i&&(this._deactivateAction(i),this._removeInactiveAction(i))}const i=this._bindingsByRootAndName[e];if(void 0!==i)for(const t in i){const e=i[t];e.restoreOriginalState(),this._removeInactiveBinding(e)}}uncacheAction(t,e){const n=this.existingAction(t,e);null!==n&&(this._deactivateAction(n),this._removeInactiveAction(n))}}Lh.prototype._controlInterpolantsResultBuffer=new Float32Array(1);class Ch{constructor(t){"string"==typeof t&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),t=arguments[1]),this.value=t}clone(){return new Ch(void 0===this.value.clone?this.value:this.value.clone())}}class Ph extends ua{constructor(t,e,n=1){super(t,e),this.meshPerAttribute=n}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}clone(t){const e=super.clone(t);return e.meshPerAttribute=this.meshPerAttribute,e}toJSON(t){const e=super.toJSON(t);return e.isInstancedInterleavedBuffer=!0,e.meshPerAttribute=this.meshPerAttribute,e}}Ph.prototype.isInstancedInterleavedBuffer=!0;class Dh{constructor(t,e,n,i,r){this.buffer=t,this.type=e,this.itemSize=n,this.elementSize=i,this.count=r,this.version=0}set needsUpdate(t){!0===t&&this.version++}setBuffer(t){return this.buffer=t,this}setType(t,e){return this.type=t,this.elementSize=e,this}setItemSize(t){return this.itemSize=t,this}setCount(t){return this.count=t,this}}Dh.prototype.isGLBufferAttribute=!0;function Ih(t,e){return t.distance-e.distance}function Nh(t,e,n,i){if(t.layers.test(e.layers)&&t.raycast(e,n),!0===i){const i=t.children;for(let t=0,r=i.length;t<r;t++)Nh(i[t],e,n,!0)}}const Bh=new At;class zh{constructor(t=new At(1/0,1/0),e=new At(-1/0,-1/0)){this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromPoints(t){this.makeEmpty();for(let e=0,n=t.length;e<n;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const n=Bh.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(n),this.max.copy(t).add(n),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y}getCenter(t){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}containsPoint(t){return!(t.x<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 Bh.copy(t).clamp(this.min,this.max).sub(t).length()}intersect(t){return this.min.max(t.min),this.max.min(t.max),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)}}zh.prototype.isBox2=!0;const Oh=new Zt,Fh=new Zt;class Uh{constructor(t=new Zt,e=new Zt){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){Oh.subVectors(t,this.start),Fh.subVectors(this.end,this.start);const n=Fh.dot(Fh);let i=Fh.dot(Oh)/n;return e&&(i=_t(i,0,1)),i}closestPointToPoint(t,e,n){const i=this.closestPointToPointParameter(t,e);return this.delta(n).multiplyScalar(i).add(this.start)}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 Hh=new Zt;const Gh=new Zt,kh=new Ae,Vh=new Ae;class Wh extends so{constructor(t){const e=jh(t),n=new Nn,i=[],r=[],s=new Ut(0,0,1),a=new Ut(0,1,0);for(let t=0;t<e.length;t++){const n=e[t];n.parent&&n.parent.isBone&&(i.push(0,0,0),i.push(0,0,0),r.push(s.r,s.g,s.b),r.push(a.r,a.g,a.b))}n.setAttribute("position",new Tn(i,3)),n.setAttribute("color",new Tn(r,3));super(n,new Za({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0})),this.type="SkeletonHelper",this.isSkeletonHelper=!0,this.root=t,this.bones=e,this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1}updateMatrixWorld(t){const e=this.bones,n=this.geometry,i=n.getAttribute("position");Vh.copy(this.root.matrixWorld).invert();for(let t=0,n=0;t<e.length;t++){const r=e[t];r.parent&&r.parent.isBone&&(kh.multiplyMatrices(Vh,r.matrixWorld),Gh.setFromMatrixPosition(kh),i.setXYZ(n,Gh.x,Gh.y,Gh.z),kh.multiplyMatrices(Vh,r.parent.matrixWorld),Gh.setFromMatrixPosition(kh),i.setXYZ(n+1,Gh.x,Gh.y,Gh.z),n+=2)}n.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(t)}}function jh(t){const e=[];t&&t.isBone&&e.push(t);for(let n=0;n<t.children.length;n++)e.push.apply(e,jh(t.children[n]));return e}const qh=new Zt,Xh=new Ut,Jh=new Ut;class Yh extends so{constructor(t=10,e=10,n=4473924,i=8947848){n=new Ut(n),i=new Ut(i);const r=e/2,s=t/e,a=t/2,o=[],l=[];for(let t=0,c=0,h=-a;t<=e;t++,h+=s){o.push(-a,0,h,a,0,h),o.push(h,0,-a,h,0,a);const e=t===r?n:i;e.toArray(l,c),c+=3,e.toArray(l,c),c+=3,e.toArray(l,c),c+=3,e.toArray(l,c),c+=3}const c=new Nn;c.setAttribute("position",new Tn(o,3)),c.setAttribute("color",new Tn(l,3));super(c,new Za({vertexColors:!0,toneMapped:!1})),this.type="GridHelper"}}const Zh=new Zt,Kh=new Zt,Qh=new Zt;const $h=new Zt,tu=new si;function eu(t,e,n,i,r,s,a){$h.set(r,s,a).unproject(i);const o=e[t];if(void 0!==o){const t=n.getAttribute("position");for(let e=0,n=o.length;e<n;e++)t.setXYZ(o[e],$h.x,$h.y,$h.z)}}const nu=new $t;class iu extends so{constructor(t,e=16776960){const n=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]),i=new Float32Array(24),r=new Nn;r.setIndex(new gn(n,1)),r.setAttribute("position",new gn(i,3)),super(r,new Za({color:e,toneMapped:!1})),this.object=t,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(t){if(void 0!==t&&console.warn("THREE.BoxHelper: .update() has no longer arguments."),void 0!==this.object&&nu.setFromObject(this.object),nu.isEmpty())return;const e=nu.min,n=nu.max,i=this.geometry.attributes.position,r=i.array;r[0]=n.x,r[1]=n.y,r[2]=n.z,r[3]=e.x,r[4]=n.y,r[5]=n.z,r[6]=e.x,r[7]=e.y,r[8]=n.z,r[9]=n.x,r[10]=e.y,r[11]=n.z,r[12]=n.x,r[13]=n.y,r[14]=e.z,r[15]=e.x,r[16]=n.y,r[17]=e.z,r[18]=e.x,r[19]=e.y,r[20]=e.z,r[21]=n.x,r[22]=e.y,r[23]=e.z,i.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(t){return this.object=t,this.update(),this}copy(t){return so.prototype.copy.call(this,t),this.object=t.object,this}}const ru=new Zt;let su,au;class ou extends so{constructor(t=1){const e=[0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t],n=new Nn;n.setAttribute("position",new Tn(e,3)),n.setAttribute("color",new Tn([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(n,new Za({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(t,e,n){const i=new Ut,r=this.geometry.attributes.color.array;return i.set(t),i.toArray(r,0),i.toArray(r,3),i.set(e),i.toArray(r,6),i.toArray(r,9),i.set(n),i.toArray(r,12),i.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}const lu=new Float32Array(1),cu=new Int32Array(lu.buffer);Lo.create=function(t,e){return console.log("THREE.Curve.create() has been deprecated"),t.prototype=Object.create(Lo.prototype),t.prototype.constructor=t,t.prototype.getPoint=e,t},Zo.prototype.fromPoints=function(t){return console.warn("THREE.Path: .fromPoints() has been renamed to .setFromPoints()."),this.setFromPoints(t)},Yh.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")},Wh.prototype.update=function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.")},fc.prototype.extractUrlBase=function(t){return console.warn("THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead."),kc.extractUrlBase(t)},fc.Handlers={add:function(){console.error("THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.")},get:function(){console.error("THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.")}},zh.prototype.center=function(t){return console.warn("THREE.Box2: .center() has been renamed to .getCenter()."),this.getCenter(t)},zh.prototype.empty=function(){return console.warn("THREE.Box2: .empty() has been renamed to .isEmpty()."),this.isEmpty()},zh.prototype.isIntersectionBox=function(t){return console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox()."),this.intersectsBox(t)},zh.prototype.size=function(t){return console.warn("THREE.Box2: .size() has been renamed to .getSize()."),this.getSize(t)},$t.prototype.center=function(t){return console.warn("THREE.Box3: .center() has been renamed to .getCenter()."),this.getCenter(t)},$t.prototype.empty=function(){return console.warn("THREE.Box3: .empty() has been renamed to .isEmpty()."),this.isEmpty()},$t.prototype.isIntersectionBox=function(t){return console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox()."),this.intersectsBox(t)},$t.prototype.isIntersectionSphere=function(t){return console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere()."),this.intersectsSphere(t)},$t.prototype.size=function(t){return console.warn("THREE.Box3: .size() has been renamed to .getSize()."),this.getSize(t)},ye.prototype.empty=function(){return console.warn("THREE.Sphere: .empty() has been renamed to .isEmpty()."),this.isEmpty()},vi.prototype.setFromMatrix=function(t){return console.warn("THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix()."),this.setFromProjectionMatrix(t)},Uh.prototype.center=function(t){return console.warn("THREE.Line3: .center() has been renamed to .getCenter()."),this.getCenter(t)},Rt.prototype.flattenToArrayOffset=function(t,e){return console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead."),this.toArray(t,e)},Rt.prototype.multiplyVector3=function(t){return console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead."),t.applyMatrix3(this)},Rt.prototype.multiplyVector3Array=function(){console.error("THREE.Matrix3: .multiplyVector3Array() has been removed.")},Rt.prototype.applyToBufferAttribute=function(t){return console.warn("THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead."),t.applyMatrix3(this)},Rt.prototype.applyToVector3Array=function(){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")},Rt.prototype.getInverse=function(t){return console.warn("THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead."),this.copy(t).invert()},Ae.prototype.extractPosition=function(t){return console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(t)},Ae.prototype.flattenToArrayOffset=function(t,e){return console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead."),this.toArray(t,e)},Ae.prototype.getPosition=function(){return console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead."),(new Zt).setFromMatrixColumn(this,3)},Ae.prototype.setRotationFromQuaternion=function(t){return console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion()."),this.makeRotationFromQuaternion(t)},Ae.prototype.multiplyToArray=function(){console.warn("THREE.Matrix4: .multiplyToArray() has been removed.")},Ae.prototype.multiplyVector3=function(t){return console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead."),t.applyMatrix4(this)},Ae.prototype.multiplyVector4=function(t){return console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead."),t.applyMatrix4(this)},Ae.prototype.multiplyVector3Array=function(){console.error("THREE.Matrix4: .multiplyVector3Array() has been removed.")},Ae.prototype.rotateAxis=function(t){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead."),t.transformDirection(this)},Ae.prototype.crossVector=function(t){return console.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead."),t.applyMatrix4(this)},Ae.prototype.translate=function(){console.error("THREE.Matrix4: .translate() has been removed.")},Ae.prototype.rotateX=function(){console.error("THREE.Matrix4: .rotateX() has been removed.")},Ae.prototype.rotateY=function(){console.error("THREE.Matrix4: .rotateY() has been removed.")},Ae.prototype.rotateZ=function(){console.error("THREE.Matrix4: .rotateZ() has been removed.")},Ae.prototype.rotateByAxis=function(){console.error("THREE.Matrix4: .rotateByAxis() has been removed.")},Ae.prototype.applyToBufferAttribute=function(t){return console.warn("THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead."),t.applyMatrix4(this)},Ae.prototype.applyToVector3Array=function(){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.")},Ae.prototype.makeFrustum=function(t,e,n,i,r,s){return console.warn("THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead."),this.makePerspective(t,e,i,n,r,s)},Ae.prototype.getInverse=function(t){return console.warn("THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead."),this.copy(t).invert()},mi.prototype.isIntersectionLine=function(t){return console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine()."),this.intersectsLine(t)},Yt.prototype.multiplyVector3=function(t){return console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead."),t.applyQuaternion(this)},Yt.prototype.inverse=function(){return console.warn("THREE.Quaternion: .inverse() has been renamed to invert()."),this.invert()},Ee.prototype.isIntersectionBox=function(t){return console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox()."),this.intersectsBox(t)},Ee.prototype.isIntersectionPlane=function(t){return console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane()."),this.intersectsPlane(t)},Ee.prototype.isIntersectionSphere=function(t){return console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere()."),this.intersectsSphere(t)},hn.prototype.area=function(){return console.warn("THREE.Triangle: .area() has been renamed to .getArea()."),this.getArea()},hn.prototype.barycoordFromPoint=function(t,e){return console.warn("THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord()."),this.getBarycoord(t,e)},hn.prototype.midpoint=function(t){return console.warn("THREE.Triangle: .midpoint() has been renamed to .getMidpoint()."),this.getMidpoint(t)},hn.prototypenormal=function(t){return console.warn("THREE.Triangle: .normal() has been renamed to .getNormal()."),this.getNormal(t)},hn.prototype.plane=function(t){return console.warn("THREE.Triangle: .plane() has been renamed to .getPlane()."),this.getPlane(t)},hn.barycoordFromPoint=function(t,e,n,i,r){return console.warn("THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord()."),hn.getBarycoord(t,e,n,i,r)},hn.normal=function(t,e,n,i){return console.warn("THREE.Triangle: .normal() has been renamed to .getNormal()."),hn.getNormal(t,e,n,i)},Ko.prototype.extractAllPoints=function(t){return console.warn("THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead."),this.extractPoints(t)},Ko.prototype.extrude=function(t){return console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead."),new El(this,t)},Ko.prototype.makeGeometry=function(t){return console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead."),new Dl(this,t)},At.prototype.fromAttribute=function(t,e,n){return console.warn("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute()."),this.fromBufferAttribute(t,e,n)},At.prototype.distanceToManhattan=function(t){return console.warn("THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo()."),this.manhattanDistanceTo(t)},At.prototype.lengthManhattan=function(){return console.warn("THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength()."),this.manhattanLength()},Zt.prototype.setEulerFromRotationMatrix=function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},Zt.prototype.setEulerFromQuaternion=function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")},Zt.prototype.getPositionFromMatrix=function(t){return console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition()."),this.setFromMatrixPosition(t)},Zt.prototype.getScaleFromMatrix=function(t){return console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale()."),this.setFromMatrixScale(t)},Zt.prototype.getColumnFromMatrix=function(t,e){return console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn()."),this.setFromMatrixColumn(e,t)},Zt.prototype.applyProjection=function(t){return console.warn("THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead."),this.applyMatrix4(t)},Zt.prototype.fromAttribute=function(t,e,n){return console.warn("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute()."),this.fromBufferAttribute(t,e,n)},Zt.prototype.distanceToManhattan=function(t){return console.warn("THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo()."),this.manhattanDistanceTo(t)},Zt.prototype.lengthManhattan=function(){return console.warn("THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength()."),this.manhattanLength()},jt.prototype.fromAttribute=function(t,e,n){return console.warn("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute()."),this.fromBufferAttribute(t,e,n)},jt.prototype.lengthManhattan=function(){return console.warn("THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength()."),this.manhattanLength()},Qe.prototype.getChildByName=function(t){return console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName()."),this.getObjectByName(t)},Qe.prototype.renderDepth=function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},Qe.prototype.translate=function(t,e){return console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead."),this.translateOnAxis(e,t)},Qe.prototype.getWorldRotation=function(){console.error("THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.")},Qe.prototype.applyMatrix=function(t){return console.warn("THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4()."),this.applyMatrix4(t)},Object.defineProperties(Qe.prototype,{eulerOrder:{get:function(){return console.warn("THREE.Object3D: .eulerOrder is now .rotation.order."),this.rotation.order},set:function(t){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order."),this.rotation.order=t}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}}),Qn.prototype.setDrawMode=function(){console.error("THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.")},Object.defineProperties(Qn.prototype,{drawMode:{get:function(){return console.error("THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode."),0},set:function(){console.error("THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.")}}}),Fa.prototype.initBones=function(){console.error("THREE.SkinnedMesh: initBones() has been removed.")},ai.prototype.setLens=function(t,e){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup."),void 0!==e&&(this.filmGauge=e),this.setFocalLength(t)},Object.defineProperties(bc.prototype,{onlyShadow:{set:function(){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(t){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov."),this.shadow.camera.fov=t}},shadowCameraLeft:{set:function(t){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left."),this.shadow.camera.left=t}},shadowCameraRight:{set:function(t){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right."),this.shadow.camera.right=t}},shadowCameraTop:{set:function(t){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top."),this.shadow.camera.top=t}},shadowCameraBottom:{set:function(t){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom."),this.shadow.camera.bottom=t}},shadowCameraNear:{set:function(t){console.warn("THREE.Light: .shadowCameraNear is now .shadow.camera.near."),this.shadow.camera.near=t}},shadowCameraFar:{set:function(t){console.warn("THREE.Light: .shadowCameraFar is now .shadow.camera.far."),this.shadow.camera.far=t}},shadowCameraVisible:{set:function(){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.")}},shadowBias:{set:function(t){console.warn("THREE.Light: .shadowBias is now .shadow.bias."),this.shadow.bias=t}},shadowDarkness:{set:function(){console.warn("THREE.Light: .shadowDarkness has been removed.")}},shadowMapWidth:{set:function(t){console.warn("THREE.Light: .shadowMapWidth is now .shadow.mapSize.width."),this.shadow.mapSize.width=t}},shadowMapHeight:{set:function(t){console.warn("THREE.Light: .shadowMapHeight is now .shadow.mapSize.height."),this.shadow.mapSize.height=t}}}),Object.defineProperties(gn.prototype,{length:{get:function(){return console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead."),this.array.length}},dynamic:{get:function(){return console.warn("THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead."),this.usage===ut},set:function(){console.warn("THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead."),this.setUsage(ut)}}}),gn.prototype.setDynamic=function(t){return console.warn("THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead."),this.setUsage(!0===t?ut:ht),this},gn.prototype.copyIndicesArray=function(){console.error("THREE.BufferAttribute: .copyIndicesArray() has been removed.")},gn.prototype.setArray=function(){console.error("THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers")},Nn.prototype.addIndex=function(t){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex()."),this.setIndex(t)},Nn.prototype.addAttribute=function(t,e){return console.warn("THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute()."),e&&e.isBufferAttribute||e&&e.isInterleavedBufferAttribute?"index"===t?(console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),this.setIndex(e),this):this.setAttribute(t,e):(console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),this.setAttribute(t,new gn(arguments[1],arguments[2])))},Nn.prototype.addDrawCall=function(t,e,n){void 0!==n&&console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset."),console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup()."),this.addGroup(t,e)},Nn.prototype.clearDrawCalls=function(){console.warn("THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups()."),this.clearGroups()},Nn.prototype.computeOffsets=function(){console.warn("THREE.BufferGeometry: .computeOffsets() has been removed.")},Nn.prototype.removeAttribute=function(t){return console.warn("THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute()."),this.deleteAttribute(t)},Nn.prototype.applyMatrix=function(t){return console.warn("THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4()."),this.applyMatrix4(t)},Object.defineProperties(Nn.prototype,{drawcalls:{get:function(){return console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups."),this.groups}},offsets:{get:function(){return console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups."),this.groups}}}),ua.prototype.setDynamic=function(t){return console.warn("THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead."),this.setUsage(!0===t?ut:ht),this},ua.prototype.setArray=function(){console.error("THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers")},El.prototype.getArrays=function(){console.error("THREE.ExtrudeGeometry: .getArrays() has been removed.")},El.prototype.addShapeList=function(){console.error("THREE.ExtrudeGeometry: .addShapeList() has been removed.")},El.prototype.addShape=function(){console.error("THREE.ExtrudeGeometry: .addShape() has been removed.")},ha.prototype.dispose=function(){console.error("THREE.Scene: .dispose() has been removed.")},Ch.prototype.onUpdate=function(){return console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead."),this},Object.defineProperties(dn.prototype,{wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.")},set:function(){console.warn("THREE.Material: .wrapAround has been removed.")}},overdraw:{get:function(){console.warn("THREE.Material: .overdraw has been removed.")},set:function(){console.warn("THREE.Material: .overdraw has been removed.")}},wrapRGB:{get:function(){return console.warn("THREE.Material: .wrapRGB has been removed."),new Ut}},shading:{get:function(){console.error("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.")},set:function(t){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===t}},stencilMask:{get:function(){return console.warn("THREE."+this.type+": .stencilMask has been removed. Use .stencilFuncMask instead."),this.stencilFuncMask},set:function(t){console.warn("THREE."+this.type+": .stencilMask has been removed. Use .stencilFuncMask instead."),this.stencilFuncMask=t}},vertexTangents:{get:function(){console.warn("THREE."+this.type+": .vertexTangents has been removed.")},set:function(){console.warn("THREE."+this.type+": .vertexTangents has been removed.")}}}),Object.defineProperties(ri.prototype,{derivatives:{get:function(){return console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives."),this.extensions.derivatives},set:function(t){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives."),this.extensions.derivatives=t}}}),aa.prototype.clearTarget=function(t,e,n,i){console.warn("THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead."),this.setRenderTarget(t),this.clear(e,n,i)},aa.prototype.animate=function(t){console.warn("THREE.WebGLRenderer: .animate() is now .setAnimationLoop()."),this.setAnimationLoop(t)},aa.prototype.getCurrentRenderTarget=function(){return console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget()."),this.getRenderTarget()},aa.prototype.getMaxAnisotropy=function(){return console.warn("THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy()."),this.capabilities.getMaxAnisotropy()},aa.prototype.getPrecision=function(){return console.warn("THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision."),this.capabilities.precision},aa.prototype.resetGLState=function(){return console.warn("THREE.WebGLRenderer: .resetGLState() is now .state.reset()."),this.state.reset()},aa.prototype.supportsFloatTextures=function(){return console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' )."),this.extensions.get("OES_texture_float")},aa.prototype.supportsHalfFloatTextures=function(){return console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' )."),this.extensions.get("OES_texture_half_float")},aa.prototype.supportsStandardDerivatives=function(){return console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' )."),this.extensions.get("OES_standard_derivatives")},aa.prototype.supportsCompressedTextureS3TC=function(){return console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' )."),this.extensions.get("WEBGL_compressed_texture_s3tc")},aa.prototype.supportsCompressedTexturePVRTC=function(){return console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' )."),this.extensions.get("WEBGL_compressed_texture_pvrtc")},aa.prototype.supportsBlendMinMax=function(){return console.warn("THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( 'EXT_blend_minmax' )."),this.extensions.get("EXT_blend_minmax")},aa.prototype.supportsVertexTextures=function(){return console.warn("THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures."),this.capabilities.vertexTextures},aa.prototype.supportsInstancedArrays=function(){return console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' )."),this.extensions.get("ANGLE_instanced_arrays")},aa.prototype.enableScissorTest=function(t){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest()."),this.setScissorTest(t)},aa.prototype.initMaterial=function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},aa.prototype.addPrePlugin=function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")},aa.prototype.addPostPlugin=function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},aa.prototype.updateShadowMap=function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")},aa.prototype.setFaceCulling=function(){console.warn("THREE.WebGLRenderer: .setFaceCulling() has been removed.")},aa.prototype.allocTextureUnit=function(){console.warn("THREE.WebGLRenderer: .allocTextureUnit() has been removed.")},aa.prototype.setTexture=function(){console.warn("THREE.WebGLRenderer: .setTexture() has been removed.")},aa.prototype.setTexture2D=function(){console.warn("THREE.WebGLRenderer: .setTexture2D() has been removed.")},aa.prototype.setTextureCube=function(){console.warn("THREE.WebGLRenderer: .setTextureCube() has been removed.")},aa.prototype.getActiveMipMapLevel=function(){return console.warn("THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel()."),this.getActiveMipmapLevel()},Object.defineProperties(aa.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(t){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled."),this.shadowMap.enabled=t}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(t){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type."),this.shadowMap.type=t}},shadowMapCullFace:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.")}},context:{get:function(){return console.warn("THREE.WebGLRenderer: .context has been removed. Use .getContext() instead."),this.getContext()}},vr:{get:function(){return console.warn("THREE.WebGLRenderer: .vr has been renamed to .xr"),this.xr}},gammaInput:{get:function(){return console.warn("THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead."),!1},set:function(){console.warn("THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.")}},gammaOutput:{get:function(){return console.warn("THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead."),!1},set:function(t){console.warn("THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead."),this.outputEncoding=!0===t?lt:ot}},toneMappingWhitePoint:{get:function(){return console.warn("THREE.WebGLRenderer: .toneMappingWhitePoint has been removed."),1},set:function(){console.warn("THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.")}},gammaFactor:{get:function(){return console.warn("THREE.WebGLRenderer: .gammaFactor has been removed."),2},set:function(){console.warn("THREE.WebGLRenderer: .gammaFactor has been removed.")}}}),Object.defineProperties(Ys.prototype,{cullFace:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.")}},renderReverseSided:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.")}},renderSingleSided:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.")}}}),Object.defineProperties(qt.prototype,{wrapS:{get:function(){return console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS."),this.texture.wrapS},set:function(t){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS."),this.texture.wrapS=t}},wrapT:{get:function(){return console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT."),this.texture.wrapT},set:function(t){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT."),this.texture.wrapT=t}},magFilter:{get:function(){return console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter."),this.texture.magFilter},set:function(t){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter."),this.texture.magFilter=t}},minFilter:{get:function(){return console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter."),this.texture.minFilter},set:function(t){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter."),this.texture.minFilter=t}},anisotropy:{get:function(){return console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy."),this.texture.anisotropy},set:function(t){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy."),this.texture.anisotropy=t}},offset:{get:function(){return console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset."),this.texture.offset},set:function(t){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset."),this.texture.offset=t}},repeat:{get:function(){return console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat."),this.texture.repeat},set:function(t){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat."),this.texture.repeat=t}},format:{get:function(){return console.warn("THREE.WebGLRenderTarget: .format is now .texture.format."),this.texture.format},set:function(t){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format."),this.texture.format=t}},type:{get:function(){return console.warn("THREE.WebGLRenderTarget: .type is now .texture.type."),this.texture.type},set:function(t){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type."),this.texture.type=t}},generateMipmaps:{get:function(){return console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps."),this.texture.generateMipmaps},set:function(t){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps."),this.texture.generateMipmaps=t}}}),ch.prototype.load=function(t){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");const e=this;return(new Kc).load(t,(function(t){e.setBuffer(t)})),this},mh.prototype.getData=function(){return console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData()."),this.getFrequencyData()},li.prototype.updateCubeMap=function(t,e){return console.warn("THREE.CubeCamera: .updateCubeMap() is now .update()."),this.update(t,e)},li.prototype.clear=function(t,e,n,i){return console.warn("THREE.CubeCamera: .clear() is now .renderTarget.clear()."),this.renderTarget.clear(t,e,n,i)},Gt.crossOrigin=void 0,Gt.loadTexture=function(t,e,n,i){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");const r=new Mc;r.setCrossOrigin(this.crossOrigin);const s=r.load(t,n,void 0,i);return e&&(s.mapping=e),s},Gt.loadTextureCube=function(t,e,n,i){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");const r=new xc;r.setCrossOrigin(this.crossOrigin);const s=r.load(t,n,void 0,i);return e&&(s.mapping=e),s},Gt.loadCompressedTexture=function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")},Gt.loadCompressedTextureCube=function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")};const hu={createMultiMaterialObject:function(){console.error("THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js")},detach:function(){console.error("THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js")},attach:function(){console.error("THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js")}};"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:e}})),"undefined"!=typeof window&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=e),t.ACESFilmicToneMapping=4,t.AddEquation=n,t.AddOperation=2,t.AdditiveAnimationBlendMode=at,t.AdditiveBlending=2,t.AlphaFormat=1021,t.AlwaysDepth=1,t.AlwaysStencilFunc=519,t.AmbientLight=Oc,t.AmbientLightProbe=$c,t.AnimationClip=hc,t.AnimationLoader=class extends fc{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new vc(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(t,(function(n){try{e(r.parse(JSON.parse(n)))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}parse(t){const e=[];for(let n=0;n<t.length;n++){const i=hc.parse(t[n]);e.push(i)}return e}},t.AnimationMixer=Lh,t.AnimationObjectGroup=Ah,t.AnimationUtils=Kl,t.ArcCurve=Po,t.ArrayCamera=$s,t.ArrowHelper=class extends Qe{constructor(t=new Zt(0,0,1),e=new Zt(0,0,0),n=1,i=16776960,r=.2*n,s=.2*r){super(),this.type="ArrowHelper",void 0===su&&(su=new Nn,su.setAttribute("position",new Tn([0,0,0,0,1,0],3)),au=new _o(0,.5,1,5,1),au.translate(0,-.5,0)),this.position.copy(e),this.line=new no(su,new Za({color:i,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new Qn(au,new pn({color:i,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(t),this.setLength(n,r,s)}setDirection(t){if(t.y>.99999)this.quaternion.set(0,0,0,1);else if(t.y<-.99999)this.quaternion.set(1,0,0,0);else{ru.set(t.z,0,-t.x).normalize();const e=Math.acos(t.y);this.quaternion.setFromAxisAngle(ru,e)}}setLength(t,e=.2*t,n=.2*e){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}},t.Audio=ch,t.AudioAnalyser=mh,t.AudioContext=Zc,t.AudioListener=class extends Qe{constructor(){super(),this.type="AudioListener",this.context=Zc.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new ih}getInput(){return this.gain}removeFilter(){return null!==this.filter&&(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 null!==this.filter?(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);const e=this.context.listener,n=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(sh,ah,oh),lh.set(0,0,-1).applyQuaternion(ah),e.positionX){const t=this.context.currentTime+this.timeDelta;e.positionX.linearRampToValueAtTime(sh.x,t),e.positionY.linearRampToValueAtTime(sh.y,t),e.positionZ.linearRampToValueAtTime(sh.z,t),e.forwardX.linearRampToValueAtTime(lh.x,t),e.forwardY.linearRampToValueAtTime(lh.y,t),e.forwardZ.linearRampToValueAtTime(lh.z,t),e.upX.linearRampToValueAtTime(n.x,t),e.upY.linearRampToValueAtTime(n.y,t),e.upZ.linearRampToValueAtTime(n.z,t)}else e.setPosition(sh.x,sh.y,sh.z),e.setOrientation(lh.x,lh.y,lh.z,n.x,n.y,n.z)}},t.AudioLoader=Kc,t.AxesHelper=ou,t.AxisHelper=function(t){return console.warn("THREE.AxisHelper has been renamed to THREE.AxesHelper."),new ou(t)},t.BackSide=1,t.BasicDepthPacking=3200,t.BasicShadowMap=0,t.BinaryTextureLoader=function(t){return console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader."),new _c(t)},t.Bone=Ua,t.BooleanKeyframeTrack=ic,t.BoundingBoxHelper=function(t,e){return console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead."),new iu(t,e)},t.Box2=zh,t.Box3=$t,t.Box3Helper=class extends so{constructor(t,e=16776960){const n=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]),i=new Nn;i.setIndex(new gn(n,1)),i.setAttribute("position",new Tn([1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],3)),super(i,new Za({color:e,toneMapped:!1})),this.box=t,this.type="Box3Helper",this.geometry.computeBoundingSphere()}updateMatrixWorld(t){const e=this.box;e.isEmpty()||(e.getCenter(this.position),e.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(t))}},t.BoxBufferGeometry=ti,t.BoxGeometry=ti,t.BoxHelper=iu,t.BufferAttribute=gn,t.BufferGeometry=Nn,t.BufferGeometryLoader=Wc,t.ByteType=1010,t.Cache=dc,t.Camera=si,t.CameraHelper=class extends so{constructor(t){const e=new Nn,n=new Za({color:16777215,vertexColors:!0,toneMapped:!1}),i=[],r=[],s={},a=new Ut(16755200),o=new Ut(16711680),l=new Ut(43775),c=new Ut(16777215),h=new Ut(3355443);function u(t,e,n){d(t,n),d(e,n)}function d(t,e){i.push(0,0,0),r.push(e.r,e.g,e.b),void 0===s[t]&&(s[t]=[]),s[t].push(i.length/3-1)}u("n1","n2",a),u("n2","n4",a),u("n4","n3",a),u("n3","n1",a),u("f1","f2",a),u("f2","f4",a),u("f4","f3",a),u("f3","f1",a),u("n1","f1",a),u("n2","f2",a),u("n3","f3",a),u("n4","f4",a),u("p","n1",o),u("p","n2",o),u("p","n3",o),u("p","n4",o),u("u1","u2",l),u("u2","u3",l),u("u3","u1",l),u("c","t",c),u("p","c",h),u("cn1","cn2",h),u("cn3","cn4",h),u("cf1","cf2",h),u("cf3","cf4",h),e.setAttribute("position",new Tn(i,3)),e.setAttribute("color",new Tn(r,3)),super(e,n),this.type="CameraHelper",this.camera=t,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=s,this.update()}update(){const t=this.geometry,e=this.pointMap;tu.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),eu("c",e,t,tu,0,0,-1),eu("t",e,t,tu,0,0,1),eu("n1",e,t,tu,-1,-1,-1),eu("n2",e,t,tu,1,-1,-1),eu("n3",e,t,tu,-1,1,-1),eu("n4",e,t,tu,1,1,-1),eu("f1",e,t,tu,-1,-1,1),eu("f2",e,t,tu,1,-1,1),eu("f3",e,t,tu,-1,1,1),eu("f4",e,t,tu,1,1,1),eu("u1",e,t,tu,.7,1.1,-1),eu("u2",e,t,tu,-.7,1.1,-1),eu("u3",e,t,tu,0,2,-1),eu("cf1",e,t,tu,-1,0,1),eu("cf2",e,t,tu,1,0,1),eu("cf3",e,t,tu,0,-1,1),eu("cf4",e,t,tu,0,1,1),eu("cn1",e,t,tu,-1,0,-1),eu("cn2",e,t,tu,1,0,-1),eu("cn3",e,t,tu,0,-1,-1),eu("cn4",e,t,tu,0,1,-1),t.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}},t.CanvasRenderer=function(){console.error("THREE.CanvasRenderer has been removed")},t.CanvasTexture=yo,t.CatmullRomCurve3=Oo,t.CineonToneMapping=3,t.CircleBufferGeometry=xo,t.CircleGeometry=xo,t.ClampToEdgeWrapping=u,t.Clock=ih,t.Color=Ut,t.ColorKeyframeTrack=rc,t.CompressedTexture=vo,t.CompressedTextureLoader=class extends fc{constructor(t){super(t)}load(t,e,n,i){const r=this,s=[],a=new vo,o=new vc(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(r.withCredentials);let l=0;function c(c){o.load(t[c],(function(t){const n=r.parse(t,!0);s[c]={width:n.width,height:n.height,format:n.format,mipmaps:n.mipmaps},l+=1,6===l&&(1===n.mipmapCount&&(a.minFilter=g),a.image=s,a.format=n.format,a.needsUpdate=!0,e&&e(a))}),n,i)}if(Array.isArray(t))for(let e=0,n=t.length;e<n;++e)c(e);else o.load(t,(function(t){const n=r.parse(t,!0);if(n.isCubemap){const t=n.mipmaps.length/n.mipmapCount;for(let e=0;e<t;e++){s[e]={mipmaps:[]};for(let t=0;t<n.mipmapCount;t++)s[e].mipmaps.push(n.mipmaps[e*n.mipmapCount+t]),s[e].format=n.format,s[e].width=n.width,s[e].height=n.height}a.image=s}else a.image.width=n.width,a.image.height=n.height,a.mipmaps=n.mipmaps;1===n.mipmapCount&&(a.minFilter=g),a.format=n.format,a.needsUpdate=!0,e&&e(a)}),n,i);return a}},t.ConeBufferGeometry=Mo,t.ConeGeometry=Mo,t.CubeCamera=li,t.CubeReflectionMapping=r,t.CubeRefractionMapping=s,t.CubeTexture=ci,t.CubeTextureLoader=xc,t.CubeUVReflectionMapping=l,t.CubeUVRefractionMapping=c,t.CubicBezierCurve=Go,t.CubicBezierCurve3=ko,t.CubicInterpolant=$l,t.CullFaceBack=1,t.CullFaceFront=2,t.CullFaceFrontBack=3,t.CullFaceNone=0,t.Curve=Lo,t.CurvePath=Yo,t.CustomBlending=5,t.CustomToneMapping=5,t.CylinderBufferGeometry=_o,t.CylinderGeometry=_o,t.Cylindrical=class{constructor(t=1,e=0,n=0){return this.radius=t,this.theta=e,this.y=n,this}set(t,e,n){return this.radius=t,this.theta=e,this.y=n,this}copy(t){return this.radius=t.radius,this.theta=t.theta,this.y=t.y,this}setFromVector3(t){return this.setFromCartesianCoords(t.x,t.y,t.z)}setFromCartesianCoords(t,e,n){return this.radius=Math.sqrt(t*t+n*n),this.theta=Math.atan2(t,n),this.y=e,this}clone(){return(new this.constructor).copy(this)}},t.DataTexture=Ha,t.DataTexture2DArray=ir,t.DataTexture3D=cr,t.DataTextureLoader=_c,t.DataUtils=class{static toHalfFloat(t){t>65504&&(console.warn("THREE.DataUtils.toHalfFloat(): value exceeds 65504."),t=65504),lu[0]=t;const e=cu[0];let n=e>>16&32768,i=e>>12&2047;const r=e>>23&255;return r<103?n:r>142?(n|=31744,n|=(255==r?0:1)&&8388607&e,n):r<113?(i|=2048,n|=(i>>114-r)+(i>>113-r&1),n):(n|=r-112<<10|i>>1,n+=1&i,n)}},t.DecrementStencilOp=7683,t.DecrementWrapStencilOp=34056,t.DefaultLoadingManager=mc,t.DepthFormat=E,t.DepthStencilFormat=A,t.DepthTexture=ia,t.DirectionalLight=zc,t.DirectionalLightHelper=class extends Qe{constructor(t,e,n){super(),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.color=n,void 0===e&&(e=1);let i=new Nn;i.setAttribute("position",new Tn([-e,e,0,e,e,0,e,-e,0,-e,-e,0,-e,e,0],3));const r=new Za({fog:!1,toneMapped:!1});this.lightPlane=new no(i,r),this.add(this.lightPlane),i=new Nn,i.setAttribute("position",new Tn([0,0,0,0,0,1],3)),this.targetLine=new no(i,r),this.add(this.targetLine),this.update()}dispose(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose()}update(){Zh.setFromMatrixPosition(this.light.matrixWorld),Kh.setFromMatrixPosition(this.light.target.matrixWorld),Qh.subVectors(Kh,Zh),this.lightPlane.lookAt(Kh),void 0!==this.color?(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)):(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color)),this.targetLine.lookAt(Kh),this.targetLine.scale.z=Qh.length()}},t.DiscreteInterpolant=ec,t.DodecahedronBufferGeometry=wo,t.DodecahedronGeometry=wo,t.DoubleSide=2,t.DstAlphaFactor=206,t.DstColorFactor=208,t.DynamicBufferAttribute=function(t,e){return console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead."),new gn(t,e).setUsage(ut)},t.DynamicCopyUsage=35050,t.DynamicDrawUsage=ut,t.DynamicReadUsage=35049,t.EdgesGeometry=Ro,t.EdgesHelper=function(t,e){return console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead."),new so(new Ro(t.geometry),new Za({color:void 0!==e?e:16777215}))},t.EllipseCurve=Co,t.EqualDepth=4,t.EqualStencilFunc=514,t.EquirectangularReflectionMapping=a,t.EquirectangularRefractionMapping=o,t.Euler=Oe,t.EventDispatcher=mt,t.ExtrudeBufferGeometry=El,t.ExtrudeGeometry=El,t.FaceColors=1,t.FileLoader=vc,t.FlatShading=1,t.Float16BufferAttribute=Sn,t.Float32Attribute=function(t,e){return console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead."),new Tn(t,e)},t.Float32BufferAttribute=Tn,t.Float64Attribute=function(t,e){return console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead."),new En(t,e)},t.Float64BufferAttribute=En,t.FloatType=b,t.Fog=ca,t.FogExp2=la,t.Font=function(){console.error("THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js")},t.FontLoader=function(){console.error("THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js")},t.FramebufferTexture=go,t.FrontSide=0,t.Frustum=vi,t.GLBufferAttribute=Dh,t.GLSL1="100",t.GLSL3=dt,t.GreaterDepth=6,t.GreaterEqualDepth=5,t.GreaterEqualStencilFunc=518,t.GreaterStencilFunc=516,t.GridHelper=Yh,t.Group=ta,t.HalfFloatType=w,t.HemisphereLight=wc,t.HemisphereLightHelper=class extends Qe{constructor(t,e,n){super(),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.color=n;const i=new Cl(e);i.rotateY(.5*Math.PI),this.material=new pn({wireframe:!0,fog:!1,toneMapped:!1}),void 0===this.color&&(this.material.vertexColors=!0);const r=i.getAttribute("position"),s=new Float32Array(3*r.count);i.setAttribute("color",new gn(s,3)),this.add(new Qn(i,this.material)),this.update()}dispose(){this.children[0].geometry.dispose(),this.children[0].material.dispose()}update(){const t=this.children[0];if(void 0!==this.color)this.material.color.set(this.color);else{const e=t.geometry.getAttribute("color");Xh.copy(this.light.color),Jh.copy(this.light.groundColor);for(let t=0,n=e.count;t<n;t++){const i=t<n/2?Xh:Jh;e.setXYZ(t,i.r,i.g,i.b)}e.needsUpdate=!0}t.lookAt(qh.setFromMatrixPosition(this.light.matrixWorld).negate())}},t.HemisphereLightProbe=Qc,t.IcosahedronBufferGeometry=Rl,t.IcosahedronGeometry=Rl,t.ImageBitmapLoader=Jc,t.ImageLoader=yc,t.ImageUtils=Gt,t.ImmediateRenderObject=function(){console.error("THREE.ImmediateRenderObject has been removed.")},t.IncrementStencilOp=7682,t.IncrementWrapStencilOp=34055,t.InstancedBufferAttribute=Wa,t.InstancedBufferGeometry=Vc,t.InstancedInterleavedBuffer=Ph,t.InstancedMesh=Ya,t.Int16Attribute=function(t,e){return console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead."),new _n(t,e)},t.Int16BufferAttribute=_n,t.Int32Attribute=function(t,e){return console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead."),new bn(t,e)},t.Int32BufferAttribute=bn,t.Int8Attribute=function(t,e){return console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead."),new vn(t,e)},t.Int8BufferAttribute=vn,t.IntType=1013,t.InterleavedBuffer=ua,t.InterleavedBufferAttribute=pa,t.Interpolant=Ql,t.InterpolateDiscrete=$,t.InterpolateLinear=tt,t.InterpolateSmooth=et,t.InvertStencilOp=5386,t.JSONLoader=function(){console.error("THREE.JSONLoader has been removed.")},t.KeepStencilOp=ct,t.KeyframeTrack=nc,t.LOD=Da,t.LatheBufferGeometry=Ll,t.LatheGeometry=Ll,t.Layers=Fe,t.LensFlare=function(){console.error("THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js")},t.LessDepth=2,t.LessEqualDepth=3,t.LessEqualStencilFunc=515,t.LessStencilFunc=513,t.Light=bc,t.LightProbe=Hc,t.Line=no,t.Line3=Uh,t.LineBasicMaterial=Za,t.LineCurve=Vo,t.LineCurve3=Wo,t.LineDashedMaterial=Yl,t.LineLoop=ao,t.LinePieces=1,t.LineSegments=so,t.LineStrip=0,t.LinearEncoding=ot,t.LinearFilter=g,t.LinearInterpolant=tc,t.LinearMipMapLinearFilter=1008,t.LinearMipMapNearestFilter=1007,t.LinearMipmapLinearFilter=y,t.LinearMipmapNearestFilter=v,t.LinearToneMapping=1,t.Loader=fc,t.LoaderUtils=kc,t.LoadingManager=pc,t.LoopOnce=2200,t.LoopPingPong=2202,t.LoopRepeat=2201,t.LuminanceAlphaFormat=1025,t.LuminanceFormat=1024,t.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},t.Material=dn,t.MaterialLoader=Gc,t.Math=Et,t.MathUtils=Et,t.Matrix3=Rt,t.Matrix4=Ae,t.MaxEquation=104,t.Mesh=Qn,t.MeshBasicMaterial=pn,t.MeshDepthMaterial=Xs,t.MeshDistanceMaterial=Js,t.MeshFaceMaterial=function(t){return console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead."),t},t.MeshLambertMaterial=Xl,t.MeshMatcapMaterial=Jl,t.MeshNormalMaterial=ql,t.MeshPhongMaterial=Wl,t.MeshPhysicalMaterial=Vl,t.MeshStandardMaterial=kl,t.MeshToonMaterial=jl,t.MinEquation=103,t.MirroredRepeatWrapping=d,t.MixOperation=1,t.MultiMaterial=function(t=[]){return console.warn("THREE.MultiMaterial has been removed. Use an Array instead."),t.isMultiMaterial=!0,t.materials=t,t.clone=function(){return t.slice()},t},t.MultiplyBlending=4,t.MultiplyOperation=0,t.NearestFilter=p,t.NearestMipMapLinearFilter=1005,t.NearestMipMapNearestFilter=1004,t.NearestMipmapLinearFilter=f,t.NearestMipmapNearestFilter=m,t.NeverDepth=0,t.NeverStencilFunc=512,t.NoBlending=0,t.NoColors=0,t.NoToneMapping=0,t.NormalAnimationBlendMode=st,t.NormalBlending=1,t.NotEqualDepth=7,t.NotEqualStencilFunc=517,t.NumberKeyframeTrack=sc,t.Object3D=Qe,t.ObjectLoader=class extends fc{constructor(t){super(t)}load(t,e,n,i){const r=this,s=""===this.path?kc.extractUrlBase(t):this.path;this.resourcePath=this.resourcePath||s;const a=new vc(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(t,(function(n){let s=null;try{s=JSON.parse(n)}catch(e){return void 0!==i&&i(e),void console.error("THREE:ObjectLoader: Can't parse "+t+".",e.message)}const a=s.metadata;void 0!==a&&void 0!==a.type&&"geometry"!==a.type.toLowerCase()?r.parse(s,e):console.error("THREE.ObjectLoader: Can't load "+t)}),n,i)}async loadAsync(t,e){const n=""===this.path?kc.extractUrlBase(t):this.path;this.resourcePath=this.resourcePath||n;const i=new vc(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials);const r=await i.loadAsync(t,e),s=JSON.parse(r),a=s.metadata;if(void 0===a||void 0===a.type||"geometry"===a.type.toLowerCase())throw new Error("THREE.ObjectLoader: Can't load "+t);return await this.parseAsync(s)}parse(t,e){const n=this.parseAnimations(t.animations),i=this.parseShapes(t.shapes),r=this.parseGeometries(t.geometries,i),s=this.parseImages(t.images,(function(){void 0!==e&&e(l)})),a=this.parseTextures(t.textures,s),o=this.parseMaterials(t.materials,a),l=this.parseObject(t.object,r,o,a,n),c=this.parseSkeletons(t.skeletons,l);if(this.bindSkeletons(l,c),void 0!==e){let t=!1;for(const e in s)if(s[e]instanceof HTMLImageElement){t=!0;break}!1===t&&e(l)}return l}async parseAsync(t){const e=this.parseAnimations(t.animations),n=this.parseShapes(t.shapes),i=this.parseGeometries(t.geometries,n),r=await this.parseImagesAsync(t.images),s=this.parseTextures(t.textures,r),a=this.parseMaterials(t.materials,s),o=this.parseObject(t.object,i,a,s,e),l=this.parseSkeletons(t.skeletons,o);return this.bindSkeletons(o,l),o}parseShapes(t){const e={};if(void 0!==t)for(let n=0,i=t.length;n<i;n++){const i=(new Ko).fromJSON(t[n]);e[i.uuid]=i}return e}parseSkeletons(t,e){const n={},i={};if(e.traverse((function(t){t.isBone&&(i[t.uuid]=t)})),void 0!==t)for(let e=0,r=t.length;e<r;e++){const r=(new Va).fromJSON(t[e],i);n[r.uuid]=r}return n}parseGeometries(t,e){const n={};if(void 0!==t){const i=new Wc;for(let r=0,s=t.length;r<s;r++){let s;const a=t[r];switch(a.type){case"BufferGeometry":case"InstancedBufferGeometry":s=i.parse(a);break;case"Geometry":console.error("THREE.ObjectLoader: The legacy Geometry type is no longer supported.");break;default:a.type in Hl?s=Hl[a.type].fromJSON(a,e):console.warn(`THREE.ObjectLoader: Unsupported geometry type "${a.type}"`)}s.uuid=a.uuid,void 0!==a.name&&(s.name=a.name),!0===s.isBufferGeometry&&void 0!==a.userData&&(s.userData=a.userData),n[a.uuid]=s}}return n}parseMaterials(t,e){const n={},i={};if(void 0!==t){const r=new Gc;r.setTextures(e);for(let e=0,s=t.length;e<s;e++){const s=t[e];if("MultiMaterial"===s.type){const t=[];for(let e=0;e<s.materials.length;e++){const i=s.materials[e];void 0===n[i.uuid]&&(n[i.uuid]=r.parse(i)),t.push(n[i.uuid])}i[s.uuid]=t}else void 0===n[s.uuid]&&(n[s.uuid]=r.parse(s)),i[s.uuid]=n[s.uuid]}}return i}parseAnimations(t){const e={};if(void 0!==t)for(let n=0;n<t.length;n++){const i=t[n],r=hc.parse(i);e[r.uuid]=r}return e}parseImages(t,e){const n=this,i={};let r;function s(t){if("string"==typeof t){const e=t;return function(t){return n.manager.itemStart(t),r.load(t,(function(){n.manager.itemEnd(t)}),void 0,(function(){n.manager.itemError(t),n.manager.itemEnd(t)}))}(/^(\/\/)|([a-z]+:(\/\/)?)/i.test(e)?e:n.resourcePath+e)}return t.data?{data:Pt(t.type,t.data),width:t.width,height:t.height}:null}if(void 0!==t&&t.length>0){const n=new pc(e);r=new yc(n),r.setCrossOrigin(this.crossOrigin);for(let e=0,n=t.length;e<n;e++){const n=t[e],r=n.url;if(Array.isArray(r)){i[n.uuid]=[];for(let t=0,e=r.length;t<e;t++){const e=s(r[t]);null!==e&&(e instanceof HTMLImageElement?i[n.uuid].push(e):i[n.uuid].push(new Ha(e.data,e.width,e.height)))}}else{const t=s(n.url);null!==t&&(i[n.uuid]=t)}}}return i}async parseImagesAsync(t){const e=this,n={};let i;async function r(t){if("string"==typeof t){const n=t,r=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(n)?n:e.resourcePath+n;return await i.loadAsync(r)}return t.data?{data:Pt(t.type,t.data),width:t.width,height:t.height}:null}if(void 0!==t&&t.length>0){i=new yc(this.manager),i.setCrossOrigin(this.crossOrigin);for(let e=0,i=t.length;e<i;e++){const i=t[e],s=i.url;if(Array.isArray(s)){n[i.uuid]=[];for(let t=0,e=s.length;t<e;t++){const e=s[t],a=await r(e);null!==a&&(a instanceof HTMLImageElement?n[i.uuid].push(a):n[i.uuid].push(new Ha(a.data,a.width,a.height)))}}else{const t=await r(i.url);null!==t&&(n[i.uuid]=t)}}}return n}parseTextures(t,e){function n(t,e){return"number"==typeof t?t:(console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",t),e[t])}const i={};if(void 0!==t)for(let r=0,s=t.length;r<s;r++){const s=t[r];let a;void 0===s.image&&console.warn('THREE.ObjectLoader: No "image" specified for',s.uuid),void 0===e[s.image]&&console.warn("THREE.ObjectLoader: Undefined image",s.image);const o=e[s.image];Array.isArray(o)?(a=new ci(o),6===o.length&&(a.needsUpdate=!0)):(a=o&&o.data?new Ha(o.data,o.width,o.height):new Vt(o),o&&(a.needsUpdate=!0)),a.uuid=s.uuid,void 0!==s.name&&(a.name=s.name),void 0!==s.mapping&&(a.mapping=n(s.mapping,jc)),void 0!==s.offset&&a.offset.fromArray(s.offset),void 0!==s.repeat&&a.repeat.fromArray(s.repeat),void 0!==s.center&&a.center.fromArray(s.center),void 0!==s.rotation&&(a.rotation=s.rotation),void 0!==s.wrap&&(a.wrapS=n(s.wrap[0],qc),a.wrapT=n(s.wrap[1],qc)),void 0!==s.format&&(a.format=s.format),void 0!==s.type&&(a.type=s.type),void 0!==s.encoding&&(a.encoding=s.encoding),void 0!==s.minFilter&&(a.minFilter=n(s.minFilter,Xc)),void 0!==s.magFilter&&(a.magFilter=n(s.magFilter,Xc)),void 0!==s.anisotropy&&(a.anisotropy=s.anisotropy),void 0!==s.flipY&&(a.flipY=s.flipY),void 0!==s.premultiplyAlpha&&(a.premultiplyAlpha=s.premultiplyAlpha),void 0!==s.unpackAlignment&&(a.unpackAlignment=s.unpackAlignment),void 0!==s.userData&&(a.userData=s.userData),i[s.uuid]=a}return i}parseObject(t,e,n,i,r){let s,a,o;function l(t){return void 0===e[t]&&console.warn("THREE.ObjectLoader: Undefined geometry",t),e[t]}function c(t){if(void 0!==t){if(Array.isArray(t)){const e=[];for(let i=0,r=t.length;i<r;i++){const r=t[i];void 0===n[r]&&console.warn("THREE.ObjectLoader: Undefined material",r),e.push(n[r])}return e}return void 0===n[t]&&console.warn("THREE.ObjectLoader: Undefined material",t),n[t]}}function h(t){return void 0===i[t]&&console.warn("THREE.ObjectLoader: Undefined texture",t),i[t]}switch(t.type){case"Scene":s=new ha,void 0!==t.background&&(Number.isInteger(t.background)?s.background=new Ut(t.background):s.background=h(t.background)),void 0!==t.environment&&(s.environment=h(t.environment)),void 0!==t.fog&&("Fog"===t.fog.type?s.fog=new ca(t.fog.color,t.fog.near,t.fog.far):"FogExp2"===t.fog.type&&(s.fog=new la(t.fog.color,t.fog.density)));break;case"PerspectiveCamera":s=new ai(t.fov,t.aspect,t.near,t.far),void 0!==t.focus&&(s.focus=t.focus),void 0!==t.zoom&&(s.zoom=t.zoom),void 0!==t.filmGauge&&(s.filmGauge=t.filmGauge),void 0!==t.filmOffset&&(s.filmOffset=t.filmOffset),void 0!==t.view&&(s.view=Object.assign({},t.view));break;case"OrthographicCamera":s=new Ci(t.left,t.right,t.top,t.bottom,t.near,t.far),void 0!==t.zoom&&(s.zoom=t.zoom),void 0!==t.view&&(s.view=Object.assign({},t.view));break;case"AmbientLight":s=new Oc(t.color,t.intensity);break;case"DirectionalLight":s=new zc(t.color,t.intensity);break;case"PointLight":s=new Nc(t.color,t.intensity,t.distance,t.decay);break;case"RectAreaLight":s=new Fc(t.color,t.intensity,t.width,t.height);break;case"SpotLight":s=new Lc(t.color,t.intensity,t.distance,t.angle,t.penumbra,t.decay);break;case"HemisphereLight":s=new wc(t.color,t.groundColor,t.intensity);break;case"LightProbe":s=(new Hc).fromJSON(t);break;case"SkinnedMesh":a=l(t.geometry),o=c(t.material),s=new Fa(a,o),void 0!==t.bindMode&&(s.bindMode=t.bindMode),void 0!==t.bindMatrix&&s.bindMatrix.fromArray(t.bindMatrix),void 0!==t.skeleton&&(s.skeleton=t.skeleton);break;case"Mesh":a=l(t.geometry),o=c(t.material),s=new Qn(a,o);break;case"InstancedMesh":a=l(t.geometry),o=c(t.material);const e=t.count,n=t.instanceMatrix,i=t.instanceColor;s=new Ya(a,o,e),s.instanceMatrix=new Wa(new Float32Array(n.array),16),void 0!==i&&(s.instanceColor=new Wa(new Float32Array(i.array),i.itemSize));break;case"LOD":s=new Da;break;case"Line":s=new no(l(t.geometry),c(t.material));break;case"LineLoop":s=new ao(l(t.geometry),c(t.material));break;case"LineSegments":s=new so(l(t.geometry),c(t.material));break;case"PointCloud":case"Points":s=new po(l(t.geometry),c(t.material));break;case"Sprite":s=new Ra(c(t.material));break;case"Group":s=new ta;break;case"Bone":s=new Ua;break;default:s=new Qe}if(s.uuid=t.uuid,void 0!==t.name&&(s.name=t.name),void 0!==t.matrix?(s.matrix.fromArray(t.matrix),void 0!==t.matrixAutoUpdate&&(s.matrixAutoUpdate=t.matrixAutoUpdate),s.matrixAutoUpdate&&s.matrix.decompose(s.position,s.quaternion,s.scale)):(void 0!==t.position&&s.position.fromArray(t.position),void 0!==t.rotation&&s.rotation.fromArray(t.rotation),void 0!==t.quaternion&&s.quaternion.fromArray(t.quaternion),void 0!==t.scale&&s.scale.fromArray(t.scale)),void 0!==t.castShadow&&(s.castShadow=t.castShadow),void 0!==t.receiveShadow&&(s.receiveShadow=t.receiveShadow),t.shadow&&(void 0!==t.shadow.bias&&(s.shadow.bias=t.shadow.bias),void 0!==t.shadow.normalBias&&(s.shadow.normalBias=t.shadow.normalBias),void 0!==t.shadow.radius&&(s.shadow.radius=t.shadow.radius),void 0!==t.shadow.mapSize&&s.shadow.mapSize.fromArray(t.shadow.mapSize),void 0!==t.shadow.camera&&(s.shadow.camera=this.parseObject(t.shadow.camera))),void 0!==t.visible&&(s.visible=t.visible),void 0!==t.frustumCulled&&(s.frustumCulled=t.frustumCulled),void 0!==t.renderOrder&&(s.renderOrder=t.renderOrder),void 0!==t.userData&&(s.userData=t.userData),void 0!==t.layers&&(s.layers.mask=t.layers),void 0!==t.children){const a=t.children;for(let t=0;t<a.length;t++)s.add(this.parseObject(a[t],e,n,i,r))}if(void 0!==t.animations){const e=t.animations;for(let t=0;t<e.length;t++){const n=e[t];s.animations.push(r[n])}}if("LOD"===t.type){void 0!==t.autoUpdate&&(s.autoUpdate=t.autoUpdate);const e=t.levels;for(let t=0;t<e.length;t++){const n=e[t],i=s.getObjectByProperty("uuid",n.object);void 0!==i&&s.addLevel(i,n.distance)}}return s}bindSkeletons(t,e){0!==Object.keys(e).length&&t.traverse((function(t){if(!0===t.isSkinnedMesh&&void 0!==t.skeleton){const n=e[t.skeleton];void 0===n?console.warn("THREE.ObjectLoader: No skeleton found with UUID:",t.skeleton):t.bind(n,t.bindMatrix)}}))}setTexturePath(t){return console.warn("THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath()."),this.setResourcePath(t)}},t.ObjectSpaceNormalMap=1,t.OctahedronBufferGeometry=Cl,t.OctahedronGeometry=Cl,t.OneFactor=201,t.OneMinusDstAlphaFactor=207,t.OneMinusDstColorFactor=209,t.OneMinusSrcAlphaFactor=205,t.OneMinusSrcColorFactor=203,t.OrthographicCamera=Ci,t.PCFShadowMap=1,t.PCFSoftShadowMap=2,t.PMREMGenerator=ji,t.ParametricGeometry=function(){return console.error("THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js"),new Nn},t.Particle=function(t){return console.warn("THREE.Particle has been renamed to THREE.Sprite."),new Ra(t)},t.ParticleBasicMaterial=function(t){return console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial."),new oo(t)},t.ParticleSystem=function(t,e){return console.warn("THREE.ParticleSystem has been renamed to THREE.Points."),new po(t,e)},t.ParticleSystemMaterial=function(t){return console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial."),new oo(t)},t.Path=Zo,t.PerspectiveCamera=ai,t.Plane=mi,t.PlaneBufferGeometry=_i,t.PlaneGeometry=_i,t.PlaneHelper=class extends no{constructor(t,e=1,n=16776960){const i=n,r=new Nn;r.setAttribute("position",new Tn([1,-1,1,-1,1,1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,0,0,1,0,0,0],3)),r.computeBoundingSphere(),super(r,new Za({color:i,toneMapped:!1})),this.type="PlaneHelper",this.plane=t,this.size=e;const s=new Nn;s.setAttribute("position",new Tn([1,1,1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,1],3)),s.computeBoundingSphere(),this.add(new Qn(s,new pn({color:i,opacity:.2,transparent:!0,depthWrite:!1,toneMapped:!1})))}updateMatrixWorld(t){let e=-this.plane.constant;Math.abs(e)<1e-8&&(e=1e-8),this.scale.set(.5*this.size,.5*this.size,e),this.children[0].material.side=e<0?1:0,this.lookAt(this.plane.normal),super.updateMatrixWorld(t)}},t.PointCloud=function(t,e){return console.warn("THREE.PointCloud has been renamed to THREE.Points."),new po(t,e)},t.PointCloudMaterial=function(t){return console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial."),new oo(t)},t.PointLight=Nc,t.PointLightHelper=class extends Qn{constructor(t,e,n){super(new Il(e,4,2),new pn({wireframe:!0,fog:!1,toneMapped:!1})),this.light=t,this.light.updateMatrixWorld(),this.color=n,this.type="PointLightHelper",this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1,this.update()}dispose(){this.geometry.dispose(),this.material.dispose()}update(){void 0!==this.color?this.material.color.set(this.color):this.material.color.copy(this.light.color)}},t.Points=po,t.PointsMaterial=oo,t.PolarGridHelper=class extends so{constructor(t=10,e=16,n=8,i=64,r=4473924,s=8947848){r=new Ut(r),s=new Ut(s);const a=[],o=[];for(let n=0;n<=e;n++){const i=n/e*(2*Math.PI),l=Math.sin(i)*t,c=Math.cos(i)*t;a.push(0,0,0),a.push(l,0,c);const h=1&n?r:s;o.push(h.r,h.g,h.b),o.push(h.r,h.g,h.b)}for(let e=0;e<=n;e++){const l=1&e?r:s,c=t-t/n*e;for(let t=0;t<i;t++){let e=t/i*(2*Math.PI),n=Math.sin(e)*c,r=Math.cos(e)*c;a.push(n,0,r),o.push(l.r,l.g,l.b),e=(t+1)/i*(2*Math.PI),n=Math.sin(e)*c,r=Math.cos(e)*c,a.push(n,0,r),o.push(l.r,l.g,l.b)}}const l=new Nn;l.setAttribute("position",new Tn(a,3)),l.setAttribute("color",new Tn(o,3));super(l,new Za({vertexColors:!0,toneMapped:!1})),this.type="PolarGridHelper"}},t.PolyhedronBufferGeometry=bo,t.PolyhedronGeometry=bo,t.PositionalAudio=class extends ch{constructor(t){super(t),this.panner=this.context.createPanner(),this.panner.panningModel="HRTF",this.panner.connect(this.gain)}getOutput(){return this.panner}getRefDistance(){return this.panner.refDistance}setRefDistance(t){return this.panner.refDistance=t,this}getRolloffFactor(){return this.panner.rolloffFactor}setRolloffFactor(t){return this.panner.rolloffFactor=t,this}getDistanceModel(){return this.panner.distanceModel}setDistanceModel(t){return this.panner.distanceModel=t,this}getMaxDistance(){return this.panner.maxDistance}setMaxDistance(t){return this.panner.maxDistance=t,this}setDirectionalCone(t,e,n){return this.panner.coneInnerAngle=t,this.panner.coneOuterAngle=e,this.panner.coneOuterGain=n,this}updateMatrixWorld(t){if(super.updateMatrixWorld(t),!0===this.hasPlaybackControl&&!1===this.isPlaying)return;this.matrixWorld.decompose(hh,uh,dh),ph.set(0,0,1).applyQuaternion(uh);const e=this.panner;if(e.positionX){const t=this.context.currentTime+this.listener.timeDelta;e.positionX.linearRampToValueAtTime(hh.x,t),e.positionY.linearRampToValueAtTime(hh.y,t),e.positionZ.linearRampToValueAtTime(hh.z,t),e.orientationX.linearRampToValueAtTime(ph.x,t),e.orientationY.linearRampToValueAtTime(ph.y,t),e.orientationZ.linearRampToValueAtTime(ph.z,t)}else e.setPosition(hh.x,hh.y,hh.z),e.setOrientation(ph.x,ph.y,ph.z)}},t.PropertyBinding=Eh,t.PropertyMixer=fh,t.QuadraticBezierCurve=jo,t.QuadraticBezierCurve3=qo,t.Quaternion=Yt,t.QuaternionKeyframeTrack=oc,t.QuaternionLinearInterpolant=ac,t.REVISION=e,t.RGBADepthPacking=3201,t.RGBAFormat=T,t.RGBAIntegerFormat=1033,t.RGBA_ASTC_10x10_Format=Y,t.RGBA_ASTC_10x5_Format=q,t.RGBA_ASTC_10x6_Format=X,t.RGBA_ASTC_10x8_Format=J,t.RGBA_ASTC_12x10_Format=Z,t.RGBA_ASTC_12x12_Format=K,t.RGBA_ASTC_4x4_Format=F,t.RGBA_ASTC_5x4_Format=U,t.RGBA_ASTC_5x5_Format=H,t.RGBA_ASTC_6x5_Format=G,t.RGBA_ASTC_6x6_Format=k,t.RGBA_ASTC_8x5_Format=V,t.RGBA_ASTC_8x6_Format=W,t.RGBA_ASTC_8x8_Format=j,t.RGBA_BPTC_Format=Q,t.RGBA_ETC2_EAC_Format=O,t.RGBA_PVRTC_2BPPV1_Format=B,t.RGBA_PVRTC_4BPPV1_Format=N,t.RGBA_S3TC_DXT1_Format=L,t.RGBA_S3TC_DXT3_Format=C,t.RGBA_S3TC_DXT5_Format=P,t.RGB_ETC1_Format=36196,t.RGB_ETC2_Format=z,t.RGB_PVRTC_2BPPV1_Format=I,t.RGB_PVRTC_4BPPV1_Format=D,t.RGB_S3TC_DXT1_Format=R,t.RGFormat=1030,t.RGIntegerFormat=1031,t.RawShaderMaterial=Pi,t.Ray=Ee,t.Raycaster=class{constructor(t,e,n=0,i=1/0){this.ray=new Ee(t,e),this.near=n,this.far=i,this.camera=null,this.layers=new Fe,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(t,e){this.ray.set(t,e)}setFromCamera(t,e){e&&e.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(t.x,t.y,.5).unproject(e).sub(this.ray.origin).normalize(),this.camera=e):e&&e.isOrthographicCamera?(this.ray.origin.set(t.x,t.y,(e.near+e.far)/(e.near-e.far)).unproject(e),this.ray.direction.set(0,0,-1).transformDirection(e.matrixWorld),this.camera=e):console.error("THREE.Raycaster: Unsupported camera type: "+e.type)}intersectObject(t,e=!0,n=[]){return Nh(t,this,n,e),n.sort(Ih),n}intersectObjects(t,e=!0,n=[]){for(let i=0,r=t.length;i<r;i++)Nh(t[i],this,n,e);return n.sort(Ih),n}},t.RectAreaLight=Fc,t.RedFormat=1028,t.RedIntegerFormat=1029,t.ReinhardToneMapping=2,t.RepeatWrapping=h,t.ReplaceStencilOp=7681,t.ReverseSubtractEquation=102,t.RingBufferGeometry=Pl,t.RingGeometry=Pl,t.Scene=ha,t.SceneUtils=hu,t.ShaderChunk=Mi,t.ShaderLib=wi,t.ShaderMaterial=ri,t.ShadowMaterial=Gl,t.Shape=Ko,t.ShapeBufferGeometry=Dl,t.ShapeGeometry=Dl,t.ShapePath=class{constructor(){this.type="ShapePath",this.color=new Ut,this.subPaths=[],this.currentPath=null}moveTo(t,e){return this.currentPath=new Zo,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,r,s){return this.currentPath.bezierCurveTo(t,e,n,i,r,s),this}splineThru(t){return this.currentPath.splineThru(t),this}toShapes(t,e){function n(t){const e=[];for(let n=0,i=t.length;n<i;n++){const i=t[n],r=new Ko;r.curves=i.curves,e.push(r)}return e}function i(t,e){const n=e.length;let i=!1;for(let r=n-1,s=0;s<n;r=s++){let n=e[r],a=e[s],o=a.x-n.x,l=a.y-n.y;if(Math.abs(l)>Number.EPSILON){if(l<0&&(n=e[s],o=-o,a=e[r],l=-l),t.y<n.y||t.y>a.y)continue;if(t.y===n.y){if(t.x===n.x)return!0}else{const e=l*(t.x-n.x)-o*(t.y-n.y);if(0===e)return!0;if(e<0)continue;i=!i}}else{if(t.y!==n.y)continue;if(a.x<=t.x&&t.x<=n.x||n.x<=t.x&&t.x<=a.x)return!0}}return i}const r=wl.isClockWise,s=this.subPaths;if(0===s.length)return[];if(!0===e)return n(s);let a,o,l;const c=[];if(1===s.length)return o=s[0],l=new Ko,l.curves=o.curves,c.push(l),c;let h=!r(s[0].getPoints());h=t?!h:h;const u=[],d=[];let p,m,f=[],g=0;d[g]=void 0,f[g]=[];for(let e=0,n=s.length;e<n;e++)o=s[e],p=o.getPoints(),a=r(p),a=t?!a:a,a?(!h&&d[g]&&g++,d[g]={s:new Ko,p:p},d[g].s.curves=o.curves,h&&g++,f[g]=[]):f[g].push({h:o,p:p[0]});if(!d[0])return n(s);if(d.length>1){let t=!1;const e=[];for(let t=0,e=d.length;t<e;t++)u[t]=[];for(let n=0,r=d.length;n<r;n++){const r=f[n];for(let s=0;s<r.length;s++){const a=r[s];let o=!0;for(let r=0;r<d.length;r++)i(a.p,d[r].p)&&(n!==r&&e.push({froms:n,tos:r,hole:s}),o?(o=!1,u[r].push(a)):t=!0);o&&u[n].push(a)}}e.length>0&&(t||(f=u))}for(let t=0,e=d.length;t<e;t++){l=d[t].s,c.push(l),m=f[t];for(let t=0,e=m.length;t<e;t++)l.holes.push(m[t].h)}return c}},t.ShapeUtils=wl,t.ShortType=1011,t.Skeleton=Va,t.SkeletonHelper=Wh,t.SkinnedMesh=Fa,t.SmoothShading=2,t.Sphere=ye,t.SphereBufferGeometry=Il,t.SphereGeometry=Il,t.Spherical=class{constructor(t=1,e=0,n=0){return this.radius=t,this.phi=e,this.theta=n,this}set(t,e,n){return this.radius=t,this.phi=e,this.theta=n,this}copy(t){return this.radius=t.radius,this.phi=t.phi,this.theta=t.theta,this}makeSafe(){const t=1e-6;return this.phi=Math.max(t,Math.min(Math.PI-t,this.phi)),this}setFromVector3(t){return this.setFromCartesianCoords(t.x,t.y,t.z)}setFromCartesianCoords(t,e,n){return this.radius=Math.sqrt(t*t+e*e+n*n),0===this.radius?(this.theta=0,this.phi=0):(this.theta=Math.atan2(t,n),this.phi=Math.acos(_t(e/this.radius,-1,1))),this}clone(){return(new this.constructor).copy(this)}},t.SphericalHarmonics3=Uc,t.SplineCurve=Xo,t.SpotLight=Lc,t.SpotLightHelper=class extends Qe{constructor(t,e){super(),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.color=e;const n=new Nn,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 t=0,e=1,n=32;t<n;t++,e++){const r=t/n*Math.PI*2,s=e/n*Math.PI*2;i.push(Math.cos(r),Math.sin(r),1,Math.cos(s),Math.sin(s),1)}n.setAttribute("position",new Tn(i,3));const r=new Za({fog:!1,toneMapped:!1});this.cone=new so(n,r),this.add(this.cone),this.update()}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose()}update(){this.light.updateMatrixWorld();const t=this.light.distance?this.light.distance:1e3,e=t*Math.tan(this.light.angle);this.cone.scale.set(e,e,t),Hh.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(Hh),void 0!==this.color?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}},t.Sprite=Ra,t.SpriteMaterial=ma,t.SrcAlphaFactor=204,t.SrcAlphaSaturateFactor=210,t.SrcColorFactor=202,t.StaticCopyUsage=35046,t.StaticDrawUsage=ht,t.StaticReadUsage=35045,t.StereoCamera=class{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new ai,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new ai,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,nh.copy(t.projectionMatrix);const n=e.eyeSep/2,i=n*e.near/e.focus,r=e.near*Math.tan(vt*e.fov*.5)/e.zoom;let s,a;eh.elements[12]=-n,th.elements[12]=n,s=-r*e.aspect+i,a=r*e.aspect+i,nh.elements[0]=2*e.near/(a-s),nh.elements[8]=(a+s)/(a-s),this.cameraL.projectionMatrix.copy(nh),s=-r*e.aspect-i,a=r*e.aspect-i,nh.elements[0]=2*e.near/(a-s),nh.elements[8]=(a+s)/(a-s),this.cameraR.projectionMatrix.copy(nh)}this.cameraL.matrixWorld.copy(t.matrixWorld).multiply(eh),this.cameraR.matrixWorld.copy(t.matrixWorld).multiply(th)}},t.StreamCopyUsage=35042,t.StreamDrawUsage=35040,t.StreamReadUsage=35041,t.StringKeyframeTrack=lc,t.SubtractEquation=101,t.SubtractiveBlending=3,t.TOUCH={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},t.TangentSpaceNormalMap=0,t.TetrahedronBufferGeometry=Nl,t.TetrahedronGeometry=Nl,t.TextGeometry=function(){return console.error("THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js"),new Nn},t.Texture=Vt,t.TextureLoader=Mc,t.TorusBufferGeometry=Bl,t.TorusGeometry=Bl,t.TorusKnotBufferGeometry=zl,t.TorusKnotGeometry=zl,t.Triangle=hn,t.TriangleFanDrawMode=2,t.TriangleStripDrawMode=1,t.TrianglesDrawMode=0,t.TubeBufferGeometry=Ol,t.TubeGeometry=Ol,t.UVMapping=i,t.Uint16Attribute=function(t,e){return console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead."),new Mn(t,e)},t.Uint16BufferAttribute=Mn,t.Uint32Attribute=function(t,e){return console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead."),new wn(t,e)},t.Uint32BufferAttribute=wn,t.Uint8Attribute=function(t,e){return console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead."),new yn(t,e)},t.Uint8BufferAttribute=yn,t.Uint8ClampedAttribute=function(t,e){return console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead."),new xn(t,e)},t.Uint8ClampedBufferAttribute=xn,t.Uniform=Ch,t.UniformsLib=bi,t.UniformsUtils=ii,t.UnsignedByteType=x,t.UnsignedInt248Type=S,t.UnsignedIntType=M,t.UnsignedShort4444Type=1017,t.UnsignedShort5551Type=1018,t.UnsignedShortType=_,t.VSMShadowMap=3,t.Vector2=At,t.Vector3=Zt,t.Vector4=jt,t.VectorKeyframeTrack=cc,t.Vertex=function(t,e,n){return console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead."),new Zt(t,e,n)},t.VertexColors=2,t.VideoTexture=fo,t.WebGL1Renderer=oa,t.WebGLCubeRenderTarget=hi,t.WebGLMultipleRenderTargets=Xt,t.WebGLMultisampleRenderTarget=Jt,t.WebGLRenderTarget=qt,t.WebGLRenderTargetCube=function(t,e,n){return console.warn("THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options )."),new hi(t,n)},t.WebGLRenderer=aa,t.WebGLUtils=Qs,t.WireframeGeometry=Fl,t.WireframeHelper=function(t,e){return console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead."),new so(new Fl(t.geometry),new Za({color:void 0!==e?e:16777215}))},t.WrapAroundEnding=rt,t.XHRLoader=function(t){return console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader."),new vc(t)},t.ZeroCurvatureEnding=nt,t.ZeroFactor=200,t.ZeroSlopeEnding=it,t.ZeroStencilOp=0,t._SRGBAFormat=pt,t.sRGBEncoding=lt,Object.defineProperty(t,"__esModule",{value:!0})}));

build/three.module.js

@@ -1,9 +1,9 @@
/**
* @license
- * Copyright 2010-2021 Three.js Authors
+ * Copyright 2010-2022 Three.js Authors
* SPDX-License-Identifier: MIT
*/
-const REVISION = '136';
+const REVISION = '137';
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;
@@ -89,10 +89,8 @@
const HalfFloatType = 1016;
const UnsignedShort4444Type = 1017;
const UnsignedShort5551Type = 1018;
-const UnsignedShort565Type = 1019;
const UnsignedInt248Type = 1020;
const AlphaFormat = 1021;
-const RGBFormat = 1022;
const RGBAFormat = 1023;
const LuminanceFormat = 1024;
const LuminanceAlphaFormat = 1025;
@@ -102,7 +100,6 @@
const RedIntegerFormat = 1029;
const RGFormat = 1030;
const RGIntegerFormat = 1031;
-const RGBIntegerFormat = 1032;
const RGBAIntegerFormat = 1033;
const RGB_S3TC_DXT1_Format = 33776;
@@ -131,20 +128,6 @@
const RGBA_ASTC_12x10_Format = 37820;
const RGBA_ASTC_12x12_Format = 37821;
const RGBA_BPTC_Format = 36492;
-const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
-const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
-const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
-const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
-const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
-const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
-const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
-const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
-const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
-const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
-const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
-const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
-const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
-const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
const LoopOnce = 2200;
const LoopRepeat = 2201;
const LoopPingPong = 2202;
@@ -197,6 +180,8 @@
const GLSL1 = '100';
const GLSL3 = '300 es';
+const _SRGBAFormat = 1035; // fallback for WebGL 1
+
/**
* https://github.com/mrdoob/eventdispatcher.js/
*/
@@ -1360,19 +1345,17 @@
Matrix3.prototype.isMatrix3 = true;
-function arrayMax( array ) {
-
- if ( array.length === 0 ) return - Infinity;
+function arrayNeedsUint32( array ) {
- let max = array[ 0 ];
+ // assumes larger values usually on last
- for ( let i = 1, l = array.length; i < l; ++ i ) {
+ for ( let i = array.length - 1; i >= 0; -- i ) {
- if ( array[ i ] > max ) max = array[ i ];
+ if ( array[ i ] > 65535 ) return true;
}
- return max;
+ return false;
}
@@ -1400,6 +1383,569 @@
}
+const _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, 'rebeccapurple': 0x663399, '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 };
+
+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;
+
+}
+
+function SRGBToLinear( c ) {
+
+ return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
+
+}
+
+function LinearToSRGB( c ) {
+
+ return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
+
+}
+
+class Color {
+
+ constructor( r, g, b ) {
+
+ if ( g === undefined && b === undefined ) {
+
+ // r is THREE.Color, hex or string
+ return this.set( r );
+
+ }
+
+ return this.setRGB( r, g, b );
+
+ }
+
+ set( value ) {
+
+ if ( value && value.isColor ) {
+
+ this.copy( value );
+
+ } else if ( typeof value === 'number' ) {
+
+ this.setHex( value );
+
+ } else if ( typeof value === 'string' ) {
+
+ this.setStyle( value );
+
+ }
+
+ return this;
+
+ }
+
+ setScalar( scalar ) {
+
+ this.r = scalar;
+ this.g = scalar;
+ this.b = scalar;
+
+ return this;
+
+ }
+
+ setHex( 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( r, g, b ) {
+
+ this.r = r;
+ this.g = g;
+ this.b = b;
+
+ return this;
+
+ }
+
+ setHSL( h, s, l ) {
+
+ // h,s,l ranges are in 0.0 - 1.0
+ 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 );
+
+ }
+
+ return this;
+
+ }
+
+ setStyle( style ) {
+
+ function handleAlpha( string ) {
+
+ if ( string === undefined ) return;
+
+ if ( parseFloat( string ) < 1 ) {
+
+ console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
+
+ }
+
+ }
+
+
+ let m;
+
+ if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
+
+ // rgb / hsl
+
+ 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 ) ) {
+
+ // rgb(255,0,0) rgba(255,0,0,0.5)
+ 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;
+
+ handleAlpha( color[ 4 ] );
+
+ return this;
+
+ }
+
+ if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
+
+ // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
+ 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;
+
+ handleAlpha( color[ 4 ] );
+
+ return this;
+
+ }
+
+ break;
+
+ case 'hsl':
+ case 'hsla':
+
+ if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
+
+ // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
+ const h = parseFloat( color[ 1 ] ) / 360;
+ const s = parseInt( color[ 2 ], 10 ) / 100;
+ const l = parseInt( color[ 3 ], 10 ) / 100;
+
+ handleAlpha( color[ 4 ] );
+
+ return this.setHSL( h, s, l );
+
+ }
+
+ break;
+
+ }
+
+ } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
+
+ // hex color
+
+ const hex = m[ 1 ];
+ const size = hex.length;
+
+ if ( size === 3 ) {
+
+ // #ff0
+ this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
+ this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
+ this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
+
+ return this;
+
+ } else if ( size === 6 ) {
+
+ // #ff0000
+ this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
+ this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
+ this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
+
+ return this;
+
+ }
+
+ }
+
+ if ( style && style.length > 0 ) {
+
+ return this.setColorName( style );
+
+ }
+
+ return this;
+
+ }
+
+ setColorName( style ) {
+
+ // color keywords
+ const hex = _colorKeywords[ style.toLowerCase() ];
+
+ if ( hex !== undefined ) {
+
+ // red
+ this.setHex( hex );
+
+ } else {
+
+ // unknown color
+ console.warn( 'THREE.Color: Unknown color ' + style );
+
+ }
+
+ return this;
+
+ }
+
+ clone() {
+
+ return new this.constructor( this.r, this.g, this.b );
+
+ }
+
+ copy( color ) {
+
+ this.r = color.r;
+ this.g = color.g;
+ this.b = color.b;
+
+ return this;
+
+ }
+
+ copySRGBToLinear( color ) {
+
+ this.r = SRGBToLinear( color.r );
+ this.g = SRGBToLinear( color.g );
+ this.b = SRGBToLinear( color.b );
+
+ return this;
+
+ }
+
+ copyLinearToSRGB( color ) {
+
+ this.r = LinearToSRGB( color.r );
+ this.g = LinearToSRGB( color.g );
+ this.b = LinearToSRGB( color.b );
+
+ return this;
+
+ }
+
+ convertSRGBToLinear() {
+
+ this.copySRGBToLinear( this );
+
+ return this;
+
+ }
+
+ convertLinearToSRGB() {
+
+ this.copyLinearToSRGB( this );
+
+ return this;
+
+ }
+
+ getHex() {
+
+ return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
+
+ }
+
+ getHexString() {
+
+ return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
+
+ }
+
+ getHSL( target ) {
+
+ // h,s,l ranges are in 0.0 - 1.0
+
+ const r = this.r, g = this.g, b = this.b;
+
+ const max = Math.max( r, g, b );
+ const min = Math.min( r, g, b );
+
+ let hue, saturation;
+ const lightness = ( min + max ) / 2.0;
+
+ 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;
+
+ }
+
+ getStyle() {
+
+ return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
+
+ }
+
+ offsetHSL( h, s, l ) {
+
+ this.getHSL( _hslA );
+
+ _hslA.h += h; _hslA.s += s; _hslA.l += l;
+
+ this.setHSL( _hslA.h, _hslA.s, _hslA.l );
+
+ return this;
+
+ }
+
+ add( color ) {
+
+ this.r += color.r;
+ this.g += color.g;
+ this.b += color.b;
+
+ return this;
+
+ }
+
+ addColors( color1, color2 ) {
+
+ this.r = color1.r + color2.r;
+ this.g = color1.g + color2.g;
+ this.b = color1.b + color2.b;
+
+ return this;
+
+ }
+
+ addScalar( s ) {
+
+ this.r += s;
+ this.g += s;
+ this.b += s;
+
+ return this;
+
+ }
+
+ 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;
+
+ }
+
+ multiply( color ) {
+
+ this.r *= color.r;
+ this.g *= color.g;
+ this.b *= color.b;
+
+ return this;
+
+ }
+
+ multiplyScalar( s ) {
+
+ this.r *= s;
+ this.g *= s;
+ this.b *= s;
+
+ return this;
+
+ }
+
+ 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;
+
+ }
+
+ 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;
+
+ }
+
+ 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;
+
+ }
+
+ equals( c ) {
+
+ return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
+
+ }
+
+ fromArray( array, offset = 0 ) {
+
+ this.r = array[ offset ];
+ this.g = array[ offset + 1 ];
+ this.b = array[ offset + 2 ];
+
+ return this;
+
+ }
+
+ toArray( array = [], offset = 0 ) {
+
+ array[ offset ] = this.r;
+ array[ offset + 1 ] = this.g;
+ array[ offset + 2 ] = this.b;
+
+ return array;
+
+ }
+
+ fromBufferAttribute( attribute, index ) {
+
+ this.r = attribute.getX( index );
+ this.g = attribute.getY( index );
+ this.b = attribute.getZ( index );
+
+ if ( attribute.normalized === true ) {
+
+ // assuming Uint8Array
+
+ this.r /= 255;
+ this.g /= 255;
+ this.b /= 255;
+
+ }
+
+ return this;
+
+ }
+
+ toJSON() {
+
+ return this.getHex();
+
+ }
+
+}
+
+Color.NAMES = _colorKeywords;
+
+Color.prototype.isColor = true;
+Color.prototype.r = 1;
+Color.prototype.g = 1;
+Color.prototype.b = 1;
+
let _canvas;
class ImageUtils {
@@ -1461,6 +2007,68 @@
}
+ 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 {
+
+ // assuming float
+
+ data[ i ] = SRGBToLinear( data[ i ] );
+
+ }
+
+ }
+
+ return {
+ data: data,
+ width: image.width,
+ height: image.height
+ };
+
+ } else {
+
+ console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
+ return image;
+
+ }
+
+ }
+
}
let textureId = 0;
@@ -1518,7 +2126,8 @@
this.version = 0;
this.onUpdate = null;
- this.isRenderTargetTexture = false;
+ this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
+ this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
}
@@ -2568,7 +3177,10 @@
this.viewport.copy( source.viewport );
this.texture = source.texture.clone();
- this.texture.image = { ...this.texture.image }; // See #20328.
+
+ // ensure image object is not shared, see #20328
+
+ this.texture.image = Object.assign( {}, source.texture.image );
this.depthBuffer = source.depthBuffer;
this.stencilBuffer = source.stencilBuffer;
@@ -3298,7 +3910,7 @@
slerpQuaternions( qa, qb, t ) {
- this.copy( qa ).slerp( qb, t );
+ return this.copy( qa ).slerp( qb, t );
}
@@ -4230,11 +4842,11 @@
}
- setFromObject( object ) {
+ setFromObject( object, precise = false ) {
this.makeEmpty();
- return this.expandByObject( object );
+ return this.expandByObject( object, precise );
}
@@ -4309,7 +4921,7 @@
}
- expandByObject( object ) {
+ expandByObject( object, precise = false ) {
// Computes the world-axis-aligned bounding box of an object (including its children),
// accounting for both the object's, and children's, world transforms
@@ -4320,6 +4932,18 @@
if ( geometry !== undefined ) {
+ if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
+
+ const position = geometry.attributes.position;
+ for ( let i = 0, l = position.count; i < l; i ++ ) {
+
+ _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
+ this.expandByPoint( _vector$b );
+
+ }
+
+ } else {
+
if ( geometry.boundingBox === null ) {
geometry.computeBoundingBox();
@@ -4333,11 +4957,13 @@
}
+ }
+
const children = object.children;
for ( let i = 0, l = children.length; i < l; i ++ ) {
- this.expandByObject( children[ i ] );
+ this.expandByObject( children[ i ], precise );
}
@@ -7841,7 +8467,6 @@
this.vertexColors = false;
this.opacity = 1;
- this.format = RGBAFormat;
this.transparent = false;
this.blendSrc = SrcAlphaFactor;
@@ -7871,6 +8496,7 @@
this.shadowSide = null;
this.colorWrite = true;
+ this.alphaWrite = true;
this.precision = null; // override the renderer's default precision for this material
@@ -8123,13 +8749,13 @@
if ( this.vertexColors ) data.vertexColors = true;
if ( this.opacity < 1 ) data.opacity = this.opacity;
- if ( this.format !== RGBAFormat ) data.format = this.format;
if ( this.transparent === true ) data.transparent = this.transparent;
data.depthFunc = this.depthFunc;
data.depthTest = this.depthTest;
data.depthWrite = this.depthWrite;
data.colorWrite = this.colorWrite;
+ data.alphaWrite = this.alphaWrite;
data.stencilWrite = this.stencilWrite;
data.stencilWriteMask = this.stencilWriteMask;
@@ -8220,7 +8846,6 @@
this.vertexColors = source.vertexColors;
this.opacity = source.opacity;
- this.format = source.format;
this.transparent = source.transparent;
this.blendSrc = source.blendSrc;
@@ -8266,6 +8891,7 @@
this.shadowSide = source.shadowSide;
this.colorWrite = source.colorWrite;
+ this.alphaWrite = source.alphaWrite;
this.precision = source.precision;
@@ -8305,569 +8931,6 @@
Material.prototype.isMaterial = true;
-const _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, 'rebeccapurple': 0x663399, '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 };
-
-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;
-
-}
-
-function SRGBToLinear( c ) {
-
- return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
-
-}
-
-function LinearToSRGB( c ) {
-
- return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
-
-}
-
-class Color {
-
- constructor( r, g, b ) {
-
- if ( g === undefined && b === undefined ) {
-
- // r is THREE.Color, hex or string
- return this.set( r );
-
- }
-
- return this.setRGB( r, g, b );
-
- }
-
- set( value ) {
-
- if ( value && value.isColor ) {
-
- this.copy( value );
-
- } else if ( typeof value === 'number' ) {
-
- this.setHex( value );
-
- } else if ( typeof value === 'string' ) {
-
- this.setStyle( value );
-
- }
-
- return this;
-
- }
-
- setScalar( scalar ) {
-
- this.r = scalar;
- this.g = scalar;
- this.b = scalar;
-
- return this;
-
- }
-
- setHex( 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( r, g, b ) {
-
- this.r = r;
- this.g = g;
- this.b = b;
-
- return this;
-
- }
-
- setHSL( h, s, l ) {
-
- // h,s,l ranges are in 0.0 - 1.0
- 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 );
-
- }
-
- return this;
-
- }
-
- setStyle( style ) {
-
- function handleAlpha( string ) {
-
- if ( string === undefined ) return;
-
- if ( parseFloat( string ) < 1 ) {
-
- console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
-
- }
-
- }
-
-
- let m;
-
- if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
-
- // rgb / hsl
-
- 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 ) ) {
-
- // rgb(255,0,0) rgba(255,0,0,0.5)
- 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;
-
- handleAlpha( color[ 4 ] );
-
- return this;
-
- }
-
- if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
-
- // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
- 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;
-
- handleAlpha( color[ 4 ] );
-
- return this;
-
- }
-
- break;
-
- case 'hsl':
- case 'hsla':
-
- if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
-
- // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
- const h = parseFloat( color[ 1 ] ) / 360;
- const s = parseInt( color[ 2 ], 10 ) / 100;
- const l = parseInt( color[ 3 ], 10 ) / 100;
-
- handleAlpha( color[ 4 ] );
-
- return this.setHSL( h, s, l );
-
- }
-
- break;
-
- }
-
- } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
-
- // hex color
-
- const hex = m[ 1 ];
- const size = hex.length;
-
- if ( size === 3 ) {
-
- // #ff0
- this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
- this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
- this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
-
- return this;
-
- } else if ( size === 6 ) {
-
- // #ff0000
- this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
- this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
- this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
-
- return this;
-
- }
-
- }
-
- if ( style && style.length > 0 ) {
-
- return this.setColorName( style );
-
- }
-
- return this;
-
- }
-
- setColorName( style ) {
-
- // color keywords
- const hex = _colorKeywords[ style.toLowerCase() ];
-
- if ( hex !== undefined ) {
-
- // red
- this.setHex( hex );
-
- } else {
-
- // unknown color
- console.warn( 'THREE.Color: Unknown color ' + style );
-
- }
-
- return this;
-
- }
-
- clone() {
-
- return new this.constructor( this.r, this.g, this.b );
-
- }
-
- copy( color ) {
-
- this.r = color.r;
- this.g = color.g;
- this.b = color.b;
-
- return this;
-
- }
-
- copySRGBToLinear( color ) {
-
- this.r = SRGBToLinear( color.r );
- this.g = SRGBToLinear( color.g );
- this.b = SRGBToLinear( color.b );
-
- return this;
-
- }
-
- copyLinearToSRGB( color ) {
-
- this.r = LinearToSRGB( color.r );
- this.g = LinearToSRGB( color.g );
- this.b = LinearToSRGB( color.b );
-
- return this;
-
- }
-
- convertSRGBToLinear() {
-
- this.copySRGBToLinear( this );
-
- return this;
-
- }
-
- convertLinearToSRGB() {
-
- this.copyLinearToSRGB( this );
-
- return this;
-
- }
-
- getHex() {
-
- return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
-
- }
-
- getHexString() {
-
- return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
-
- }
-
- getHSL( target ) {
-
- // h,s,l ranges are in 0.0 - 1.0
-
- const r = this.r, g = this.g, b = this.b;
-
- const max = Math.max( r, g, b );
- const min = Math.min( r, g, b );
-
- let hue, saturation;
- const lightness = ( min + max ) / 2.0;
-
- 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;
-
- }
-
- getStyle() {
-
- return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
-
- }
-
- offsetHSL( h, s, l ) {
-
- this.getHSL( _hslA );
-
- _hslA.h += h; _hslA.s += s; _hslA.l += l;
-
- this.setHSL( _hslA.h, _hslA.s, _hslA.l );
-
- return this;
-
- }
-
- add( color ) {
-
- this.r += color.r;
- this.g += color.g;
- this.b += color.b;
-
- return this;
-
- }
-
- addColors( color1, color2 ) {
-
- this.r = color1.r + color2.r;
- this.g = color1.g + color2.g;
- this.b = color1.b + color2.b;
-
- return this;
-
- }
-
- addScalar( s ) {
-
- this.r += s;
- this.g += s;
- this.b += s;
-
- return this;
-
- }
-
- 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;
-
- }
-
- multiply( color ) {
-
- this.r *= color.r;
- this.g *= color.g;
- this.b *= color.b;
-
- return this;
-
- }
-
- multiplyScalar( s ) {
-
- this.r *= s;
- this.g *= s;
- this.b *= s;
-
- return this;
-
- }
-
- 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;
-
- }
-
- 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;
-
- }
-
- 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;
-
- }
-
- equals( c ) {
-
- return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
-
- }
-
- fromArray( array, offset = 0 ) {
-
- this.r = array[ offset ];
- this.g = array[ offset + 1 ];
- this.b = array[ offset + 2 ];
-
- return this;
-
- }
-
- toArray( array = [], offset = 0 ) {
-
- array[ offset ] = this.r;
- array[ offset + 1 ] = this.g;
- array[ offset + 2 ] = this.b;
-
- return array;
-
- }
-
- fromBufferAttribute( attribute, index ) {
-
- this.r = attribute.getX( index );
- this.g = attribute.getY( index );
- this.b = attribute.getZ( index );
-
- if ( attribute.normalized === true ) {
-
- // assuming Uint8Array
-
- this.r /= 255;
- this.g /= 255;
- this.b /= 255;
-
- }
-
- return this;
-
- }
-
- toJSON() {
-
- return this.getHex();
-
- }
-
-}
-
-Color.NAMES = _colorKeywords;
-
-Color.prototype.isColor = true;
-Color.prototype.r = 1;
-Color.prototype.g = 1;
-Color.prototype.b = 1;
-
/**
* parameters = {
* color: <hex>,
@@ -9525,7 +9588,7 @@
if ( Array.isArray( index ) ) {
- this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
+ this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
} else {
@@ -11818,6 +11881,8 @@
renderer.xr.enabled = currentXrEnabled;
+ renderTarget.texture.needsPMREMUpdate = true;
+
}
}
@@ -11881,8 +11946,6 @@
this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
- this.texture._needsFlipEnvMap = false;
-
}
fromEquirectangularTexture( renderer, texture ) {
@@ -12725,15 +12788,15 @@
var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
-var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
+var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
-var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
+var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
-var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
+var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
@@ -12753,7 +12816,7 @@
var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
-var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
+var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
@@ -12771,13 +12834,13 @@
var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
-var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\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\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= specularColorMapTexelToLinear( texture2D( specularColorMap, vUv ) ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= sheenColorMapTexelToLinear( texture2D( sheenColorMap, vUv ) ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
+var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\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\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\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\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
-var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
+var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
@@ -12789,11 +12852,11 @@
var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
-var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
+var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
-var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
+var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
@@ -12801,11 +12864,11 @@
var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
-var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
+var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
-var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
+var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
@@ -12867,7 +12930,7 @@
var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif";
-var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
+var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
@@ -12885,7 +12948,7 @@
const vertex$g = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
-const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
+const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
const vertex$f = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
@@ -12901,7 +12964,7 @@
const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
-const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
+const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
@@ -12909,7 +12972,7 @@
const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
-const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
+const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
const vertex$9 = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
@@ -12917,7 +12980,7 @@
const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
-const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
+const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
@@ -13590,7 +13653,7 @@
sheen: { value: 0 },
sheenColor: { value: new Color( 0x000000 ) },
sheenColorMap: { value: null },
- sheenRoughness: { value: 0 },
+ sheenRoughness: { value: 1 },
sheenRoughnessMap: { value: null },
transmission: { value: 0 },
transmissionMap: { value: null },
@@ -13600,7 +13663,7 @@
thicknessMap: { value: null },
attenuationDistance: { value: 0 },
attenuationColor: { value: new Color( 0x000000 ) },
- specularIntensity: { value: 0 },
+ specularIntensity: { value: 1 },
specularIntensityMap: { value: null },
specularColor: { value: new Color( 1, 1, 1 ) },
specularColorMap: { value: null },
@@ -13612,10 +13675,10 @@
};
-function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
+function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipliedAlpha ) {
const clearColor = new Color( 0x000000 );
- let clearAlpha = 0;
+ let clearAlpha = alpha === true ? 0 : 1;
let planeMesh;
let boxMesh;
@@ -14798,14 +14861,10 @@
if ( image && image.height > 0 ) {
- const currentRenderTarget = renderer.getRenderTarget();
-
const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
renderTarget.fromEquirectangularTexture( renderer, texture );
cubemaps.set( texture, renderTarget );
- renderer.setRenderTarget( currentRenderTarget );
-
texture.addEventListener( 'dispose', onTextureDispose );
return mapTextureMapping( renderTarget.texture, texture.mapping );
@@ -15021,11 +15080,6 @@
// samples and exit early, but not recompile the shader.
const MAX_SAMPLES = 20;
-const ENCODINGS = {
- [ LinearEncoding ]: 0,
- [ sRGBEncoding ]: 1
-};
-
const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
const _clearColor = /*@__PURE__*/ new Color();
@@ -15110,9 +15164,9 @@
* or HDR. The ideal input image size is 1k (1024 x 512),
* as this matches best with the 256 x 256 cubemap output.
*/
- fromEquirectangular( equirectangular ) {
+ fromEquirectangular( equirectangular, renderTarget = null ) {
- return this._fromTexture( equirectangular );
+ return this._fromTexture( equirectangular, renderTarget );
}
@@ -15121,9 +15175,9 @@
* or HDR. The ideal input cube size is 256 x 256,
* as this matches best with the 256 x 256 cubemap output.
*/
- fromCubemap( cubemap ) {
+ fromCubemap( cubemap, renderTarget = null ) {
- return this._fromTexture( cubemap );
+ return this._fromTexture( cubemap, renderTarget );
}
@@ -15166,6 +15220,8 @@
this._blurMaterial.dispose();
+ if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
+
if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
if ( this._equirectShader !== null ) this._equirectShader.dispose();
@@ -15181,17 +15237,16 @@
_cleanup( outputTarget ) {
- this._pingPongRenderTarget.dispose();
this._renderer.setRenderTarget( _oldTarget );
outputTarget.scissorTest = false;
_setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
}
- _fromTexture( texture ) {
+ _fromTexture( texture, renderTarget ) {
_oldTarget = this._renderer.getRenderTarget();
- const cubeUVRenderTarget = this._allocateTargets( texture );
+ const cubeUVRenderTarget = renderTarget || this._allocateTargets( texture );
this._textureToCubeUV( texture, cubeUVRenderTarget );
this._applyPMREM( cubeUVRenderTarget );
this._cleanup( cubeUVRenderTarget );
@@ -15214,7 +15269,13 @@
const cubeUVRenderTarget = _createRenderTarget( params );
cubeUVRenderTarget.depthBuffer = texture ? false : true;
+
+ if ( this._pingPongRenderTarget === null ) {
+
this._pingPongRenderTarget = _createRenderTarget( params );
+
+ }
+
return cubeUVRenderTarget;
}
@@ -15274,12 +15335,12 @@
for ( let i = 0; i < 6; i ++ ) {
const col = i % 3;
- if ( col == 0 ) {
+ if ( col === 0 ) {
cubeCamera.up.set( 0, upSign[ i ], 0 );
cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
- } else if ( col == 1 ) {
+ } else if ( col === 1 ) {
cubeCamera.up.set( 0, 0, upSign[ i ] );
cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
@@ -15314,20 +15375,6 @@
}
- _setEncoding( uniform, texture ) {
-
- if ( this._renderer.capabilities.isWebGL2 === true && texture.format === RGBAFormat && texture.type === UnsignedByteType && texture.encoding === sRGBEncoding ) {
-
- uniform.value = ENCODINGS[ LinearEncoding ];
-
- } else {
-
- uniform.value = ENCODINGS[ texture.encoding ];
-
- }
-
- }
-
_textureToCubeUV( texture, cubeUVRenderTarget ) {
const renderer = this._renderer;
@@ -15336,15 +15383,17 @@
if ( isCubeTexture ) {
- if ( this._cubemapShader == null ) {
+ if ( this._cubemapShader === null ) {
this._cubemapShader = _getCubemapShader();
}
+ this._cubemapShader.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
+
} else {
- if ( this._equirectShader == null ) {
+ if ( this._equirectShader === null ) {
this._equirectShader = _getEquirectShader();
@@ -15365,8 +15414,6 @@
}
- this._setEncoding( uniforms[ 'inputEncoding' ], texture );
-
_setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
renderer.setRenderTarget( cubeUVRenderTarget );
@@ -15465,7 +15512,7 @@
const weight = Math.exp( - x * x / 2 );
weights.push( weight );
- if ( i == 0 ) {
+ if ( i === 0 ) {
sum += weight;
@@ -15527,7 +15574,7 @@
sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
- } else if ( i == 0 ) {
+ } else if ( i === 0 ) {
sigma = 0;
@@ -15641,8 +15688,6 @@
uniform float mipInt;
uniform vec3 poleAxis;
- ${ _getEncodings() }
-
#define ENVMAP_TYPE_CUBE_UV
#include <cube_uv_reflection_fragment>
@@ -15709,8 +15754,7 @@
uniforms: {
'envMap': { value: null },
- 'texelSize': { value: texelSize },
- 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }
+ 'texelSize': { value: texelSize }
},
vertexShader: _getCommonVertexShader(),
@@ -15725,8 +15769,6 @@
uniform sampler2D envMap;
uniform vec2 texelSize;
- ${ _getEncodings() }
-
#include <common>
void main() {
@@ -15738,13 +15780,13 @@
vec2 f = fract( uv / texelSize - 0.5 );
uv -= f * texelSize;
- vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
+ vec3 tl = texture2D ( envMap, uv ).rgb;
uv.x += texelSize.x;
- vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
+ vec3 tr = texture2D ( envMap, uv ).rgb;
uv.y += texelSize.y;
- vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
+ vec3 br = texture2D ( envMap, uv ).rgb;
uv.x -= texelSize.x;
- vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
+ vec3 bl = texture2D ( envMap, uv ).rgb;
vec3 tm = mix( tl, tr, f.x );
vec3 bm = mix( bl, br, f.x );
@@ -15771,7 +15813,7 @@
uniforms: {
'envMap': { value: null },
- 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }
+ 'flipEnvMap': { value: - 1 }
},
vertexShader: _getCommonVertexShader(),
@@ -15781,15 +15823,15 @@
precision mediump float;
precision mediump int;
+ uniform float flipEnvMap;
+
varying vec3 vOutputDirection;
uniform samplerCube envMap;
- ${ _getEncodings() }
-
void main() {
- gl_FragColor = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) );
+ gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
}
`,
@@ -15867,37 +15909,6 @@
}
-function _getEncodings() {
-
- return /* glsl */`
-
- uniform int inputEncoding;
-
- #include <encodings_pars_fragment>
-
- vec4 inputTexelToLinear( vec4 value ) {
-
- if ( inputEncoding == 0 ) {
-
- return value;
-
- } else {
-
- return sRGBToLinear( value );
-
- }
-
- }
-
- vec4 envMapTexelToLinear( vec4 color ) {
-
- return inputTexelToLinear( color );
-
- }
- `;
-
-}
-
function WebGLCubeUVMaps( renderer ) {
let cubeUVmaps = new WeakMap();
@@ -15906,16 +15917,31 @@
function get( texture ) {
- if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
+ if ( texture && texture.isTexture ) {
const mapping = texture.mapping;
const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
+ // equirect/cube map to cubeUV conversion
+
if ( isEquirectMap || isCubeMap ) {
- // equirect/cube map to cubeUV conversion
+ if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
+
+ texture.needsPMREMUpdate = false;
+
+ let renderTarget = cubeUVmaps.get( texture );
+
+ if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
+
+ renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
+ cubeUVmaps.set( texture, renderTarget );
+
+ return renderTarget.texture;
+
+ } else {
if ( cubeUVmaps.has( texture ) ) {
@@ -15927,15 +15953,11 @@
if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
- const currentRenderTarget = renderer.getRenderTarget();
-
if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
cubeUVmaps.set( texture, renderTarget );
- renderer.setRenderTarget( currentRenderTarget );
-
texture.addEventListener( 'dispose', onTextureDispose );
return renderTarget.texture;
@@ -15954,6 +15976,8 @@
}
+ }
+
return texture;
}
@@ -16237,7 +16261,7 @@
}
- const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
+ const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
attribute.version = version;
// Updating index buffer in VAO now. See WebGLBindingStates
@@ -16589,6 +16613,18 @@
morphTextures.set( geometry, entry );
+ function disposeTexture() {
+
+ texture.dispose();
+
+ morphTextures.delete( geometry );
+
+ geometry.removeEventListener( 'dispose', disposeTexture );
+
+ }
+
+ geometry.addEventListener( 'dispose', disposeTexture );
+
}
//
@@ -17905,13 +17941,6 @@
}
-function getTexelDecodingFunction( functionName, encoding ) {
-
- const components = getEncodingComponents( encoding );
- return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
-
-}
-
function getTexelEncodingFunction( functionName, encoding ) {
const components = getEncodingComponents( encoding );
@@ -18481,6 +18510,8 @@
parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
+ parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
+
parameters.vertexTangents ? '#define USE_TANGENT' : '',
parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
@@ -18515,16 +18546,9 @@
( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
parameters.dithering ? '#define DITHERING' : '',
- parameters.format === RGBFormat ? '#define OPAQUE' : '',
+ parameters.alphaWrite ? '' : '#define OPAQUE',
ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
- parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
- parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
- parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
- parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
- parameters.specularColorMap ? getTexelDecodingFunction( 'specularColorMapTexelToLinear', parameters.specularColorMapEncoding ) : '',
- parameters.sheenColorMap ? getTexelDecodingFunction( 'sheenColorMapTexelToLinear', parameters.sheenColorMapEncoding ) : '',
- parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
@@ -18919,35 +18943,6 @@
}
- function getTextureEncodingFromMap( map ) {
-
- let encoding;
-
- if ( map && map.isTexture ) {
-
- encoding = map.encoding;
-
- } else if ( map && map.isWebGLRenderTarget ) {
-
- console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
- encoding = map.texture.encoding;
-
- } else {
-
- encoding = LinearEncoding;
-
- }
-
- if ( isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding ) {
-
- encoding = LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
-
- }
-
- return encoding;
-
- }
-
function getParameters( material, lights, shadows, scene, object ) {
const fog = scene.fog;
@@ -19024,25 +19019,22 @@
instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
supportsVertexTextures: vertexTextures,
- outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
+ outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
map: !! material.map,
- mapEncoding: getTextureEncodingFromMap( material.map ),
matcap: !! material.matcap,
- matcapEncoding: getTextureEncodingFromMap( material.matcap ),
envMap: !! envMap,
envMapMode: envMap && envMap.mapping,
- envMapEncoding: getTextureEncodingFromMap( envMap ),
envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
lightMap: !! material.lightMap,
- lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
aoMap: !! material.aoMap,
emissiveMap: !! material.emissiveMap,
- emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
bumpMap: !! material.bumpMap,
normalMap: !! material.normalMap,
objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
+ decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
+
clearcoat: useClearcoat,
clearcoatMap: useClearcoat && !! material.clearcoatMap,
clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
@@ -19054,16 +19046,15 @@
specularMap: !! material.specularMap,
specularIntensityMap: !! material.specularIntensityMap,
specularColorMap: !! material.specularColorMap,
- specularColorMapEncoding: getTextureEncodingFromMap( material.specularColorMap ),
alphaMap: !! material.alphaMap,
alphaTest: useAlphaTest,
+ alphaWrite: material.alphaWrite || material.transparent,
gradientMap: !! material.gradientMap,
sheen: material.sheen > 0,
sheenColorMap: !! material.sheenColorMap,
- sheenColorMapEncoding: getTextureEncodingFromMap( material.sheenColorMap ),
sheenRoughnessMap: !! material.sheenRoughnessMap,
transmission: material.transmission > 0,
@@ -19108,7 +19099,6 @@
numClippingPlanes: clipping.numPlanes,
numClipIntersection: clipping.numIntersection,
- format: material.format,
dithering: material.dithering,
shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
@@ -19187,12 +19177,7 @@
array.push( parameters.precision );
array.push( parameters.outputEncoding );
- array.push( parameters.mapEncoding );
- array.push( parameters.matcapEncoding );
array.push( parameters.envMapMode );
- array.push( parameters.envMapEncoding );
- array.push( parameters.lightMapEncoding );
- array.push( parameters.emissiveMapEncoding );
array.push( parameters.combine );
array.push( parameters.vertexUvs );
array.push( parameters.fogExp2 );
@@ -19211,9 +19196,7 @@
array.push( parameters.toneMapping );
array.push( parameters.numClippingPlanes );
array.push( parameters.numClipIntersection );
- array.push( parameters.format );
- array.push( parameters.specularColorMapEncoding );
- array.push( parameters.sheenColorMapEncoding );
+ array.push( parameters.alphaWrite );
}
@@ -19333,6 +19316,8 @@
_programLayers.enable( 20 );
if ( parameters.sheenRoughnessMap )
_programLayers.enable( 21 );
+ if ( parameters.decodeVideoTexture )
+ _programLayers.enable( 22 );
array.push( _programLayers.mask );
@@ -21180,6 +21165,8 @@
let enabledCapabilities = {};
let currentBoundFramebuffers = {};
+ let currentDrawbuffers = new WeakMap();
+ let defaultDrawbuffers = [];
let currentProgram = null;
@@ -21324,6 +21311,82 @@
}
+ function drawBuffers( renderTarget, framebuffer ) {
+
+ let drawBuffers = defaultDrawbuffers;
+
+ let needsUpdate = false;
+
+ if ( renderTarget ) {
+
+ drawBuffers = currentDrawbuffers.get( framebuffer );
+
+ if ( drawBuffers === undefined ) {
+
+ drawBuffers = [];
+ currentDrawbuffers.set( framebuffer, drawBuffers );
+
+ }
+
+ if ( renderTarget.isWebGLMultipleRenderTargets ) {
+
+ const textures = renderTarget.texture;
+
+ if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) {
+
+ for ( let i = 0, il = textures.length; i < il; i ++ ) {
+
+ drawBuffers[ i ] = 36064 + i;
+
+ }
+
+ drawBuffers.length = textures.length;
+
+ needsUpdate = true;
+
+ }
+
+ } else {
+
+ if ( drawBuffers[ 0 ] !== 36064 ) {
+
+ drawBuffers[ 0 ] = 36064;
+
+ needsUpdate = true;
+
+ }
+
+ }
+
+ } else {
+
+ if ( drawBuffers[ 0 ] !== 1029 ) {
+
+ drawBuffers[ 0 ] = 1029;
+
+ needsUpdate = true;
+
+ }
+
+ }
+
+ if ( needsUpdate ) {
+
+ if ( capabilities.isWebGL2 ) {
+
+ gl.drawBuffers( drawBuffers );
+
+ } else {
+
+ extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
+
+ }
+
+ }
+
+
+ }
+
function useProgram( program ) {
if ( currentProgram !== program ) {
@@ -21426,7 +21489,7 @@
break;
case SubtractiveBlending:
- gl.blendFuncSeparate( 0, 0, 769, 771 );
+ gl.blendFuncSeparate( 0, 769, 0, 1 );
break;
case MultiplyBlending:
@@ -21452,7 +21515,7 @@
break;
case SubtractiveBlending:
- gl.blendFunc( 0, 769 );
+ gl.blendFuncSeparate( 0, 769, 0, 1 );
break;
case MultiplyBlending:
@@ -21910,6 +21973,8 @@
currentBoundTextures = {};
currentBoundFramebuffers = {};
+ currentDrawbuffers = new WeakMap();
+ defaultDrawbuffers = [];
currentProgram = null;
@@ -21952,6 +22017,7 @@
disable: disable,
bindFramebuffer: bindFramebuffer,
+ drawBuffers: drawBuffers,
useProgram: useProgram,
@@ -22116,7 +22182,7 @@
}
- function getInternalFormat( internalFormatName, glFormat, glType, encoding ) {
+ function getInternalFormat( internalFormatName, glFormat, glType, encoding, isVideoTexture = false ) {
if ( isWebGL2 === false ) return glFormat;
@@ -22138,11 +22204,11 @@
}
- if ( glFormat === 6407 ) {
+ if ( glFormat === 33319 ) {
- if ( glType === 5126 ) internalFormat = 34837;
- if ( glType === 5131 ) internalFormat = 34843;
- if ( glType === 5121 ) internalFormat = 32849;
+ if ( glType === 5126 ) internalFormat = 33328;
+ if ( glType === 5131 ) internalFormat = 33327;
+ if ( glType === 5121 ) internalFormat = 33323;
}
@@ -22150,11 +22216,14 @@
if ( glType === 5126 ) internalFormat = 34836;
if ( glType === 5131 ) internalFormat = 34842;
- if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding ) ? 35907 : 32856;
+ if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && isVideoTexture === false ) ? 35907 : 32856;
+ if ( glType === 32819 ) internalFormat = 32854;
+ if ( glType === 32820 ) internalFormat = 32855;
}
if ( internalFormat === 33325 || internalFormat === 33326 ||
+ internalFormat === 33327 || internalFormat === 33328 ||
internalFormat === 34842 || internalFormat === 34836 ) {
extensions.get( 'EXT_color_buffer_float' );
@@ -22536,13 +22605,14 @@
_gl.pixelStorei( 37443, 0 );
const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
- const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
+ let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
+ image = verifyColorSpace( texture, image );
const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
- glFormat = utils.convert( texture.format );
+ glFormat = utils.convert( texture.format, texture.encoding );
let glType = utils.convert( texture.type ),
- glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
+ glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
setTextureParameters( textureType, texture, supportsMips );
@@ -22703,7 +22773,7 @@
mipmap = mipmaps[ i ];
- if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
+ if ( texture.format !== RGBAFormat ) {
if ( glFormat !== null ) {
@@ -22886,11 +22956,13 @@
}
+ cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
+
}
const image = cubeImage[ 0 ],
supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
- glFormat = utils.convert( texture.format ),
+ glFormat = utils.convert( texture.format, texture.encoding ),
glType = utils.convert( texture.type ),
glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
@@ -22918,7 +22990,7 @@
const mipmap = mipmaps[ j ];
- if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
+ if ( texture.format !== RGBAFormat ) {
if ( glFormat !== null ) {
@@ -23055,7 +23127,7 @@
// Setup storage for target texture and bind it to correct framebuffer
function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
- const glFormat = utils.convert( texture.format );
+ const glFormat = utils.convert( texture.format, texture.encoding );
const glType = utils.convert( texture.type );
const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
const renderTargetProperties = properties.get( renderTarget );
@@ -23163,7 +23235,7 @@
// Use the first texture for MRT so far
const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture;
- const glFormat = utils.convert( texture.format );
+ const glFormat = utils.convert( texture.format, texture.encoding );
const glType = utils.convert( texture.type );
const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
const samples = getRenderTargetSamples( renderTarget );
@@ -23337,16 +23409,6 @@
const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
- // Handles WebGL2 RGBFormat fallback - #18858
-
- if ( isWebGL2 && texture.format === RGBFormat && ( texture.type === FloatType || texture.type === HalfFloatType ) ) {
-
- texture.format = RGBAFormat;
-
- console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
-
- }
-
// Setup framebuffer
if ( isCube ) {
@@ -23398,7 +23460,7 @@
_gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
- const glFormat = utils.convert( texture.format );
+ const glFormat = utils.convert( texture.format, texture.encoding );
const glType = utils.convert( texture.type );
const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
const samples = getRenderTargetSamples( renderTarget );
@@ -23617,6 +23679,65 @@
}
+ function verifyColorSpace( texture, image ) {
+
+ const encoding = texture.encoding;
+ const format = texture.format;
+ const type = texture.type;
+
+ if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
+
+ if ( encoding !== LinearEncoding ) {
+
+ // sRGB
+
+ if ( encoding === sRGBEncoding ) {
+
+ if ( isWebGL2 === false ) {
+
+ // in WebGL 1, try to use EXT_sRGB extension and unsized formats
+
+ if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
+
+ texture.format = _SRGBAFormat;
+
+ // it's not possible to generate mips in WebGL 1 with this extension
+
+ texture.minFilter = LinearFilter;
+ texture.generateMipmaps = false;
+
+ } else {
+
+ // slow fallback (CPU decode)
+
+ image = ImageUtils.sRGBToLinear( image );
+
+ }
+
+ } else {
+
+ // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
+
+ if ( format !== RGBAFormat || type !== UnsignedByteType ) {
+
+ console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
+
+ }
+
+ }
+
+ } else {
+
+ console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
+
+ }
+
+ }
+
+ return image;
+
+ }
+
// backwards compatibility
let warnedTexture2D = false;
@@ -23686,14 +23807,13 @@
const isWebGL2 = capabilities.isWebGL2;
- function convert( p ) {
+ function convert( p, encoding = null ) {
let extension;
if ( p === UnsignedByteType ) return 5121;
if ( p === UnsignedShort4444Type ) return 32819;
if ( p === UnsignedShort5551Type ) return 32820;
- if ( p === UnsignedShort565Type ) return 33635;
if ( p === ByteType ) return 5120;
if ( p === ShortType ) return 5122;
@@ -23721,7 +23841,6 @@
}
if ( p === AlphaFormat ) return 6406;
- if ( p === RGBFormat ) return 6407;
if ( p === RGBAFormat ) return 6408;
if ( p === LuminanceFormat ) return 6409;
if ( p === LuminanceAlphaFormat ) return 6410;
@@ -23729,16 +23848,53 @@
if ( p === DepthStencilFormat ) return 34041;
if ( p === RedFormat ) return 6403;
+ // WebGL 1 sRGB fallback
+
+ if ( p === _SRGBAFormat ) {
+
+ extension = extensions.get( 'EXT_sRGB' );
+
+ if ( extension !== null ) {
+
+ return extension.SRGB_ALPHA_EXT;
+
+ } else {
+
+ return null;
+
+ }
+
+ }
+
// WebGL2 formats.
if ( p === RedIntegerFormat ) return 36244;
if ( p === RGFormat ) return 33319;
if ( p === RGIntegerFormat ) return 33320;
- if ( p === RGBIntegerFormat ) return 36248;
if ( p === RGBAIntegerFormat ) return 36249;
- if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
- p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
+ // S3TC
+
+ if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
+
+ if ( encoding === sRGBEncoding ) {
+
+ 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' );
@@ -23757,8 +23913,11 @@
}
- if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
- p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
+ }
+
+ // PVRTC
+
+ 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' );
@@ -23777,6 +23936,8 @@
}
+ // ETC1
+
if ( p === RGB_ETC1_Format ) {
extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
@@ -23793,37 +23954,51 @@
}
+ // ETC2
+
if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
extension = extensions.get( 'WEBGL_compressed_texture_etc' );
if ( extension !== null ) {
- if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
- if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
+ if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
+ if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
+
+ } else {
+
+ return null;
}
}
+ // ASTC
+
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 ||
- p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
- p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
- p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
- p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
- p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
+ p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
extension = extensions.get( 'WEBGL_compressed_texture_astc' );
if ( extension !== null ) {
- // TODO Complete?
-
- return p;
+ if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
+ if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
+ if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
+ if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
+ if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
+ if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
+ if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
+ if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
+ if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
+ if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
+ if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
+ if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
+ if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
+ if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
} else {
@@ -23833,15 +24008,15 @@
}
+ // BPTC
+
if ( p === RGBA_BPTC_Format ) {
extension = extensions.get( 'EXT_texture_compression_bptc' );
if ( extension !== null ) {
- // TODO Complete?
-
- return p;
+ if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
} else {
@@ -23851,6 +24026,8 @@
}
+ //
+
if ( p === UnsignedInt248Type ) {
if ( isWebGL2 ) return 34042;
@@ -24492,7 +24669,7 @@
}
const projectionlayerInit = {
- colorFormat: ( attributes.alpha || isMultisample ) ? 32856 : 32849,
+ colorFormat: ( renderer.outputEncoding === sRGBEncoding ) ? 35907 : 32856,
depthFormat: glDepthFormat,
scaleFactor: framebufferScaleFactor
};
@@ -24524,7 +24701,7 @@
glProjLayer.textureWidth,
glProjLayer.textureHeight,
{
- format: attributes.alpha ? RGBAFormat : RGBFormat,
+ format: RGBAFormat,
type: UnsignedByteType,
depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
stencilBuffer: attributes.stencil,
@@ -24536,6 +24713,8 @@
}
+ newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
+
// Set foveation to maximum.
this.setFoveation( 1.0 );
@@ -25794,10 +25973,6 @@
const _scissor = new Vector4( 0, 0, _width, _height );
let _scissorTest = false;
- //
-
- const _currentDrawBuffers = [];
-
// frustum
const _frustum = new Frustum();
@@ -25846,7 +26021,7 @@
try {
const contextAttributes = {
- alpha: _alpha,
+ alpha: true,
depth: _depth,
stencil: _stencil,
antialias: _antialias,
@@ -25930,8 +26105,6 @@
state = new WebGLState( _gl, extensions, capabilities );
- _currentDrawBuffers[ 0 ] = 1029;
-
info = new WebGLInfo( _gl );
properties = new WebGLProperties();
textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
@@ -25947,7 +26120,7 @@
materials = new WebGLMaterials( properties );
renderLists = new WebGLRenderLists();
renderStates = new WebGLRenderStates( extensions, capabilities );
- background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
+ background = new WebGLBackground( _this, cubemaps, state, objects, _alpha, _premultipliedAlpha );
shadowMap = new WebGLShadowMap( _this, objects, capabilities );
bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
@@ -27062,7 +27235,7 @@
const fog = scene.fog;
const environment = material.isMeshStandardMaterial ? scene.environment : null;
- const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
+ const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
@@ -27530,67 +27703,7 @@
if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
- let needsUpdate = false;
-
- if ( renderTarget ) {
-
- if ( renderTarget.isWebGLMultipleRenderTargets ) {
-
- const textures = renderTarget.texture;
-
- if ( _currentDrawBuffers.length !== textures.length || _currentDrawBuffers[ 0 ] !== 36064 ) {
-
- for ( let i = 0, il = textures.length; i < il; i ++ ) {
-
- _currentDrawBuffers[ i ] = 36064 + i;
-
- }
-
- _currentDrawBuffers.length = textures.length;
-
- needsUpdate = true;
-
- }
-
- } else {
-
- if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 36064 ) {
-
- _currentDrawBuffers[ 0 ] = 36064;
- _currentDrawBuffers.length = 1;
-
- needsUpdate = true;
-
- }
-
- }
-
- } else {
-
- if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 1029 ) {
-
- _currentDrawBuffers[ 0 ] = 1029;
- _currentDrawBuffers.length = 1;
-
- needsUpdate = true;
-
- }
-
- }
-
- if ( needsUpdate ) {
-
- if ( capabilities.isWebGL2 ) {
-
- _gl.drawBuffers( _currentDrawBuffers );
-
- } else {
-
- extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( _currentDrawBuffers );
-
- }
-
- }
+ state.drawBuffers( renderTarget, framebuffer );
}
@@ -30049,8 +30162,6 @@
super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
- this.format = format !== undefined ? format : RGBFormat;
-
this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
@@ -34878,7 +34989,7 @@
// faces
indices.push( a, b, d );
- indices.push( b, c, d );
+ indices.push( c, d, b );
}
@@ -39143,6 +39254,10 @@
// An abort controller could be added within a future PR
} );
+ // record states ( avoid data race )
+ const mimeType = this.mimeType;
+ const responseType = this.responseType;
+
// start the fetch
fetch( req )
.then( response => {
@@ -39221,7 +39336,7 @@
} )
.then( response => {
- switch ( this.responseType ) {
+ switch ( responseType ) {
case 'arraybuffer':
@@ -39237,7 +39352,7 @@
.then( text => {
const parser = new DOMParser();
- return parser.parseFromString( text, this.mimeType );
+ return parser.parseFromString( text, mimeType );
} );
@@ -39247,8 +39362,21 @@
default:
+ if ( mimeType === undefined ) {
+
return response.text();
+ } else {
+
+ // sniff encoding
+ const re = /charset="?([^;"\s]*)"?/i;
+ const exec = re.exec( mimeType );
+ const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
+ const decoder = new TextDecoder( label );
+ return response.arrayBuffer().then( ab => decoder.decode( ab ) );
+
+ }
+
}
} )
@@ -40746,12 +40874,12 @@
if ( json.side !== undefined ) material.side = json.side;
if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
if ( json.opacity !== undefined ) material.opacity = json.opacity;
- if ( json.format !== undefined ) material.format = json.format;
if ( json.transparent !== undefined ) material.transparent = json.transparent;
if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
+ if ( json.alphaWrite !== undefined ) material.alphaWrite = json.alphaWrite;
if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
@@ -45544,6 +45672,7 @@
if ( binding !== undefined ) {
+ ++ binding.referenceCount;
bindings[ i ] = binding;
} else {
@@ -50309,4 +50438,4 @@
}
-export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, AxisHelper, BackSide, BasicDepthPacking, BasicShadowMap, BinaryTextureLoader, Bone, BooleanKeyframeTrack, BoundingBoxHelper, Box2, Box3, Box3Helper, BoxGeometry as BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CatmullRomCurve3, CineonToneMapping, CircleGeometry as CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeGeometry as ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry as CylinderBufferGeometry, CylinderGeometry, Cylindrical, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry as DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry as ExtrudeBufferGeometry, ExtrudeGeometry, FaceColors, FileLoader, FlatShading, Float16BufferAttribute, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronGeometry as IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry as LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LinePieces, LineSegments, LineStrip, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils as Math, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshFaceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiMaterial, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColors, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry as OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, ParametricGeometry, Particle, ParticleBasicMaterial, ParticleSystem, ParticleSystemMaterial, Path, PerspectiveCamera, Plane, PlaneGeometry as PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointCloud, PointCloudMaterial, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry as PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry as RingBufferGeometry, RingGeometry, SRGB8_ALPHA8_ASTC_10x10_Format, SRGB8_ALPHA8_ASTC_10x5_Format, SRGB8_ALPHA8_ASTC_10x6_Format, SRGB8_ALPHA8_ASTC_10x8_Format, SRGB8_ALPHA8_ASTC_12x10_Format, SRGB8_ALPHA8_ASTC_12x12_Format, SRGB8_ALPHA8_ASTC_4x4_Format, SRGB8_ALPHA8_ASTC_5x4_Format, SRGB8_ALPHA8_ASTC_5x5_Format, SRGB8_ALPHA8_ASTC_6x5_Format, SRGB8_ALPHA8_ASTC_6x6_Format, SRGB8_ALPHA8_ASTC_8x5_Format, SRGB8_ALPHA8_ASTC_8x6_Format, SRGB8_ALPHA8_ASTC_8x8_Format, Scene, SceneUtils, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry as ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, Sphere, SphereGeometry as SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry as TetrahedronBufferGeometry, TetrahedronGeometry, TextGeometry, Texture, TextureLoader, TorusGeometry as TorusBufferGeometry, TorusGeometry, TorusKnotGeometry as TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry as TubeBufferGeometry, TubeGeometry, UVMapping, Uint16Attribute, Uint16BufferAttribute, Uint32Attribute, Uint32BufferAttribute, Uint8Attribute, Uint8BufferAttribute, Uint8ClampedAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, Vertex, VertexColors, VideoTexture, WebGL1Renderer, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, sRGBEncoding };
+export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, AxisHelper, BackSide, BasicDepthPacking, BasicShadowMap, BinaryTextureLoader, Bone, BooleanKeyframeTrack, BoundingBoxHelper, Box2, Box3, Box3Helper, BoxGeometry as BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CatmullRomCurve3, CineonToneMapping, CircleGeometry as CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeGeometry as ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry as CylinderBufferGeometry, CylinderGeometry, Cylindrical, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry as DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry as ExtrudeBufferGeometry, ExtrudeGeometry, FaceColors, FileLoader, FlatShading, Float16BufferAttribute, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronGeometry as IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry as LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LinePieces, LineSegments, LineStrip, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils as Math, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshFaceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiMaterial, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColors, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry as OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, ParametricGeometry, Particle, ParticleBasicMaterial, ParticleSystem, ParticleSystemMaterial, Path, PerspectiveCamera, Plane, PlaneGeometry as PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointCloud, PointCloudMaterial, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry as PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry as RingBufferGeometry, RingGeometry, Scene, SceneUtils, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry as ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, Sphere, SphereGeometry as SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry as TetrahedronBufferGeometry, TetrahedronGeometry, TextGeometry, Texture, TextureLoader, TorusGeometry as TorusBufferGeometry, TorusGeometry, TorusKnotGeometry as TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry as TubeBufferGeometry, TubeGeometry, UVMapping, Uint16Attribute, Uint16BufferAttribute, Uint32Attribute, Uint32BufferAttribute, Uint8Attribute, Uint8BufferAttribute, Uint8ClampedAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, Vertex, VertexColors, VideoTexture, WebGL1Renderer, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, sRGBEncoding };

examples/js/animation/MMDAnimationHelper.js

@@ -44,7 +44,9 @@
cameraAnimation: true
};
- this.onBeforePhysics = function () {}; // experimental
+ this.onBeforePhysics = function
+ /* mesh */
+ () {}; // experimental
this.sharedPhysics = false;

examples/js/animation/MMDPhysics.js

@@ -821,7 +821,7 @@
return new Ammo.btCapsuleShape( p.width, p.height );
default:
- throw 'unknown shape type ' + p.shapeType;
+ throw new Error( 'unknown shape type ' + p.shapeType );
}

examples/js/cameras/CinematicCamera.js

@@ -91,13 +91,8 @@
this.postprocessing.scene = new THREE.Scene();
this.postprocessing.camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, - 10000, 10000 );
this.postprocessing.scene.add( this.postprocessing.camera );
- const pars = {
- minFilter: THREE.LinearFilter,
- magFilter: THREE.LinearFilter,
- format: THREE.RGBFormat
- };
- this.postprocessing.rtTextureDepth = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, pars );
- this.postprocessing.rtTextureColor = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, pars );
+ this.postprocessing.rtTextureDepth = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight );
+ this.postprocessing.rtTextureColor = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight );
const bokeh_shader = THREE.BokehShader;
this.postprocessing.bokeh_uniforms = THREE.UniformsUtils.clone( bokeh_shader.uniforms );
this.postprocessing.bokeh_uniforms[ 'tColor' ].value = this.postprocessing.rtTextureColor.texture;

examples/js/controls/experimental/CameraControls.js

@@ -510,7 +510,9 @@
}
- function handleMouseUp() { // no-op
+ function
+ /*event*/
+ handleMouseUp() { // no-op
}
function handleMouseWheel( event ) {
@@ -691,7 +693,9 @@
}
- function handleTouchEnd() { // no-op
+ function
+ /*event*/
+ handleTouchEnd() { // no-op
} //
// event handlers - FSM: listen for events and reset state
//

examples/js/exporters/GLTFExporter.js

@@ -625,6 +625,71 @@
}
}
+
+ buildORMTexture( material ) {
+
+ const occlusion = material.aoMap?.image;
+ const roughness = material.roughnessMap?.image;
+ const metalness = material.metalnessMap?.image;
+ if ( occlusion === roughness && roughness === metalness ) return occlusion;
+
+ if ( occlusion || roughness || metalness ) {
+
+ const width = Math.max( occlusion?.width || 0, roughness?.width || 0, metalness?.width || 0 );
+ const height = Math.max( occlusion?.height || 0, roughness?.height || 0, metalness?.height || 0 );
+ const canvas = document.createElement( 'canvas' );
+ canvas.width = width;
+ canvas.height = height;
+ const context = canvas.getContext( '2d' );
+ context.fillStyle = '#ffffff';
+ context.fillRect( 0, 0, width, height );
+ const composite = context.getImageData( 0, 0, width, height );
+
+ if ( occlusion ) {
+
+ context.drawImage( occlusion, 0, 0, width, height );
+ const data = context.getImageData( 0, 0, width, height ).data;
+
+ for ( let i = 0; i < data.length; i += 4 ) {
+
+ composite.data[ i ] = data[ i ];
+
+ }
+
+ }
+
+ if ( roughness ) {
+
+ context.drawImage( roughness, 0, 0, width, height );
+ const data = context.getImageData( 0, 0, width, height ).data;
+
+ for ( let i = 1; i < data.length; i += 4 ) {
+
+ composite.data[ i ] = data[ i ];
+
+ }
+
+ }
+
+ if ( metalness ) {
+
+ context.drawImage( metalness, 0, 0, width, height );
+ const data = context.getImageData( 0, 0, width, height ).data;
+
+ for ( let i = 2; i < data.length; i += 4 ) {
+
+ composite.data[ i ] = data[ i ];
+
+ }
+
+ }
+
+ context.putImageData( composite, 0, 0 );
+ return new THREE.Texture( canvas );
+
+ }
+
+ }
/**
* Process a buffer to append to the default one.
* @param {ArrayBuffer} buffer
@@ -866,7 +931,7 @@
/**
* Process image
* @param {Image} image to process
- * @param {Integer} format of the image (e.g. THREE.RGBFormat, THREE.RGBAFormat etc)
+ * @param {Integer} format of the image (THREE.RGBAFormat)
* @param {Boolean} flipY before writing out the image
* @return {Integer} Index of the processed texture in the "images" array
*/
@@ -909,9 +974,9 @@
} else {
- if ( format !== THREE.RGBAFormat && format !== THREE.RGBFormat ) {
+ if ( format !== THREE.RGBAFormat ) {
- console.error( 'GLTFExporter: Only RGB and RGBA formats are supported.' );
+ console.error( 'GLTFExporter: Only THREE.RGBAFormat is supported.' );
}
@@ -923,8 +988,6 @@
const data = new Uint8ClampedArray( image.height * image.width * 4 );
- if ( format === THREE.RGBAFormat ) {
-
for ( let i = 0; i < data.length; i += 4 ) {
data[ i + 0 ] = image.data[ i + 0 ];
@@ -934,19 +997,6 @@
}
- } else {
-
- for ( let i = 0, j = 0; i < data.length; i += 4, j += 3 ) {
-
- data[ i + 0 ] = image.data[ j + 0 ];
- data[ i + 1 ] = image.data[ j + 1 ];
- data[ i + 2 ] = image.data[ j + 2 ];
- data[ i + 3 ] = 255;
-
- }
-
- }
-
ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
}
@@ -987,7 +1037,7 @@
}
/**
* Process sampler
- * @param {Texture} map Texture to process
+ * @param {Texture} map THREE.Texture to process
* @return {Integer} Index of the processed texture in the "samplers" array
*/
@@ -1086,25 +1136,18 @@
materialDef.pbrMetallicRoughness.metallicFactor = 0.5;
materialDef.pbrMetallicRoughness.roughnessFactor = 0.5;
- } // pbrMetallicRoughness.metallicRoughnessTexture
+ }
+ const ormTexture = this.buildORMTexture( material ); // pbrMetallicRoughness.metallicRoughnessTexture
if ( material.metalnessMap || material.roughnessMap ) {
- if ( material.metalnessMap === material.roughnessMap ) {
-
const metalRoughMapDef = {
- index: this.processTexture( material.metalnessMap )
+ index: this.processTexture( ormTexture )
};
- this.applyTextureTransform( metalRoughMapDef, material.metalnessMap );
+ this.applyTextureTransform( metalRoughMapDef, material.metalnessMap || material.roughnessMap );
materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
- } else {
-
- console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
-
- }
-
} // pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture
@@ -1174,7 +1217,7 @@
if ( material.aoMap ) {
const occlusionMapDef = {
- index: this.processTexture( material.aoMap ),
+ index: this.processTexture( ormTexture ),
texCoord: 1
};

examples/js/exporters/MMDExporter.js

@@ -161,7 +161,7 @@
if ( value === undefined ) {
- throw 'cannot convert charcode 0x' + code.toString( 16 );
+ throw new Error( 'cannot convert charcode 0x' + code.toString( 16 ) );
} else if ( value > 0xff ) {

examples/js/geometries/ConvexGeometry.js

@@ -2,7 +2,7 @@
class ConvexGeometry extends THREE.BufferGeometry {
- constructor( points ) {
+ constructor( points = [] ) {
super(); // buffers

examples/js/geometries/TextGeometry.js

@@ -23,12 +23,11 @@
const font = parameters.font;
- if ( ! ( font && font.isFont ) ) {
+ if ( font === undefined ) {
- console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
- return new THREE.BufferGeometry();
+ super(); // generate default extrude geometry
- }
+ } else {
const shapes = font.generateShapes( text, parameters.size ); // translate parameters to THREE.ExtrudeGeometry API
@@ -38,6 +37,9 @@
if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
super( shapes, parameters );
+
+ }
+
this.type = 'TextGeometry';
}

examples/js/interactive/HTMLMesh.js

@@ -14,7 +14,7 @@
function onEvent( event ) {
- material.map.dispatchEvent( event );
+ material.map.dispatchDOMEvent( event );
}
@@ -23,6 +23,18 @@
this.addEventListener( 'mouseup', onEvent );
this.addEventListener( 'click', onEvent );
+ this.dispose = function () {
+
+ geometry.dispose();
+ material.dispose();
+ material.map.dispose();
+ this.removeEventListener( 'mousedown', onEvent );
+ this.removeEventListener( 'mousemove', onEvent );
+ this.removeEventListener( 'mouseup', onEvent );
+ this.removeEventListener( 'click', onEvent );
+
+ };
+
}
}
@@ -40,7 +52,7 @@
}
- dispatchEvent( event ) {
+ dispatchDOMEvent( event ) {
htmlevent( this.dom, event.type, event.data.x, event.data.y );
this.update();

examples/js/loaders/BasisTextureLoader.js

@@ -28,6 +28,7 @@
this.workerNextTaskID = 1;
this.workerSourceURL = '';
this.workerConfig = null;
+ console.warn( 'THREE.BasisTextureLoader: This loader is deprecated, and will be removed in a future release. ' + 'Instead, use Basis Universal compression in KTX2 (.ktx2) files with THREE.KTX2Loader.' );
}

examples/js/loaders/EXRLoader.js

@@ -210,7 +210,7 @@
if ( p.value - inOffset.value > ni ) {
- throw 'Something wrong with hufUnpackEncTable';
+ throw new Error( 'Something wrong with hufUnpackEncTable' );
}
@@ -221,7 +221,7 @@
if ( im + zerun > iM + 1 ) {
- throw 'Something wrong with hufUnpackEncTable';
+ throw new Error( 'Something wrong with hufUnpackEncTable' );
}
@@ -235,7 +235,7 @@
if ( im + zerun > iM + 1 ) {
- throw 'Something wrong with hufUnpackEncTable';
+ throw new Error( 'Something wrong with hufUnpackEncTable' );
}
@@ -272,7 +272,7 @@
if ( c >> l ) {
- throw 'Invalid table entry';
+ throw new Error( 'Invalid table entry' );
}
@@ -282,7 +282,7 @@
if ( pl.len ) {
- throw 'Invalid table entry';
+ throw new Error( 'Invalid table entry' );
}
@@ -317,7 +317,7 @@
if ( pl.len || pl.p ) {
- throw 'Invalid table entry';
+ throw new Error( 'Invalid table entry' );
}
@@ -576,7 +576,7 @@
if ( ! pl.p ) {
- throw 'hufDecode issues';
+ throw new Error( 'hufDecode issues' );
}
@@ -612,7 +612,7 @@
if ( j == pl.lit ) {
- throw 'hufDecode issues';
+ throw new Error( 'hufDecode issues' );
}
@@ -639,7 +639,7 @@
} else {
- throw 'hufDecode issues';
+ throw new Error( 'hufDecode issues' );
}
@@ -663,7 +663,7 @@
if ( im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE ) {
- throw 'Something wrong with HUF_ENCSIZE';
+ throw new Error( 'Something wrong with HUF_ENCSIZE' );
}
@@ -675,7 +675,7 @@
if ( nBits > 8 * ( nCompressed - ( inOffset.value - initialInOffset ) ) ) {
- throw 'Something wrong with hufUncompress';
+ throw new Error( 'Something wrong with hufUncompress' );
}
@@ -1198,7 +1198,7 @@
if ( maxNonZero >= BITMAP_SIZE ) {
- throw 'Something is wrong with PIZ_COMPRESSION BITMAP_SIZE';
+ throw new Error( 'Something is wrong with PIZ_COMPRESSION BITMAP_SIZE' );
}
@@ -1346,7 +1346,7 @@
totalDcUncompressedCount: parseInt64( inDataView, inOffset ),
acCompression: parseInt64( inDataView, inOffset )
};
- if ( dwaHeader.version < 2 ) throw 'EXRLoader.parse: ' + EXRHeader.compression + ' version ' + dwaHeader.version + ' is unsupported'; // Read channel ruleset information
+ if ( dwaHeader.version < 2 ) throw new Error( 'EXRLoader.parse: ' + EXRHeader.compression + ' version ' + dwaHeader.version + ' is unsupported' ); // Read channel ruleset information
var channelRules = new Array();
var ruleSize = parseUint16( inDataView, inOffset ) - INT16_SIZE;
@@ -1523,7 +1523,7 @@
case LOSSY_DCT: // skip
default:
- throw 'EXRLoader.parse: unsupported channel compression';
+ throw new Error( 'EXRLoader.parse: unsupported channel compression' );
}
@@ -1606,13 +1606,24 @@
}
- function parseInt64( dataView, offset ) {
+ const parseInt64 = function ( dataView, offset ) {
+
+ let int;
+
+ if ( 'getBigInt64' in DataView.prototype ) {
+
+ int = Number( dataView.getBigInt64( offset.value, true ) );
+
+ } else {
+
+ int = dataView.getUint32( offset.value + 4, true ) + Number( dataView.getUint32( offset.value, true ) << 32 );
+
+ }
- var int = Number( dataView.getBigInt64( offset.value, true ) );
offset.value += ULONG_SIZE;
return int;
- }
+ };
function parseFloat32( dataView, offset ) {
@@ -1818,16 +1829,22 @@
function parseHeader( dataView, buffer, offset ) {
const EXRHeader = {};
- if ( dataView.getUint32( 0, true ) != 20000630 ) // magic
- throw 'THREE.EXRLoader: provided file doesn\'t appear to be in OpenEXR format.';
- EXRHeader.version = dataView.getUint8( 4, true );
- const spec = dataView.getUint8( 5, true ); // fullMask
+
+ if ( dataView.getUint32( 0, true ) != 20000630 ) {
+
+ // magic
+ throw new Error( 'THREE.EXRLoader: provided file doesn\'t appear to be in OpenEXR format.' );
+
+ }
+
+ EXRHeader.version = dataView.getUint8( 4 );
+ const spec = dataView.getUint8( 5 ); // fullMask
EXRHeader.spec = {
- singleTile: !! ( spec & 1 ),
- longName: !! ( spec & 2 ),
- deepFormat: !! ( spec & 4 ),
- multiPart: !! ( spec & 8 )
+ singleTile: !! ( spec & 2 ),
+ longName: !! ( spec & 4 ),
+ deepFormat: !! ( spec & 8 ),
+ multiPart: !! ( spec & 16 )
}; // start of header
offset.value = 8; // start at 8 - after pre-amble
@@ -1865,7 +1882,7 @@
if ( spec != 0 ) {
console.error( 'EXRHeader:', EXRHeader );
- throw 'THREE.EXRLoader: provided file is currently unsupported.';
+ throw new Error( 'THREE.EXRLoader: provided file is currently unsupported.' );
}
@@ -1936,7 +1953,7 @@
break;
default:
- throw 'EXRLoader.parse: ' + EXRHeader.compression + ' is unsupported';
+ throw new Error( 'EXRLoader.parse: ' + EXRHeader.compression + ' is unsupported' );
}
@@ -1977,7 +1994,7 @@
} else {
- throw 'EXRLoader.parse: unsupported pixelType ' + EXRDecoder.type + ' for ' + EXRHeader.compression + '.';
+ throw new Error( 'EXRLoader.parse: unsupported pixelType ' + EXRDecoder.type + ' for ' + EXRHeader.compression + '.' );
}

examples/js/loaders/GLTFLoader.js

@@ -1329,7 +1329,7 @@
const specularMapParsFragmentChunk = [ '#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif' ].join( '\n' );
const glossinessMapParsFragmentChunk = [ '#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif' ].join( '\n' );
- const specularMapFragmentChunk = [ 'vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif' ].join( '\n' );
+ const specularMapFragmentChunk = [ 'vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif' ].join( '\n' );
const glossinessMapFragmentChunk = [ 'float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif' ].join( '\n' );
const lightPhysicalFragmentChunk = [ 'PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );', 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', 'material.roughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', 'material.roughness += geometryRoughness;', 'material.roughness = min( material.roughness, 1.0 );', 'material.specularColor = specularFactor;' ].join( '\n' );
const uniforms = {
@@ -2006,7 +2006,7 @@
this.nodeNamesUsed = {}; // Use an THREE.ImageBitmapLoader if imageBitmaps are supported. Moves much of the
// expensive work of uploading a texture to the GPU off the main thread.
- if ( typeof createImageBitmap !== 'undefined' && /Firefox|Safari/.test( navigator.userAgent ) === false ) {
+ if ( typeof createImageBitmap !== 'undefined' && /Firefox|^((?!chrome|android).)*safari/i.test( navigator.userAgent ) === false ) {
this.textureLoader = new THREE.ImageBitmapLoader( this.options.manager );
@@ -2884,8 +2884,8 @@
} else {
- materialParams.format = THREE.RGBFormat;
materialParams.transparent = false;
+ materialParams.alphaWrite = false;
if ( alphaMode === ALPHA_MODES.MASK ) {

examples/js/loaders/HDRCubeTextureLoader.js

@@ -30,7 +30,6 @@
case THREE.FloatType:
texture.encoding = THREE.LinearEncoding;
- texture.format = THREE.RGBFormat;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.generateMipmaps = false;
@@ -38,7 +37,6 @@
case THREE.HalfFloatType:
texture.encoding = THREE.LinearEncoding;
- texture.format = THREE.RGBFormat;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.generateMipmaps = false;

examples/js/loaders/LDrawLoader.js

@@ -17,6 +17,8 @@
const FILE_LOCATION_TRY_RELATIVE = 4;
const FILE_LOCATION_TRY_ABSOLUTE = 5;
const FILE_LOCATION_NOT_FOUND = 6;
+ const MAIN_COLOUR_CODE = '16';
+ const MAIN_EDGE_COLOUR_CODE = '24';
const _tempVec0 = new THREE.Vector3();
@@ -142,16 +144,56 @@
}
- function smoothNormals( faces, lineSegments ) {
+ class ConditionalLineSegments extends THREE.LineSegments {
+
+ constructor( geometry, material ) {
+
+ super( geometry, material );
+ this.isConditionalLine = true;
+
+ }
+
+ }
+
+ function generateFaceNormals( faces ) {
+
+ for ( let i = 0, l = faces.length; i < l; i ++ ) {
+
+ const face = faces[ i ];
+ const vertices = face.vertices;
+ const v0 = vertices[ 0 ];
+ const v1 = vertices[ 1 ];
+ const v2 = vertices[ 2 ];
+
+ _tempVec0.subVectors( v1, v0 );
+
+ _tempVec1.subVectors( v2, v1 );
+
+ face.faceNormal = new THREE.Vector3().crossVectors( _tempVec0, _tempVec1 ).normalize();
+
+ }
+
+ }
+
+ const _ray = new THREE.Ray();
+
+ function smoothNormals( faces, lineSegments, checkSubSegments = false ) {
+
+ // NOTE: 1e2 is pretty coarse but was chosen to quantize the resulting value because
+ // it allows edges to be smoothed as expected (see minifig arms).
+ // --
+ // And the vector values are initialize multiplied by 1 + 1e-10 to account for floating
+ // point errors on vertices along quantization boundaries. Ie after matrix multiplication
+ // vertices that should be merged might be set to "1.7" and "1.6999..." meaning they won't
+ // get merged. This added epsilon attempts to push these error values to the same quantized
+ // value for the sake of hashing. See "AT-ST mini" dishes. See mrdoob/three#23169.
+ const hashMultiplier = ( 1 + 1e-10 ) * 1e2;
function hashVertex( v ) {
- // NOTE: 1e2 is pretty coarse but was chosen because it allows edges
- // to be smoothed as expected (see minifig arms). The errors between edges
- // could be due to matrix multiplication.
- const x = ~ ~ ( v.x * 1e2 );
- const y = ~ ~ ( v.y * 1e2 );
- const z = ~ ~ ( v.z * 1e2 );
+ const x = ~ ~ ( v.x * hashMultiplier );
+ const y = ~ ~ ( v.y * hashMultiplier );
+ const z = ~ ~ ( v.z * hashMultiplier );
return `${x},${y},${z}`;
}
@@ -160,9 +202,27 @@
return `${hashVertex( v0 )}_${hashVertex( v1 )}`;
+ } // converts the two vertices to a ray with a normalized direction and origin of 0, 0, 0 projected
+ // onto the original line.
+
+
+ function toNormalizedRay( v0, v1, targetRay ) {
+
+ targetRay.direction.subVectors( v1, v0 ).normalize();
+ const scalar = v0.dot( targetRay.direction );
+ targetRay.origin.copy( v0 ).addScaledVector( targetRay.direction, - scalar );
+ return targetRay;
+
+ }
+
+ function hashRay( ray ) {
+
+ return hashEdge( ray.origin, ray.direction );
+
}
const hardEdges = new Set();
+ const hardEdgeRays = new Map();
const halfEdgeList = {};
const normals = []; // Save the list of hard edges by hash
@@ -173,7 +233,43 @@
const v0 = vertices[ 0 ];
const v1 = vertices[ 1 ];
hardEdges.add( hashEdge( v0, v1 ) );
- hardEdges.add( hashEdge( v1, v0 ) );
+ hardEdges.add( hashEdge( v1, v0 ) ); // only generate the hard edge ray map if we're checking subsegments because it's more expensive to check
+ // and requires more memory.
+
+ if ( checkSubSegments ) {
+
+ // add both ray directions to the map
+ const ray = toNormalizedRay( v0, v1, new THREE.Ray() );
+ const rh1 = hashRay( ray );
+
+ if ( ! hardEdgeRays.has( rh1 ) ) {
+
+ toNormalizedRay( v1, v0, ray );
+ const rh2 = hashRay( ray );
+ const info = {
+ ray,
+ distances: []
+ };
+ hardEdgeRays.set( rh1, info );
+ hardEdgeRays.set( rh2, info );
+
+ } // store both segments ends in min, max order in the distances array to check if a face edge is a
+ // subsegment later.
+
+
+ const info = hardEdgeRays.get( rh1 );
+ let d0 = info.ray.direction.dot( v0 );
+ let d1 = info.ray.direction.dot( v1 );
+
+ if ( d0 > d1 ) {
+
+ [ d0, d1 ] = [ d1, d0 ];
+
+ }
+
+ info.distances.push( d0, d1 );
+
+ }
} // track the half edges associated with each triangle
@@ -192,7 +288,58 @@
const v1 = vertices[ next ];
const hash = hashEdge( v0, v1 ); // don't add the triangle if the edge is supposed to be hard
- if ( hardEdges.has( hash ) ) continue;
+ if ( hardEdges.has( hash ) ) {
+
+ continue;
+
+ } // if checking subsegments then check to see if this edge lies on a hard edge ray and whether its within any ray bounds
+
+
+ if ( checkSubSegments ) {
+
+ toNormalizedRay( v0, v1, _ray );
+ const rayHash = hashRay( _ray );
+
+ if ( hardEdgeRays.has( rayHash ) ) {
+
+ const info = hardEdgeRays.get( rayHash );
+ const {
+ ray,
+ distances
+ } = info;
+ let d0 = ray.direction.dot( v0 );
+ let d1 = ray.direction.dot( v1 );
+
+ if ( d0 > d1 ) {
+
+ [ d0, d1 ] = [ d1, d0 ];
+
+ } // return early if the face edge is found to be a subsegment of a line edge meaning the edge will have "hard" normals
+
+
+ let found = false;
+
+ for ( let i = 0, l = distances.length; i < l; i += 2 ) {
+
+ if ( d0 >= distances[ i ] && d1 <= distances[ i + 1 ] ) {
+
+ found = true;
+ break;
+
+ }
+
+ }
+
+ if ( found ) {
+
+ continue;
+
+ }
+
+ }
+
+ }
+
const info = {
index: index,
tri: tri
@@ -363,13 +510,7 @@
function isPartType( type ) {
- return type === 'Part';
-
- }
-
- function isModelType( type ) {
-
- return type === 'Model' || type === 'Unofficial_Model';
+ return type === 'Part' || type === 'Unofficial_Part';
}
@@ -433,6 +574,12 @@
}
+ getVector() {
+
+ return new THREE.Vector3( parseFloat( this.getToken() ), parseFloat( this.getToken() ), parseFloat( this.getToken() ) );
+
+ }
+
getRemainingString() {
return this.line.substring( this.currentCharIndex, this.lineLength );
@@ -457,34 +604,67 @@
}
- }
+ } // Fetches and parses an intermediate representation of LDraw parts files.
- class LDrawFileCache {
+
+ class LDrawParsedCache {
constructor( loader ) {
- this.cache = {};
this.loader = loader;
+ this._cache = {};
}
- setData( key, contents ) {
+ cloneResult( original ) {
- this.cache[ key.toLowerCase() ] = contents;
+ const result = {}; // vertices are transformed and normals computed before being converted to geometry
+ // so these pieces must be cloned.
- }
+ result.faces = original.faces.map( face => {
- async loadData( fileName ) {
+ return {
+ colorCode: face.colorCode,
+ material: face.material,
+ vertices: face.vertices.map( v => v.clone() ),
+ normals: face.normals.map( () => null ),
+ faceNormal: null
+ };
- const key = fileName.toLowerCase();
+ } );
+ result.conditionalSegments = original.conditionalSegments.map( face => {
- if ( key in this.cache ) {
+ return {
+ colorCode: face.colorCode,
+ material: face.material,
+ vertices: face.vertices.map( v => v.clone() ),
+ controlPoints: face.controlPoints.map( v => v.clone() )
+ };
+
+ } );
+ result.lineSegments = original.lineSegments.map( face => {
+
+ return {
+ colorCode: face.colorCode,
+ material: face.material,
+ vertices: face.vertices.map( v => v.clone() )
+ };
- return this.cache[ key ];
+ } ); // none if this is subsequently modified
+
+ result.type = original.type;
+ result.category = original.category;
+ result.keywords = original.keywords;
+ result.subobjects = original.subobjects;
+ result.totalFaces = original.totalFaces;
+ result.startingConstructionStep = original.startingConstructionStep;
+ result.materials = original.materials;
+ result.group = null;
+ return result;
}
- this.cache[ fileName ] = new Promise( async ( resolve, reject ) => {
+ async fetchData( fileName ) {
let triedLowerCase = false;
let locationState = FILE_LOCATION_AS_IS;
@@ -548,9 +728,7 @@
try {
const text = await fileLoader.loadAsync( subobjectURL );
- this.setData( fileName, text );
- resolve( text );
- return;
+ return text;
} catch {
@@ -560,10 +738,782 @@
}
- reject();
+ throw new Error( 'LDrawLoader: Subobject "' + fileName + '" could not be loaded.' );
+
+ }
+
+ parse( text, fileName = null ) {
+
+ const loader = this.loader; // final results
+
+ const faces = [];
+ const lineSegments = [];
+ const conditionalSegments = [];
+ const subobjects = [];
+ const materials = {};
+
+ const getLocalMaterial = colorCode => {
+
+ return materials[ colorCode ] || null;
+
+ };
+
+ let type = 'Model';
+ let category = null;
+ let keywords = null;
+ let totalFaces = 0; // split into lines
+
+ if ( text.indexOf( '\r\n' ) !== - 1 ) {
+
+ // This is faster than String.split with regex that splits on both
+ text = text.replace( /\r\n/g, '\n' );
+
+ }
+
+ const lines = text.split( '\n' );
+ const numLines = lines.length;
+ let parsingEmbeddedFiles = false;
+ let currentEmbeddedFileName = null;
+ let currentEmbeddedText = null;
+ let bfcCertified = false;
+ let bfcCCW = true;
+ let bfcInverted = false;
+ let bfcCull = true;
+ let startingConstructionStep = false; // Parse all line commands
+
+ for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
+
+ const line = lines[ lineIndex ];
+ if ( line.length === 0 ) continue;
+
+ if ( parsingEmbeddedFiles ) {
+
+ if ( line.startsWith( '0 FILE ' ) ) {
+
+ // Save previous embedded file in the cache
+ this.setData( currentEmbeddedFileName, currentEmbeddedText ); // New embedded text file
+
+ currentEmbeddedFileName = line.substring( 7 );
+ currentEmbeddedText = '';
+
+ } else {
+
+ currentEmbeddedText += line + '\n';
+
+ }
+
+ continue;
+
+ }
+
+ const lp = new LineParser( line, lineIndex + 1 );
+ lp.seekNonSpace();
+
+ if ( lp.isAtTheEnd() ) {
+
+ // Empty line
+ continue;
+
+ } // Parse the line type
+
+
+ const lineType = lp.getToken();
+ let material;
+ let colorCode;
+ let segment;
+ let ccw;
+ let doubleSided;
+ let v0, v1, v2, v3, c0, c1;
+
+ switch ( lineType ) {
+
+ // Line type 0: Comment or META
+ case '0':
+ // Parse meta directive
+ const meta = lp.getToken();
+
+ if ( meta ) {
+
+ switch ( meta ) {
+
+ case '!LDRAW_ORG':
+ type = lp.getToken();
+ break;
+
+ case '!COLOUR':
+ material = loader.parseColorMetaDirective( lp );
+
+ if ( material ) {
+
+ materials[ material.userData.code ] = material;
+
+ } else {
+
+ console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
+
+ }
+
+ break;
+
+ case '!CATEGORY':
+ category = lp.getToken();
+ break;
+
+ case '!KEYWORDS':
+ const newKeywords = lp.getRemainingString().split( ',' );
+
+ if ( newKeywords.length > 0 ) {
+
+ if ( ! keywords ) {
+
+ keywords = [];
+
+ }
+
+ newKeywords.forEach( function ( keyword ) {
+
+ keywords.push( keyword.trim() );
+
+ } );
+
+ }
+
+ break;
+
+ case 'FILE':
+ if ( lineIndex > 0 ) {
+
+ // Start embedded text files parsing
+ parsingEmbeddedFiles = true;
+ currentEmbeddedFileName = lp.getRemainingString();
+ currentEmbeddedText = '';
+ bfcCertified = false;
+ bfcCCW = true;
+
+ }
+
+ break;
+
+ case 'BFC':
+ // Changes to the backface culling state
+ while ( ! lp.isAtTheEnd() ) {
+
+ const token = lp.getToken();
+
+ switch ( token ) {
+
+ case 'CERTIFY':
+ case 'NOCERTIFY':
+ bfcCertified = token === 'CERTIFY';
+ bfcCCW = true;
+ break;
+
+ case 'CW':
+ case 'CCW':
+ bfcCCW = token === 'CCW';
+ break;
+
+ case 'INVERTNEXT':
+ bfcInverted = true;
+ break;
+
+ case 'CLIP':
+ case 'NOCLIP':
+ bfcCull = token === 'CLIP';
+ break;
+
+ default:
+ console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
+ break;
+
+ }
+
+ }
+
+ break;
+
+ case 'STEP':
+ startingConstructionStep = true;
+ break;
+
+ default:
+ // Other meta directives are not implemented
+ break;
+
+ }
+
+ }
+
+ break;
+ // Line type 1: Sub-object file
+
+ case '1':
+ colorCode = lp.getToken();
+ material = getLocalMaterial( colorCode );
+ const posX = parseFloat( lp.getToken() );
+ const posY = parseFloat( lp.getToken() );
+ const posZ = parseFloat( lp.getToken() );
+ const m0 = parseFloat( lp.getToken() );
+ const m1 = parseFloat( lp.getToken() );
+ const m2 = parseFloat( lp.getToken() );
+ const m3 = parseFloat( lp.getToken() );
+ const m4 = parseFloat( lp.getToken() );
+ const m5 = parseFloat( lp.getToken() );
+ const m6 = parseFloat( lp.getToken() );
+ const m7 = parseFloat( lp.getToken() );
+ const m8 = parseFloat( lp.getToken() );
+ const matrix = new THREE.Matrix4().set( m0, m1, m2, posX, m3, m4, m5, posY, m6, m7, m8, posZ, 0, 0, 0, 1 );
+ let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
+
+ if ( loader.fileMap[ fileName ] ) {
+
+ // Found the subobject path in the preloaded file path map
+ fileName = loader.fileMap[ fileName ];
+
+ } else {
+
+ // Standardized subfolders
+ if ( fileName.startsWith( 's/' ) ) {
+
+ fileName = 'parts/' + fileName;
+
+ } else if ( fileName.startsWith( '48/' ) ) {
+
+ fileName = 'p/' + fileName;
+
+ }
+
+ }
+
+ subobjects.push( {
+ material: material,
+ colorCode: colorCode,
+ matrix: matrix,
+ fileName: fileName,
+ inverted: bfcInverted,
+ startingConstructionStep: startingConstructionStep
+ } );
+ bfcInverted = false;
+ break;
+ // Line type 2: Line segment
+
+ case '2':
+ colorCode = lp.getToken();
+ material = getLocalMaterial( colorCode );
+ v0 = lp.getVector();
+ v1 = lp.getVector();
+ segment = {
+ material: material,
+ colorCode: colorCode,
+ vertices: [ v0, v1 ]
+ };
+ lineSegments.push( segment );
+ break;
+ // Line type 5: Conditional Line segment
+
+ case '5':
+ colorCode = lp.getToken();
+ material = getLocalMaterial( colorCode );
+ v0 = lp.getVector();
+ v1 = lp.getVector();
+ c0 = lp.getVector();
+ c1 = lp.getVector();
+ segment = {
+ material: material,
+ colorCode: colorCode,
+ vertices: [ v0, v1 ],
+ controlPoints: [ c0, c1 ]
+ };
+ conditionalSegments.push( segment );
+ break;
+ // Line type 3: Triangle
+
+ case '3':
+ colorCode = lp.getToken();
+ material = getLocalMaterial( colorCode );
+ ccw = bfcCCW;
+ doubleSided = ! bfcCertified || ! bfcCull;
+
+ if ( ccw === true ) {
+
+ v0 = lp.getVector();
+ v1 = lp.getVector();
+ v2 = lp.getVector();
+
+ } else {
+
+ v2 = lp.getVector();
+ v1 = lp.getVector();
+ v0 = lp.getVector();
+
+ }
+
+ faces.push( {
+ material: material,
+ colorCode: colorCode,
+ faceNormal: null,
+ vertices: [ v0, v1, v2 ],
+ normals: [ null, null, null ]
+ } );
+ totalFaces ++;
+
+ if ( doubleSided === true ) {
+
+ faces.push( {
+ material: material,
+ colorCode: colorCode,
+ faceNormal: null,
+ vertices: [ v2, v1, v0 ],
+ normals: [ null, null, null ]
+ } );
+ totalFaces ++;
+
+ }
+
+ break;
+ // Line type 4: Quadrilateral
+
+ case '4':
+ colorCode = lp.getToken();
+ material = getLocalMaterial( colorCode );
+ ccw = bfcCCW;
+ doubleSided = ! bfcCertified || ! bfcCull;
+
+ if ( ccw === true ) {
+
+ v0 = lp.getVector();
+ v1 = lp.getVector();
+ v2 = lp.getVector();
+ v3 = lp.getVector();
+
+ } else {
+
+ v3 = lp.getVector();
+ v2 = lp.getVector();
+ v1 = lp.getVector();
+ v0 = lp.getVector();
+
+ } // specifically place the triangle diagonal in the v0 and v1 slots so we can
+ // account for the doubling of vertices later when smoothing normals.
+
+
+ faces.push( {
+ material: material,
+ colorCode: colorCode,
+ faceNormal: null,
+ vertices: [ v0, v1, v2, v3 ],
+ normals: [ null, null, null, null ]
+ } );
+ totalFaces += 2;
+
+ if ( doubleSided === true ) {
+
+ faces.push( {
+ material: material,
+ colorCode: colorCode,
+ faceNormal: null,
+ vertices: [ v3, v2, v1, v0 ],
+ normals: [ null, null, null, null ]
+ } );
+ totalFaces += 2;
+
+ }
+
+ break;
+
+ default:
+ throw new Error( 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.' );
+
+ }
+
+ }
+
+ if ( parsingEmbeddedFiles ) {
+
+ this.setData( currentEmbeddedFileName, currentEmbeddedText );
+
+ }
+
+ return {
+ faces,
+ conditionalSegments,
+ lineSegments,
+ type,
+ category,
+ keywords,
+ subobjects,
+ totalFaces,
+ startingConstructionStep,
+ materials,
+ fileName,
+ group: null
+ };
+
+ } // returns an (optionally cloned) instance of the data
+
+
+ getData( fileName, clone = true ) {
+
+ const key = fileName.toLowerCase();
+ const result = this._cache[ key ];
+
+ if ( result === null || result instanceof Promise ) {
+
+ return null;
+
+ }
+
+ if ( clone ) {
+
+ return this.cloneResult( result );
+
+ } else {
+
+ return result;
+
+ }
+
+ } // kicks off a fetch and parse of the requested data if it hasn't already been loaded. Returns when
+ // the data is ready to use and can be retrieved synchronously with "getData".
+
+
+ async ensureDataLoaded( fileName ) {
+
+ const key = fileName.toLowerCase();
+
+ if ( ! ( key in this._cache ) ) {
+
+ // replace the promise with a copy of the parsed data for immediate processing
+ this._cache[ key ] = this.fetchData( fileName ).then( text => {
+
+ const info = this.parse( text, fileName );
+ this._cache[ key ] = info;
+ return info;
+
+ } );
+
+ }
+
+ await this._cache[ key ];
+
+ } // sets the data in the cache from parsed data
+
+
+ setData( fileName, text ) {
+
+ const key = fileName.toLowerCase();
+ this._cache[ key ] = this.parse( text, fileName );
+
+ }
+
+ } // returns the material for an associated color code. If the color code is 16 for a face or 24 for
+ // an edge then the passthroughColorCode is used.
+
+
+ function getMaterialFromCode( colorCode, parentColorCode, materialHierarchy, forEdge ) {
+
+ const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
+
+ if ( isPassthrough ) {
+
+ colorCode = parentColorCode;
+
+ }
+
+ return materialHierarchy[ colorCode ] || null;
+
+ } // Class used to parse and build LDraw parts as three.js objects and cache them if they're a "Part" type.
+
+
+ class LDrawPartsGeometryCache {
+
+ constructor( loader ) {
+
+ this.loader = loader;
+ this.parseCache = new LDrawParsedCache( loader );
+ this._cache = {};
+
+ } // Convert the given file information into a mesh by processing subobjects.
+
+
+ async processIntoMesh( info ) {
+
+ const loader = this.loader;
+ const parseCache = this.parseCache;
+ const faceMaterials = new Set(); // Processes the part subobject information to load child parts and merge geometry onto part
+ // piece object.
+
+ const processInfoSubobjects = async ( info, subobject = null ) => {
+
+ const subobjects = info.subobjects;
+ const promises = []; // Trigger load of all subobjects. If a subobject isn't a primitive then load it as a separate
+ // group which lets instruction steps apply correctly.
+
+ for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
+
+ const subobject = subobjects[ i ];
+ const promise = parseCache.ensureDataLoaded( subobject.fileName ).then( () => {
+
+ const subobjectInfo = parseCache.getData( subobject.fileName, false );
+
+ if ( ! isPrimitiveType( subobjectInfo.type ) ) {
+
+ return this.loadModel( subobject.fileName ).catch( error => {
+
+ console.warn( error );
+ return null;
} );
- return this.cache[ fileName ];
+
+ }
+
+ return processInfoSubobjects( parseCache.getData( subobject.fileName ), subobject );
+
+ } );
+ promises.push( promise );
+
+ }
+
+ const group = new THREE.Group();
+ group.userData.category = info.category;
+ group.userData.keywords = info.keywords;
+ info.group = group;
+ const subobjectInfos = await Promise.all( promises );
+
+ for ( let i = 0, l = subobjectInfos.length; i < l; i ++ ) {
+
+ const subobject = info.subobjects[ i ];
+ const subobjectInfo = subobjectInfos[ i ];
+
+ if ( subobjectInfo === null ) {
+
+ // the subobject failed to load
+ continue;
+
+ } // if the subobject was loaded as a separate group then apply the parent scopes materials
+
+
+ if ( subobjectInfo.isGroup ) {
+
+ const subobjectGroup = subobjectInfo;
+ subobject.matrix.decompose( subobjectGroup.position, subobjectGroup.quaternion, subobjectGroup.scale );
+ subobjectGroup.userData.startingConstructionStep = subobject.startingConstructionStep;
+ subobjectGroup.name = subobject.fileName;
+ loader.applyMaterialsToMesh( subobjectGroup, subobject.colorCode, info.materials );
+ group.add( subobjectGroup );
+ continue;
+
+ } // add the subobject group if it has children in case it has both children and primitives
+
+
+ if ( subobjectInfo.group.children.length ) {
+
+ group.add( subobjectInfo.group );
+
+ } // transform the primitives into the local space of the parent piece and append them to
+ // to the parent primitives list.
+
+
+ const parentLineSegments = info.lineSegments;
+ const parentConditionalSegments = info.conditionalSegments;
+ const parentFaces = info.faces;
+ const lineSegments = subobjectInfo.lineSegments;
+ const conditionalSegments = subobjectInfo.conditionalSegments;
+ const faces = subobjectInfo.faces;
+ const matrix = subobject.matrix;
+ const inverted = subobject.inverted;
+ const matrixScaleInverted = matrix.determinant() < 0;
+ const colorCode = subobject.colorCode;
+ const lineColorCode = colorCode === MAIN_COLOUR_CODE ? MAIN_EDGE_COLOUR_CODE : colorCode;
+
+ for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
+
+ const ls = lineSegments[ i ];
+ const vertices = ls.vertices;
+ vertices[ 0 ].applyMatrix4( matrix );
+ vertices[ 1 ].applyMatrix4( matrix );
+ ls.colorCode = ls.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : ls.colorCode;
+ ls.material = ls.material || getMaterialFromCode( ls.colorCode, ls.colorCode, info.materials, true );
+ parentLineSegments.push( ls );
+
+ }
+
+ for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
+
+ const os = conditionalSegments[ i ];
+ const vertices = os.vertices;
+ const controlPoints = os.controlPoints;
+ vertices[ 0 ].applyMatrix4( matrix );
+ vertices[ 1 ].applyMatrix4( matrix );
+ controlPoints[ 0 ].applyMatrix4( matrix );
+ controlPoints[ 1 ].applyMatrix4( matrix );
+ os.colorCode = os.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : os.colorCode;
+ os.material = os.material || getMaterialFromCode( os.colorCode, os.colorCode, info.materials, true );
+ parentConditionalSegments.push( os );
+
+ }
+
+ for ( let i = 0, l = faces.length; i < l; i ++ ) {
+
+ const tri = faces[ i ];
+ const vertices = tri.vertices;
+
+ for ( let i = 0, l = vertices.length; i < l; i ++ ) {
+
+ vertices[ i ].applyMatrix4( matrix );
+
+ }
+
+ tri.colorCode = tri.colorCode === MAIN_COLOUR_CODE ? colorCode : tri.colorCode;
+ tri.material = tri.material || getMaterialFromCode( tri.colorCode, colorCode, info.materials, false );
+ faceMaterials.add( tri.colorCode ); // If the scale of the object is negated then the triangle winding order
+ // needs to be flipped.
+
+ if ( matrixScaleInverted !== inverted ) {
+
+ vertices.reverse();
+
+ }
+
+ parentFaces.push( tri );
+
+ }
+
+ info.totalFaces += subobjectInfo.totalFaces;
+
+ } // Apply the parent subobjects pass through material code to this object. This is done several times due
+ // to material scoping.
+
+
+ if ( subobject ) {
+
+ loader.applyMaterialsToMesh( group, subobject.colorCode, info.materials );
+
+ }
+
+ return info;
+
+ }; // Track material use to see if we need to use the normal smooth slow path for hard edges.
+
+
+ for ( let i = 0, l = info.faces; i < l; i ++ ) {
+
+ faceMaterials.add( info.faces[ i ].colorCode );
+
+ }
+
+ await processInfoSubobjects( info );
+
+ if ( loader.smoothNormals ) {
+
+ const checkSubSegments = faceMaterials.size > 1;
+ generateFaceNormals( info.faces );
+ smoothNormals( info.faces, info.lineSegments, checkSubSegments );
+
+ } // Add the primitive objects and metadata.
+
+
+ const group = info.group;
+
+ if ( info.faces.length > 0 ) {
+
+ group.add( createObject( info.faces, 3, false, info.totalFaces ) );
+
+ }
+
+ if ( info.lineSegments.length > 0 ) {
+
+ group.add( createObject( info.lineSegments, 2 ) );
+
+ }
+
+ if ( info.conditionalSegments.length > 0 ) {
+
+ group.add( createObject( info.conditionalSegments, 2, true ) );
+
+ }
+
+ return group;
+
+ }
+
+ hasCachedModel( fileName ) {
+
+ return fileName !== null && fileName.toLowerCase() in this._cache;
+
+ }
+
+ async getCachedModel( fileName ) {
+
+ if ( fileName !== null && this.hasCachedModel( fileName ) ) {
+
+ const key = fileName.toLowerCase();
+ const group = await this._cache[ key ];
+ return group.clone();
+
+ } else {
+
+ return null;
+
+ }
+
+ } // Loads and parses the model with the given file name. Returns a cached copy if available.
+
+
+ async loadModel( fileName ) {
+
+ const parseCache = this.parseCache;
+ const key = fileName.toLowerCase();
+
+ if ( this.hasCachedModel( fileName ) ) {
+
+ // Return cached model if available.
+ return this.getCachedModel( fileName );
+
+ } else {
+
+ // Otherwise parse a new model.
+ // Ensure the file data is loaded and pre parsed.
+ await parseCache.ensureDataLoaded( fileName );
+ const info = parseCache.getData( fileName );
+ const promise = this.processIntoMesh( info ); // Now that the file has loaded it's possible that another part parse has been waiting in parallel
+ // so check the cache again to see if it's been added since the last async operation so we don't
+ // do unnecessary work.
+
+ if ( this.hasCachedModel( fileName ) ) {
+
+ return this.getCachedModel( fileName );
+
+ } // Cache object if it's a part so it can be reused later.
+
+
+ if ( isPartType( info.type ) ) {
+
+ this._cache[ key ] = promise;
+
+ } // return a copy
+
+
+ const group = await promise;
+ return group.clone();
+
+ }
+
+ } // parses the given model text into a renderable object. Returns cached copy if available.
+
+
+ async parseModel( text ) {
+
+ const parseCache = this.parseCache;
+ const info = parseCache.parse( text );
+
+ if ( isPartType( info.type ) && this.hasCachedModel( info.fileName ) ) {
+
+ return this.getCachedModel( info.fileName );
+
+ }
+
+ return this.processIntoMesh( info );
}
@@ -571,13 +1521,13 @@
function sortByMaterial( a, b ) {
- if ( a.colourCode === b.colourCode ) {
+ if ( a.colorCode === b.colorCode ) {
return 0;
}
- if ( a.colourCode < b.colourCode ) {
+ if ( a.colorCode < b.colorCode ) {
return - 1;
@@ -591,7 +1541,7 @@
// Creates a THREE.LineSegments (elementSize = 2) or a THREE.Mesh (elementSize = 3 )
// With per face / segment material, implemented with mesh groups and materials array
- // Sort the faces or line segments by colour code to make later the mesh groups
+ // Sort the faces or line segments by color code to make later the mesh groups
elements.sort( sortByMaterial );
if ( totalElements === null ) {
@@ -635,10 +1585,25 @@
positions[ index + 1 ] = v.y;
positions[ index + 2 ] = v.z;
- }
+ } // create the normals array if this is a set of faces
+
if ( elementSize === 3 ) {
+ if ( ! elem.faceNormal ) {
+
+ const v0 = vertices[ 0 ];
+ const v1 = vertices[ 1 ];
+ const v2 = vertices[ 2 ];
+
+ _tempVec0.subVectors( v1, v0 );
+
+ _tempVec1.subVectors( v2, v1 );
+
+ elem.faceNormal = new THREE.Vector3().crossVectors( _tempVec0, _tempVec1 ).normalize();
+
+ }
+
let elemNormals = elem.normals;
if ( elemNormals.length === 4 ) {
@@ -655,6 +1620,7 @@
for ( let j = 0, l = elemNormals.length; j < l; j ++ ) {
+ // use face normal if a vertex normal is not provided
let n = elem.faceNormal;
if ( elemNormals[ j ] ) {
@@ -672,7 +1638,7 @@
}
- if ( prevMaterial !== elem.material ) {
+ if ( prevMaterial !== elem.colorCode ) {
if ( prevMaterial !== null ) {
@@ -680,8 +1646,45 @@
}
- materials.push( elem.material );
- prevMaterial = elem.material;
+ const material = elem.material;
+
+ if ( material !== null ) {
+
+ if ( elementSize === 3 ) {
+
+ materials.push( material );
+
+ } else if ( elementSize === 2 ) {
+
+ if ( material !== null ) {
+
+ if ( isConditionalSegments ) {
+
+ materials.push( material.userData.edgeMaterial.userData.conditionalEdgeMaterial );
+
+ } else {
+
+ materials.push( material.userData.edgeMaterial );
+
+ }
+
+ } else {
+
+ materials.push( null );
+
+ }
+
+ }
+
+ } else {
+
+ // If a material has not been made available yet then keep the color code string in the material array
+ // to save the spot for the material once a parent scopes materials are being applied to the object.
+ materials.push( elem.colorCode );
+
+ }
+
+ prevMaterial = elem.colorCode;
index0 = offset / 3;
numGroupVerts = vertices.length;
@@ -713,8 +1716,16 @@
if ( elementSize === 2 ) {
+ if ( isConditionalSegments ) {
+
+ object3d = new ConditionalLineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
+
+ } else {
+
object3d = new THREE.LineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
+ }
+
} else if ( elementSize === 3 ) {
object3d = new THREE.Mesh( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
@@ -776,18 +1787,14 @@
super( manager ); // Array of THREE.Material
- this.materials = []; // Not using THREE.Cache here because it returns the previous HTML error response instead of calling onError()
- // This also allows to handle the embedded text files ("0 FILE" lines)
-
- this.cache = new LDrawFileCache( this ); // This object is a map from file names to paths. It agilizes the paths search. If it is not set then files will be searched by trial and error.
+ this.materials = [];
+ this.materialLibrary = {}; // This also allows to handle the embedded text files ("0 FILE" lines)
- this.fileMap = null;
- this.rootParseScope = this.newParseScopeLevel(); // Add default main triangle and line edge materials (used in pieces that can be coloured with a main color)
+ this.partsCache = new LDrawPartsGeometryCache( this ); // This object is a map from file names to paths. It agilizes the paths search. If it is not set then files will be searched by trial and error.
- this.setMaterials( [ this.parseColourMetaDirective( new LineParser( 'Main_Colour CODE 16 VALUE #FF8080 EDGE #333333' ) ), this.parseColourMetaDirective( new LineParser( 'Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333' ) ) ] ); // If this flag is set to true, each subobject will be a Object.
- // If not (the default), only one object which contains all the merged primitives will be created.
+ this.fileMap = {}; // Initializes the materials library with default materials
- this.separateObjects = false; // If this flag is set to true the vertex normals will be smoothed.
+ this.setMaterials( [] ); // If this flag is set to true the vertex normals will be smoothed.
this.smoothNormals = true; // The path to load parts from the LDraw parts library from.
@@ -820,7 +1827,7 @@
if ( colorLineRegex.test( line ) ) {
const directive = line.replace( colorLineRegex, '' );
- const material = this.parseColourMetaDirective( new LineParser( directive ) );
+ const material = this.parseColorMetaDirective( new LineParser( directive ) );
materials.push( material );
}
@@ -833,34 +1840,30 @@
load( url, onLoad, onProgress, onError ) {
- if ( ! this.fileMap ) {
-
- this.fileMap = {};
-
- }
-
const fileLoader = new THREE.FileLoader( this.manager );
fileLoader.setPath( this.path );
fileLoader.setRequestHeader( this.requestHeader );
fileLoader.setWithCredentials( this.withCredentials );
fileLoader.load( url, text => {
- this.processObject( text, null, url, this.rootParseScope ).then( function ( result ) {
+ this.partsCache.parseModel( text, this.materialLibrary ).then( group => {
- onLoad( result.groupObject );
+ this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
+ this.computeConstructionSteps( group );
+ onLoad( group );
- } );
+ } ).catch( onError );
}, onProgress, onError );
}
- parse( text, path, onLoad ) {
+ parse( text, onLoad ) {
- // Async parse. This function calls onParse with the parsed THREE.Object3D as parameter
- this.processObject( text, null, path, this.rootParseScope ).then( function ( result ) {
+ this.partsCache.parseModel( text, this.materialLibrary ).then( group => {
- onLoad( result.groupObject );
+ this.computeConstructionSteps( group );
+ onLoad( group );
} );
@@ -868,10 +1871,18 @@
setMaterials( materials ) {
- // Clears parse scopes stack, adds new scope with material library
- this.rootParseScope = this.newParseScopeLevel( materials );
- this.rootParseScope.isFromParse = false;
- this.materials = materials;
+ this.materialLibrary = {};
+ this.materials = [];
+
+ for ( let i = 0, l = materials.length; i < l; i ++ ) {
+
+ this.addMaterial( materials[ i ] );
+
+ } // Add default main triangle and line edge materials (used in pieces that can be colored with a main color)
+
+
+ this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Main_Colour CODE 16 VALUE #FF8080 EDGE #333333' ) ) );
+ this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333' ) ) );
return this;
}
@@ -883,109 +1894,153 @@
}
- newParseScopeLevel( materials = null, parentScope = null ) {
+ addMaterial( material ) {
- // Adds a new scope level, assign materials to it and returns it
- const matLib = {};
-
- if ( materials ) {
+ // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
+ const matLib = this.materialLibrary;
- for ( let i = 0, n = materials.length; i < n; i ++ ) {
+ if ( ! matLib[ material.userData.code ] ) {
- const material = materials[ i ];
+ this.materials.push( material );
matLib[ material.userData.code ] = material;
}
+ return this;
+
}
- const newParseScope = {
- parentScope: parentScope,
- lib: matLib,
- url: null,
- // Subobjects
- subobjects: null,
- numSubobjects: 0,
- subobjectIndex: 0,
- inverted: false,
- category: null,
- keywords: null,
- // Current subobject
- currentFileName: null,
- mainColourCode: parentScope ? parentScope.mainColourCode : '16',
- mainEdgeColourCode: parentScope ? parentScope.mainEdgeColourCode : '24',
- currentMatrix: new THREE.Matrix4(),
- matrix: new THREE.Matrix4(),
- type: 'Model',
- groupObject: null,
- // If false, it is a root material scope previous to parse
- isFromParse: true,
- faces: [],
- lineSegments: [],
- conditionalSegments: [],
- totalFaces: 0,
- // If true, this object is the start of a construction step
- startingConstructionStep: false
- };
- return newParseScope;
+ getMaterial( colorCode ) {
+
+ if ( colorCode.startsWith( '0x2' ) ) {
+
+ // Special 'direct' material value (RGB color)
+ const color = colorCode.substring( 3 );
+ return this.parseColorMetaDirective( new LineParser( 'Direct_Color_' + color + ' CODE -1 VALUE #' + color + ' EDGE #' + color + '' ) );
}
- addMaterial( material, parseScope ) {
+ return this.materialLibrary[ colorCode ] || null;
- // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
- const matLib = parseScope.lib;
+ } // Applies the appropriate materials to a prebuilt hierarchy of geometry. Assumes that color codes are present
+ // in the material array if they need to be filled in.
- if ( ! matLib[ material.userData.code ] ) {
- this.materials.push( material );
+ applyMaterialsToMesh( group, parentColorCode, materialHierarchy, finalMaterialPass = false ) {
+
+ // find any missing materials as indicated by a color code string and replace it with a material from the current material lib
+ const loader = this;
+ const parentIsPassthrough = parentColorCode === MAIN_COLOUR_CODE;
+ group.traverse( c => {
+
+ if ( c.isMesh || c.isLineSegments ) {
+
+ if ( Array.isArray( c.material ) ) {
+
+ for ( let i = 0, l = c.material.length; i < l; i ++ ) {
+
+ if ( ! c.material[ i ].isMaterial ) {
+
+ c.material[ i ] = getMaterial( c, c.material[ i ] );
}
- matLib[ material.userData.code ] = material;
- return this;
+ }
+
+ } else if ( ! c.material.isMaterial ) {
+
+ c.material = getMaterial( c, c.material );
}
- getMaterial( colourCode, parseScope = this.rootParseScope ) {
+ }
- // Given a colour code search its material in the parse scopes stack
- if ( colourCode.startsWith( '0x2' ) ) {
+ } ); // Returns the appropriate material for the object (line or face) given color code. If the code is "pass through"
+ // (24 for lines, 16 for edges) then the pass through color code is used. If that is also pass through then it's
+ // simply returned for the subsequent material application.
- // Special 'direct' material value (RGB colour)
- const colour = colourCode.substring( 3 );
- return this.parseColourMetaDirective( new LineParser( 'Direct_Color_' + colour + ' CODE -1 VALUE #' + colour + ' EDGE #' + colour + '' ) );
+ function getMaterial( c, colorCode ) {
+
+ // if our parent is a passthrough color code and we don't have the current material color available then
+ // return early.
+ if ( parentIsPassthrough && ! ( colorCode in materialHierarchy ) && ! finalMaterialPass ) {
+
+ return colorCode;
}
- while ( parseScope ) {
+ const forEdge = c.isLineSegments || c.isConditionalLine;
+ const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
- const material = parseScope.lib[ colourCode ];
+ if ( isPassthrough ) {
- if ( material ) {
+ colorCode = parentColorCode;
- return material;
+ }
+
+ let material = null;
+
+ if ( colorCode in materialHierarchy ) {
+
+ material = materialHierarchy[ colorCode ];
+
+ } else if ( finalMaterialPass ) {
+
+ // see if we can get the final material from from the "getMaterial" function which will attempt to
+ // parse the "direct" colors
+ material = loader.getMaterial( colorCode );
+
+ if ( material === null ) {
+
+ // otherwise throw an error if this is final opportunity to set the material
+ throw new Error( `LDrawLoader: Material properties for code ${colorCode} not available.` );
+
+ }
} else {
- parseScope = parseScope.parentScope;
+ return colorCode;
}
- } // Material was not found
+ if ( c.isLineSegments ) {
+ material = material.userData.edgeMaterial;
- return null;
+ if ( c.isConditionalLine ) {
+
+ material = material.userData.conditionalEdgeMaterial;
}
- parseColourMetaDirective( lineParser ) {
+ }
- // Parses a colour definition and returns a THREE.Material
- let code = null; // Triangle and line colours
+ return material;
- let colour = 0xFF00FF;
- let edgeColour = 0xFF00FF; // Transparency
+ }
+
+ }
+
+ getMainMaterial() {
+
+ return this.getMaterial( MAIN_COLOUR_CODE );
+
+ }
+
+ getMainEdgeMaterial() {
+
+ const mainMat = this.getMainMaterial();
+ return mainMat && mainMat.userData ? mainMat.userData.edgeMaterial : null;
+
+ }
+
+ parseColorMetaDirective( lineParser ) {
+
+ // Parses a color definition and returns a THREE.Material
+ let code = null; // Triangle and line colors
+
+ let color = 0xFF00FF;
+ let edgeColor = 0xFF00FF; // Transparency
let alpha = 1;
let isTransparent = false; // Self-illumination:
@@ -997,7 +2052,7 @@
if ( ! name ) {
- throw 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.';
+ throw new Error( 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.' );
} // Parse tag tokens and their parameters
@@ -1021,35 +2076,35 @@
break;
case 'VALUE':
- colour = lineParser.getToken();
+ color = lineParser.getToken();
- if ( colour.startsWith( '0x' ) ) {
+ if ( color.startsWith( '0x' ) ) {
- colour = '#' + colour.substring( 2 );
+ color = '#' + color.substring( 2 );
- } else if ( ! colour.startsWith( '#' ) ) {
+ } else if ( ! color.startsWith( '#' ) ) {
- throw 'LDrawLoader: Invalid colour while parsing material' + lineParser.getLineNumberString() + '.';
+ throw new Error( 'LDrawLoader: Invalid color while parsing material' + lineParser.getLineNumberString() + '.' );
}
break;
case 'EDGE':
- edgeColour = lineParser.getToken();
+ edgeColor = lineParser.getToken();
- if ( edgeColour.startsWith( '0x' ) ) {
+ if ( edgeColor.startsWith( '0x' ) ) {
- edgeColour = '#' + edgeColour.substring( 2 );
+ edgeColor = '#' + edgeColor.substring( 2 );
- } else if ( ! edgeColour.startsWith( '#' ) ) {
+ } else if ( ! edgeColor.startsWith( '#' ) ) {
- // Try to see if edge colour is a colour code
- edgeMaterial = this.getMaterial( edgeColour );
+ // Try to see if edge color is a color code
+ edgeMaterial = this.getMaterial( edgeColor );
if ( ! edgeMaterial ) {
- throw 'LDrawLoader: Invalid edge colour while parsing material' + lineParser.getLineNumberString() + '.';
+ throw new Error( 'LDrawLoader: Invalid edge color while parsing material' + lineParser.getLineNumberString() + '.' );
} // Get the edge material for this triangle material
@@ -1065,7 +2120,7 @@
if ( isNaN( alpha ) ) {
- throw 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.';
+ throw new Error( 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.' );
}
@@ -1084,7 +2139,7 @@
if ( isNaN( luminance ) ) {
- throw 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.';
+ throw new Error( 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.' );
}
@@ -1117,8 +2172,7 @@
break;
default:
- throw 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.';
- break;
+ throw new Error( 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.' );
}
@@ -1130,7 +2184,7 @@
case FINISH_TYPE_DEFAULT:
material = new THREE.MeshStandardMaterial( {
- color: colour,
+ color: color,
roughness: 0.3,
metalness: 0
} );
@@ -1139,7 +2193,7 @@
case FINISH_TYPE_PEARLESCENT:
// Try to imitate pearlescency by making the surface glossy
material = new THREE.MeshStandardMaterial( {
- color: colour,
+ color: color,
roughness: 0.3,
metalness: 0.25
} );
@@ -1148,7 +2202,7 @@
case FINISH_TYPE_CHROME:
// Mirror finish surface
material = new THREE.MeshStandardMaterial( {
- color: colour,
+ color: color,
roughness: 0,
metalness: 1
} );
@@ -1157,7 +2211,7 @@
case FINISH_TYPE_RUBBER:
// Rubber finish
material = new THREE.MeshStandardMaterial( {
- color: colour,
+ color: color,
roughness: 0.9,
metalness: 0
} );
@@ -1166,7 +2220,7 @@
case FINISH_TYPE_MATTE_METALLIC:
// Brushed metal finish
material = new THREE.MeshStandardMaterial( {
- color: colour,
+ color: color,
roughness: 0.8,
metalness: 0.4
} );
@@ -1175,7 +2229,7 @@
case FINISH_TYPE_METAL:
// Average metal finish
material = new THREE.MeshStandardMaterial( {
- color: colour,
+ color: color,
roughness: 0.2,
metalness: 0.85
} );
@@ -1191,6 +2245,7 @@
material.premultipliedAlpha = true;
material.opacity = alpha;
material.depthWrite = ! isTransparent;
+ material.color.convertSRGBToLinear();
material.polygonOffset = true;
material.polygonOffsetFactor = 1;
@@ -1204,500 +2259,32 @@
// This is the material used for edges
edgeMaterial = new THREE.LineBasicMaterial( {
- color: edgeColour,
+ color: edgeColor,
transparent: isTransparent,
opacity: alpha,
depthWrite: ! isTransparent
} );
edgeMaterial.userData.code = code;
- edgeMaterial.name = name + ' - Edge'; // This is the material used for conditional edges
+ edgeMaterial.name = name + ' - Edge';
+ edgeMaterial.color.convertSRGBToLinear(); // This is the material used for conditional edges
edgeMaterial.userData.conditionalEdgeMaterial = new LDrawConditionalLineMaterial( {
fog: true,
transparent: isTransparent,
depthWrite: ! isTransparent,
- color: edgeColour,
+ color: edgeColor,
opacity: alpha
} );
+ edgeMaterial.userData.conditionalEdgeMaterial.color.convertSRGBToLinear();
}
material.userData.code = code;
material.name = name;
material.userData.edgeMaterial = edgeMaterial;
+ this.addMaterial( material );
return material;
- } //
-
-
- objectParse( text, parseScope ) {
-
- // Retrieve data from the parent parse scope
- const currentParseScope = parseScope;
- const parentParseScope = currentParseScope.parentScope; // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
-
- const mainColourCode = currentParseScope.mainColourCode;
- const mainEdgeColourCode = currentParseScope.mainEdgeColourCode; // Parse result variables
-
- let faces;
- let lineSegments;
- let conditionalSegments;
- const subobjects = [];
- let category = null;
- let keywords = null;
-
- if ( text.indexOf( '\r\n' ) !== - 1 ) {
-
- // This is faster than String.split with regex that splits on both
- text = text.replace( /\r\n/g, '\n' );
-
- }
-
- const lines = text.split( '\n' );
- const numLines = lines.length;
- let parsingEmbeddedFiles = false;
- let currentEmbeddedFileName = null;
- let currentEmbeddedText = null;
- let bfcCertified = false;
- let bfcCCW = true;
- let bfcInverted = false;
- let bfcCull = true;
- let type = '';
- let startingConstructionStep = false;
- const scope = this;
-
- function parseColourCode( lineParser, forEdge ) {
-
- // Parses next colour code and returns a THREE.Material
- let colourCode = lineParser.getToken();
-
- if ( ! forEdge && colourCode === '16' ) {
-
- colourCode = mainColourCode;
-
- }
-
- if ( forEdge && colourCode === '24' ) {
-
- colourCode = mainEdgeColourCode;
-
- }
-
- const material = scope.getMaterial( colourCode, currentParseScope );
-
- if ( ! material ) {
-
- throw 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.';
-
- }
-
- return material;
-
- }
-
- function parseVector( lp ) {
-
- const v = new THREE.Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
-
- if ( ! scope.separateObjects ) {
-
- v.applyMatrix4( currentParseScope.currentMatrix );
-
- }
-
- return v;
-
- } // Parse all line commands
-
-
- for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
-
- const line = lines[ lineIndex ];
- if ( line.length === 0 ) continue;
-
- if ( parsingEmbeddedFiles ) {
-
- if ( line.startsWith( '0 FILE ' ) ) {
-
- // Save previous embedded file in the cache
- this.cache.setData( currentEmbeddedFileName.toLowerCase(), currentEmbeddedText ); // New embedded text file
-
- currentEmbeddedFileName = line.substring( 7 );
- currentEmbeddedText = '';
-
- } else {
-
- currentEmbeddedText += line + '\n';
-
- }
-
- continue;
-
- }
-
- const lp = new LineParser( line, lineIndex + 1 );
- lp.seekNonSpace();
-
- if ( lp.isAtTheEnd() ) {
-
- // Empty line
- continue;
-
- } // Parse the line type
-
-
- const lineType = lp.getToken();
- let material;
- let segment;
- let inverted;
- let ccw;
- let doubleSided;
- let v0, v1, v2, v3, c0, c1, faceNormal;
-
- switch ( lineType ) {
-
- // Line type 0: Comment or META
- case '0':
- // Parse meta directive
- const meta = lp.getToken();
-
- if ( meta ) {
-
- switch ( meta ) {
-
- case '!LDRAW_ORG':
- type = lp.getToken();
- currentParseScope.type = type; // If the scale of the object is negated then the triangle winding order
- // needs to be flipped.
-
- if ( currentParseScope.matrix.determinant() < 0 && ( scope.separateObjects && isPrimitiveType( type ) || ! scope.separateObjects ) ) {
-
- currentParseScope.inverted = ! currentParseScope.inverted;
-
- }
-
- faces = currentParseScope.faces;
- lineSegments = currentParseScope.lineSegments;
- conditionalSegments = currentParseScope.conditionalSegments;
- break;
-
- case '!COLOUR':
- material = this.parseColourMetaDirective( lp );
-
- if ( material ) {
-
- this.addMaterial( material, parseScope );
-
- } else {
-
- console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
-
- }
-
- break;
-
- case '!CATEGORY':
- category = lp.getToken();
- break;
-
- case '!KEYWORDS':
- const newKeywords = lp.getRemainingString().split( ',' );
-
- if ( newKeywords.length > 0 ) {
-
- if ( ! keywords ) {
-
- keywords = [];
-
- }
-
- newKeywords.forEach( function ( keyword ) {
-
- keywords.push( keyword.trim() );
-
- } );
-
- }
-
- break;
-
- case 'FILE':
- if ( lineIndex > 0 ) {
-
- // Start embedded text files parsing
- parsingEmbeddedFiles = true;
- currentEmbeddedFileName = lp.getRemainingString();
- currentEmbeddedText = '';
- bfcCertified = false;
- bfcCCW = true;
-
- }
-
- break;
-
- case 'BFC':
- // Changes to the backface culling state
- while ( ! lp.isAtTheEnd() ) {
-
- const token = lp.getToken();
-
- switch ( token ) {
-
- case 'CERTIFY':
- case 'NOCERTIFY':
- bfcCertified = token === 'CERTIFY';
- bfcCCW = true;
- break;
-
- case 'CW':
- case 'CCW':
- bfcCCW = token === 'CCW';
- break;
-
- case 'INVERTNEXT':
- bfcInverted = true;
- break;
-
- case 'CLIP':
- case 'NOCLIP':
- bfcCull = token === 'CLIP';
- break;
-
- default:
- console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
- break;
-
- }
-
- }
-
- break;
-
- case 'STEP':
- startingConstructionStep = true;
- break;
-
- default:
- // Other meta directives are not implemented
- break;
-
- }
-
- }
-
- break;
- // Line type 1: Sub-object file
-
- case '1':
- material = parseColourCode( lp );
- const posX = parseFloat( lp.getToken() );
- const posY = parseFloat( lp.getToken() );
- const posZ = parseFloat( lp.getToken() );
- const m0 = parseFloat( lp.getToken() );
- const m1 = parseFloat( lp.getToken() );
- const m2 = parseFloat( lp.getToken() );
- const m3 = parseFloat( lp.getToken() );
- const m4 = parseFloat( lp.getToken() );
- const m5 = parseFloat( lp.getToken() );
- const m6 = parseFloat( lp.getToken() );
- const m7 = parseFloat( lp.getToken() );
- const m8 = parseFloat( lp.getToken() );
- const matrix = new THREE.Matrix4().set( m0, m1, m2, posX, m3, m4, m5, posY, m6, m7, m8, posZ, 0, 0, 0, 1 );
- let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
-
- if ( scope.fileMap[ fileName ] ) {
-
- // Found the subobject path in the preloaded file path map
- fileName = scope.fileMap[ fileName ];
-
- } else {
-
- // Standardized subfolders
- if ( fileName.startsWith( 's/' ) ) {
-
- fileName = 'parts/' + fileName;
-
- } else if ( fileName.startsWith( '48/' ) ) {
-
- fileName = 'p/' + fileName;
-
- }
-
- }
-
- subobjects.push( {
- material: material,
- matrix: matrix,
- fileName: fileName,
- inverted: bfcInverted !== currentParseScope.inverted,
- startingConstructionStep: startingConstructionStep
- } );
- bfcInverted = false;
- break;
- // Line type 2: Line segment
-
- case '2':
- material = parseColourCode( lp, true );
- v0 = parseVector( lp );
- v1 = parseVector( lp );
- segment = {
- material: material.userData.edgeMaterial,
- colourCode: material.userData.code,
- v0: v0,
- v1: v1,
- vertices: [ v0, v1 ]
- };
- lineSegments.push( segment );
- break;
- // Line type 5: Conditional Line segment
-
- case '5':
- material = parseColourCode( lp, true );
- v0 = parseVector( lp );
- v1 = parseVector( lp );
- c0 = parseVector( lp );
- c1 = parseVector( lp );
- segment = {
- material: material.userData.edgeMaterial.userData.conditionalEdgeMaterial,
- colourCode: material.userData.code,
- vertices: [ v0, v1 ],
- controlPoints: [ c0, c1 ]
- };
- conditionalSegments.push( segment );
- break;
- // Line type 3: Triangle
-
- case '3':
- material = parseColourCode( lp );
- inverted = currentParseScope.inverted;
- ccw = bfcCCW !== inverted;
- doubleSided = ! bfcCertified || ! bfcCull;
-
- if ( ccw === true ) {
-
- v0 = parseVector( lp );
- v1 = parseVector( lp );
- v2 = parseVector( lp );
-
- } else {
-
- v2 = parseVector( lp );
- v1 = parseVector( lp );
- v0 = parseVector( lp );
-
- }
-
- _tempVec0.subVectors( v1, v0 );
-
- _tempVec1.subVectors( v2, v1 );
-
- faceNormal = new THREE.Vector3().crossVectors( _tempVec0, _tempVec1 ).normalize();
- faces.push( {
- material: material,
- colourCode: material.userData.code,
- faceNormal: faceNormal,
- vertices: [ v0, v1, v2 ],
- normals: [ null, null, null ]
- } );
- currentParseScope.totalFaces ++;
-
- if ( doubleSided === true ) {
-
- faces.push( {
- material: material,
- colourCode: material.userData.code,
- faceNormal: faceNormal,
- vertices: [ v2, v1, v0 ],
- normals: [ null, null, null ]
- } );
- currentParseScope.totalFaces ++;
-
- }
-
- break;
- // Line type 4: Quadrilateral
-
- case '4':
- material = parseColourCode( lp );
- inverted = currentParseScope.inverted;
- ccw = bfcCCW !== inverted;
- doubleSided = ! bfcCertified || ! bfcCull;
-
- if ( ccw === true ) {
-
- v0 = parseVector( lp );
- v1 = parseVector( lp );
- v2 = parseVector( lp );
- v3 = parseVector( lp );
-
- } else {
-
- v3 = parseVector( lp );
- v2 = parseVector( lp );
- v1 = parseVector( lp );
- v0 = parseVector( lp );
-
- }
-
- _tempVec0.subVectors( v1, v0 );
-
- _tempVec1.subVectors( v2, v1 );
-
- faceNormal = new THREE.Vector3().crossVectors( _tempVec0, _tempVec1 ).normalize(); // specifically place the triangle diagonal in the v0 and v1 slots so we can
- // account for the doubling of vertices later when smoothing normals.
-
- faces.push( {
- material: material,
- colourCode: material.userData.code,
- faceNormal: faceNormal,
- vertices: [ v0, v1, v2, v3 ],
- normals: [ null, null, null, null ]
- } );
- currentParseScope.totalFaces += 2;
-
- if ( doubleSided === true ) {
-
- faces.push( {
- material: material,
- colourCode: material.userData.code,
- faceNormal: faceNormal,
- vertices: [ v3, v2, v1, v0 ],
- normals: [ null, null, null, null ]
- } );
- currentParseScope.totalFaces += 2;
-
- }
-
- break;
-
- default:
- throw 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.';
- break;
-
- }
-
- }
-
- if ( parsingEmbeddedFiles ) {
-
- this.cache.setData( currentEmbeddedFileName.toLowerCase(), currentEmbeddedText );
-
- }
-
- currentParseScope.category = category;
- currentParseScope.keywords = keywords;
- currentParseScope.subobjects = subobjects;
- currentParseScope.numSubobjects = subobjects.length;
- currentParseScope.subobjectIndex = 0;
- const isRoot = ! parentParseScope.isFromParse;
-
- if ( isRoot || scope.separateObjects && ! isPrimitiveType( type ) ) {
-
- currentParseScope.groupObject = new THREE.Group();
- currentParseScope.groupObject.userData.startingConstructionStep = currentParseScope.startingConstructionStep;
-
- }
-
}
computeConstructionSteps( model ) {
@@ -1723,205 +2310,6 @@
}
- finalizeObject( subobjectParseScope ) {
-
- // fail gracefully if an object could not be loaded
- if ( subobjectParseScope === null ) {
-
- return;
-
- }
-
- const parentParseScope = subobjectParseScope.parentScope; // Smooth the normals if this is a part or if this is a case where the subpart
- // is added directly into the parent model (meaning it will never get smoothed by
- // being added to a part)
-
- const doSmooth = isPartType( subobjectParseScope.type ) || ! isPartType( subobjectParseScope.type ) && ! isModelType( subobjectParseScope.type ) && isModelType( subobjectParseScope.parentScope.type );
-
- if ( this.smoothNormals && doSmooth ) {
-
- smoothNormals( subobjectParseScope.faces, subobjectParseScope.lineSegments );
-
- }
-
- const isRoot = ! parentParseScope.isFromParse;
-
- if ( this.separateObjects && ! isPrimitiveType( subobjectParseScope.type ) || isRoot ) {
-
- const objGroup = subobjectParseScope.groupObject;
-
- if ( subobjectParseScope.faces.length > 0 ) {
-
- objGroup.add( createObject( subobjectParseScope.faces, 3, false, subobjectParseScope.totalFaces ) );
-
- }
-
- if ( subobjectParseScope.lineSegments.length > 0 ) {
-
- objGroup.add( createObject( subobjectParseScope.lineSegments, 2 ) );
-
- }
-
- if ( subobjectParseScope.conditionalSegments.length > 0 ) {
-
- objGroup.add( createObject( subobjectParseScope.conditionalSegments, 2, true ) );
-
- }
-
- if ( parentParseScope.groupObject ) {
-
- objGroup.name = subobjectParseScope.fileName;
- objGroup.userData.category = subobjectParseScope.category;
- objGroup.userData.keywords = subobjectParseScope.keywords;
- subobjectParseScope.matrix.decompose( objGroup.position, objGroup.quaternion, objGroup.scale );
- parentParseScope.groupObject.add( objGroup );
-
- }
-
- } else {
-
- const separateObjects = this.separateObjects;
- const parentLineSegments = parentParseScope.lineSegments;
- const parentConditionalSegments = parentParseScope.conditionalSegments;
- const parentFaces = parentParseScope.faces;
- const lineSegments = subobjectParseScope.lineSegments;
- const conditionalSegments = subobjectParseScope.conditionalSegments;
- const faces = subobjectParseScope.faces;
-
- for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
-
- const ls = lineSegments[ i ];
-
- if ( separateObjects ) {
-
- const vertices = ls.vertices;
- vertices[ 0 ].applyMatrix4( subobjectParseScope.matrix );
- vertices[ 1 ].applyMatrix4( subobjectParseScope.matrix );
-
- }
-
- parentLineSegments.push( ls );
-
- }
-
- for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
-
- const os = conditionalSegments[ i ];
-
- if ( separateObjects ) {
-
- const vertices = os.vertices;
- const controlPoints = os.controlPoints;
- vertices[ 0 ].applyMatrix4( subobjectParseScope.matrix );
- vertices[ 1 ].applyMatrix4( subobjectParseScope.matrix );
- controlPoints[ 0 ].applyMatrix4( subobjectParseScope.matrix );
- controlPoints[ 1 ].applyMatrix4( subobjectParseScope.matrix );
-
- }
-
- parentConditionalSegments.push( os );
-
- }
-
- for ( let i = 0, l = faces.length; i < l; i ++ ) {
-
- const tri = faces[ i ];
-
- if ( separateObjects ) {
-
- const vertices = tri.vertices;
-
- for ( let i = 0, l = vertices.length; i < l; i ++ ) {
-
- vertices[ i ] = vertices[ i ].clone().applyMatrix4( subobjectParseScope.matrix );
-
- }
-
- _tempVec0.subVectors( vertices[ 1 ], vertices[ 0 ] );
-
- _tempVec1.subVectors( vertices[ 2 ], vertices[ 1 ] );
-
- tri.faceNormal.crossVectors( _tempVec0, _tempVec1 ).normalize();
-
- }
-
- parentFaces.push( tri );
-
- }
-
- parentParseScope.totalFaces += subobjectParseScope.totalFaces;
-
- }
-
- }
-
- async processObject( text, subobject, url, parentScope ) {
-
- const scope = this;
- const parseScope = this.newParseScopeLevel( null, parentScope );
- parseScope.url = url;
- const parentParseScope = parseScope.parentScope; // Set current matrix
-
- if ( subobject ) {
-
- parseScope.currentMatrix.multiplyMatrices( parentParseScope.currentMatrix, subobject.matrix );
- parseScope.matrix.copy( subobject.matrix );
- parseScope.inverted = subobject.inverted;
- parseScope.startingConstructionStep = subobject.startingConstructionStep;
- parseScope.mainColourCode = subobject.material.userData.code;
- parseScope.mainEdgeColourCode = subobject.material.userData.edgeMaterial.userData.code;
- parseScope.fileName = subobject.fileName;
-
- } // Parse the object
-
-
- this.objectParse( text, parseScope );
- const subobjects = parseScope.subobjects;
- const promises = [];
-
- for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
-
- promises.push( loadSubobject( parseScope.subobjects[ i ] ) );
-
- } // Kick off of the downloads in parallel but process all the subobjects
- // in order so all the assembly instructions are correct
-
-
- const subobjectScopes = await Promise.all( promises );
-
- for ( let i = 0, l = subobjectScopes.length; i < l; i ++ ) {
-
- this.finalizeObject( subobjectScopes[ i ] );
-
- } // If it is root object then finalize this object and compute construction steps
-
-
- if ( ! parentParseScope.isFromParse ) {
-
- this.finalizeObject( parseScope );
- this.computeConstructionSteps( parseScope.groupObject );
-
- }
-
- return parseScope;
-
- function loadSubobject( subobject ) {
-
- return scope.cache.loadData( subobject.fileName ).then( function ( text ) {
-
- return scope.processObject( text, subobject, url, parseScope );
-
- } ).catch( function () {
-
- console.warn( 'LDrawLoader: Subobject "' + subobject.fileName + '" could not be found.' );
- return null;
-
- } );
-
- }
-
- }
-
}
THREE.LDrawLoader = LDrawLoader;

examples/js/loaders/LUT3dlLoader.js

@@ -54,7 +54,7 @@
}
- const dataArray = new Array( size * size * size * 3 );
+ const dataArray = new Array( size * size * size * 4 );
let index = 0;
let maxOutputValue = 0.0;
@@ -71,22 +71,29 @@
const rLayer = Math.floor( index / ( size * size ) ) % size; // b grows first, then g, then r
const pixelIndex = bLayer * size * size + gLayer * size + rLayer;
- dataArray[ 3 * pixelIndex + 0 ] = r;
- dataArray[ 3 * pixelIndex + 1 ] = g;
- dataArray[ 3 * pixelIndex + 2 ] = b;
+ dataArray[ 4 * pixelIndex + 0 ] = r;
+ dataArray[ 4 * pixelIndex + 1 ] = g;
+ dataArray[ 4 * pixelIndex + 2 ] = b;
+ dataArray[ 4 * pixelIndex + 3 ] = 1.0;
index += 1;
- } // Find the apparent bit depth of the stored RGB values and scale the
+ } // Find the apparent bit depth of the stored RGB values and map the
// values to [ 0, 255 ].
const bits = Math.ceil( Math.log2( maxOutputValue ) );
const maxBitValue = Math.pow( 2.0, bits );
- for ( let i = 0, l = dataArray.length; i < l; i ++ ) {
+ for ( let i = 0, l = dataArray.length; i < l; i += 4 ) {
- const val = dataArray[ i ];
- dataArray[ i ] = 255 * val / maxBitValue;
+ const r = dataArray[ i + 0 ];
+ const g = dataArray[ i + 1 ];
+ const b = dataArray[ i + 2 ];
+ dataArray[ i + 0 ] = 255 * r / maxBitValue; // r
+
+ dataArray[ i + 1 ] = 255 * g / maxBitValue; // g
+
+ dataArray[ i + 2 ] = 255 * b / maxBitValue; // b
}
@@ -95,7 +102,7 @@
texture.image.data = data;
texture.image.width = size;
texture.image.height = size * size;
- texture.format = THREE.RGBFormat;
+ texture.format = THREE.RGBAFormat;
texture.type = THREE.UnsignedByteType;
texture.magFilter = THREE.LinearFilter;
texture.minFilter = THREE.LinearFilter;
@@ -108,7 +115,7 @@
texture3D.image.width = size;
texture3D.image.height = size;
texture3D.image.depth = size;
- texture3D.format = THREE.RGBFormat;
+ texture3D.format = THREE.RGBAFormat;
texture3D.type = THREE.UnsignedByteType;
texture3D.magFilter = THREE.LinearFilter;
texture3D.minFilter = THREE.LinearFilter;

examples/js/loaders/LUTCubeLoader.js

@@ -62,7 +62,7 @@
// more precision than can be captured with Uint8Array.
const sizeToken = split[ 1 ];
size = parseFloat( sizeToken );
- data = new Uint8Array( size * size * size * 3 );
+ data = new Uint8Array( size * size * size * 4 );
break;
case 'DOMAIN_MIN':
@@ -91,7 +91,8 @@
data[ currIndex + 0 ] = r * 255;
data[ currIndex + 1 ] = g * 255;
data[ currIndex + 2 ] = b * 255;
- currIndex += 3;
+ data[ currIndex + 3 ] = 255;
+ currIndex += 4;
}
@@ -101,7 +102,6 @@
texture.image.data = data;
texture.image.width = size;
texture.image.height = size * size;
- texture.format = THREE.RGBFormat;
texture.type = THREE.UnsignedByteType;
texture.magFilter = THREE.LinearFilter;
texture.minFilter = THREE.LinearFilter;
@@ -114,7 +114,6 @@
texture3D.image.width = size;
texture3D.image.height = size;
texture3D.image.depth = size;
- texture3D.format = THREE.RGBFormat;
texture3D.type = THREE.UnsignedByteType;
texture3D.magFilter = THREE.LinearFilter;
texture3D.minFilter = THREE.LinearFilter;

examples/js/loaders/MD2Loader.js

@@ -114,7 +114,7 @@
for ( let j = 0; j < 16; j ++ ) {
- const character = data.getUint8( offset + j, true );
+ const character = data.getUint8( offset + j );
if ( character === 0 ) break;
string[ j ] = character;
@@ -129,11 +129,11 @@
for ( let j = 0; j < header.num_vertices; j ++ ) {
- let x = data.getUint8( offset ++, true );
- let y = data.getUint8( offset ++, true );
- let z = data.getUint8( offset ++, true );
+ let x = data.getUint8( offset ++ );
+ let y = data.getUint8( offset ++ );
+ let z = data.getUint8( offset ++ );
- const n = _normalData[ data.getUint8( offset ++, true ) ];
+ const n = _normalData[ data.getUint8( offset ++ ) ];
x = x * scale.x + translation.x;
y = y * scale.y + translation.y;

examples/js/loaders/MTLLoader.js

@@ -327,6 +327,13 @@
map.offset.copy( texParams.offset );
map.wrapS = scope.wrap;
map.wrapT = scope.wrap;
+
+ if ( mapType === 'map' || mapType === 'emissiveMap' ) {
+
+ map.encoding = THREE.sRGBEncoding;
+
+ }
+
params[ mapType ] = map;
}
@@ -342,17 +349,17 @@
// Ns is material specular exponent
case 'kd':
// Diffuse color (color under white light) using RGB values
- params.color = new THREE.Color().fromArray( value );
+ params.color = new THREE.Color().fromArray( value ).convertSRGBToLinear();
break;
case 'ks':
// Specular color (color when light is reflected from shiny surface) using RGB values
- params.specular = new THREE.Color().fromArray( value );
+ params.specular = new THREE.Color().fromArray( value ).convertSRGBToLinear();
break;
case 'ke':
// Emissive using RGB values
- params.emissive = new THREE.Color().fromArray( value );
+ params.emissive = new THREE.Color().fromArray( value ).convertSRGBToLinear();
break;
case 'map_kd':

examples/js/loaders/PCDLoader.js

@@ -262,9 +262,9 @@
if ( offset.rgb !== undefined ) {
- color.push( dataview.getUint8( PCDheader.points * offset.rgb + PCDheader.size[ 3 ] * i + 0 ) / 255.0 );
- color.push( dataview.getUint8( PCDheader.points * offset.rgb + PCDheader.size[ 3 ] * i + 1 ) / 255.0 );
color.push( dataview.getUint8( PCDheader.points * offset.rgb + PCDheader.size[ 3 ] * i + 2 ) / 255.0 );
+ color.push( dataview.getUint8( PCDheader.points * offset.rgb + PCDheader.size[ 3 ] * i + 1 ) / 255.0 );
+ color.push( dataview.getUint8( PCDheader.points * offset.rgb + PCDheader.size[ 3 ] * i + 0 ) / 255.0 );
}

examples/js/loaders/RGBELoader.js

@@ -343,6 +343,7 @@
destArray[ destOffset + 0 ] = sourceArray[ sourceOffset + 0 ] * scale;
destArray[ destOffset + 1 ] = sourceArray[ sourceOffset + 1 ] * scale;
destArray[ destOffset + 2 ] = sourceArray[ sourceOffset + 2 ] * scale;
+ destArray[ destOffset + 3 ] = 1;
};
@@ -354,6 +355,7 @@
destArray[ destOffset + 0 ] = THREE.DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 0 ] * scale, 65504 ) );
destArray[ destOffset + 1 ] = THREE.DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 1 ] * scale, 65504 ) );
destArray[ destOffset + 2 ] = THREE.DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 2 ] * scale, 65504 ) );
+ destArray[ destOffset + 3 ] = THREE.DataUtils.toHalfFloat( 1 );
};
@@ -376,31 +378,29 @@
case THREE.FloatType:
numElements = image_rgba_data.length / 4;
- const floatArray = new Float32Array( numElements * 3 );
+ const floatArray = new Float32Array( numElements * 4 );
for ( let j = 0; j < numElements; j ++ ) {
- RGBEByteToRGBFloat( image_rgba_data, j * 4, floatArray, j * 3 );
+ RGBEByteToRGBFloat( image_rgba_data, j * 4, floatArray, j * 4 );
}
data = floatArray;
- format = THREE.RGBFormat;
type = THREE.FloatType;
break;
case THREE.HalfFloatType:
numElements = image_rgba_data.length / 4;
- const halfArray = new Uint16Array( numElements * 3 );
+ const halfArray = new Uint16Array( numElements * 4 );
for ( let j = 0; j < numElements; j ++ ) {
- RGBEByteToRGBHalf( image_rgba_data, j * 4, halfArray, j * 3 );
+ RGBEByteToRGBHalf( image_rgba_data, j * 4, halfArray, j * 4 );
}
data = halfArray;
- format = THREE.RGBFormat;
type = THREE.HalfFloatType;
break;

examples/js/loaders/RGBMLoader.js

@@ -393,7 +393,7 @@
var mgck = [ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a ];
- for ( var i = 0; i < 8; i ++ ) if ( data[ i ] != mgck[ i ] ) throw 'The input is not a PNG file!';
+ for ( var i = 0; i < 8; i ++ ) if ( data[ i ] != mgck[ i ] ) throw new Error( 'The input is not a PNG file!' );
while ( offset < data.length ) {

examples/js/loaders/STLLoader.js

@@ -134,7 +134,7 @@
// Check if each byte in query matches the corresponding byte from the current offset
for ( let i = 0, il = query.length; i < il; i ++ ) {
- if ( query[ i ] !== reader.getUint8( offset + i, false ) ) return false;
+ if ( query[ i ] !== reader.getUint8( offset + i ) ) return false;
}

examples/js/loaders/SVGLoader.js

@@ -110,7 +110,8 @@
case 'use':
style = parseStyle( node, style );
- const usedNodeId = node.href.baseVal.substring( 1 );
+ const href = node.getAttributeNS( 'http://www.w3.org/1999/xlink', 'href' ) || '';
+ const usedNodeId = href.substring( 1 );
const usedNode = node.viewportElement.getElementById( usedNodeId );
if ( usedNode ) {
@@ -560,7 +561,9 @@
for ( let j = 0; j < selectorList.length; j ++ ) {
- stylesheets[ selectorList[ j ] ] = Object.assign( stylesheets[ selectorList[ j ] ] || {}, stylesheet.style );
+ // Remove empty rules
+ const definitions = Object.fromEntries( Object.entries( stylesheet.style ).filter( ( [ , v ] ) => v !== '' ) );
+ stylesheets[ selectorList[ j ] ] = Object.assign( stylesheets[ selectorList[ j ] ] || {}, definitions );
}

examples/js/loaders/VRMLLoader.js

@@ -1166,6 +1166,7 @@
color.r = value;
color.g = value;
color.b = value;
+ color.a = 1;
break;
case TEXTURE_TYPE.INTENSITY_ALPHA:
@@ -1182,6 +1183,7 @@
color.r = parseInt( '0x' + hex.substring( 2, 4 ) );
color.g = parseInt( '0x' + hex.substring( 4, 6 ) );
color.b = parseInt( '0x' + hex.substring( 6, 8 ) );
+ color.a = 1;
break;
case TEXTURE_TYPE.RGBA:
@@ -1247,10 +1249,8 @@
const width = fieldValues[ 0 ];
const height = fieldValues[ 1 ];
const num_components = fieldValues[ 2 ];
- const useAlpha = num_components === 2 || num_components === 4;
const textureType = getTextureType( num_components );
- const size = ( useAlpha === true ? 4 : 3 ) * ( width * height );
- const data = new Uint8Array( size );
+ const data = new Uint8Array( 4 * width * height );
const color = {
r: 0,
g: 0,
@@ -1261,27 +1261,15 @@
for ( let j = 3, k = 0, jl = fieldValues.length; j < jl; j ++, k ++ ) {
parseHexColor( fieldValues[ j ], textureType, color );
-
- if ( useAlpha === true ) {
-
const stride = k * 4;
data[ stride + 0 ] = color.r;
data[ stride + 1 ] = color.g;
data[ stride + 2 ] = color.b;
data[ stride + 3 ] = color.a;
- } else {
-
- const stride = k * 3;
- data[ stride + 0 ] = color.r;
- data[ stride + 1 ] = color.g;
- data[ stride + 2 ] = color.b;
-
- }
-
}
- texture = new THREE.DataTexture( data, width, height, useAlpha === true ? THREE.RGBAFormat : THREE.RGBFormat );
+ texture = new THREE.DataTexture( data, width, height );
texture.needsUpdate = true;
texture.__type = textureType; // needed for material modifications

examples/js/math/ConvexHull.js

@@ -44,17 +44,8 @@
setFromPoints( points ) {
- if ( Array.isArray( points ) !== true ) {
-
- console.error( 'THREE.ConvexHull: Points parameter is not an array.' );
-
- }
-
- if ( points.length < 4 ) {
-
- console.error( 'THREE.ConvexHull: The algorithm needs at least four points.' );
-
- }
+ // The algorithm needs at least four points.
+ if ( points.length >= 4 ) {
this.makeEmpty();
@@ -65,6 +56,9 @@
}
this.compute();
+
+ }
+
return this;
}

examples/js/misc/Volume.js

@@ -104,7 +104,7 @@
case 'unsigned long long int':
case 'uint64':
case 'uint64_t':
- throw 'Error in Volume constructor : this type is not supported in JavaScript';
+ throw new Error( 'Error in Volume constructor : this type is not supported in JavaScript' );
break;
case 'Float32':
@@ -126,7 +126,7 @@
if ( this.data.length !== this.xLength * this.yLength * this.zLength ) {
- throw 'Error in Volume constructor, lengths are not matching arrayBuffer size';
+ throw new Error( 'Error in Volume constructor, lengths are not matching arrayBuffer size' );
}

examples/js/modifiers/CurveModifier.js

@@ -1,7 +1,7 @@
( function () {
// Original src: https://github.com/zz85/threejs-path-flow
- const BITS = 3;
+ const CHANNELS = 4;
const TEXTURE_WIDTH = 1024;
const TEXTURE_HEIGHT = 4;
/**
@@ -12,8 +12,8 @@
function initSplineTexture( numberOfCurves = 1 ) {
- const dataArray = new Float32Array( TEXTURE_WIDTH * TEXTURE_HEIGHT * numberOfCurves * BITS );
- const dataTexture = new THREE.DataTexture( dataArray, TEXTURE_WIDTH, TEXTURE_HEIGHT * numberOfCurves, THREE.RGBFormat, THREE.FloatType );
+ const dataArray = new Float32Array( TEXTURE_WIDTH * TEXTURE_HEIGHT * numberOfCurves * CHANNELS );
+ const dataTexture = new THREE.DataTexture( dataArray, TEXTURE_WIDTH, TEXTURE_HEIGHT * numberOfCurves, THREE.RGBAFormat, THREE.FloatType );
dataTexture.wrapS = THREE.RepeatWrapping;
dataTexture.wrapY = THREE.RepeatWrapping;
dataTexture.magFilter = THREE.NearestFilter;
@@ -62,11 +62,12 @@
const {
data
} = image;
- const i = BITS * TEXTURE_WIDTH * o; // Row Offset
+ const i = CHANNELS * TEXTURE_WIDTH * o; // Row Offset
- data[ index * BITS + i + 0 ] = x;
- data[ index * BITS + i + 1 ] = y;
- data[ index * BITS + i + 2 ] = z;
+ data[ index * CHANNELS + i + 0 ] = x;
+ data[ index * CHANNELS + i + 1 ] = y;
+ data[ index * CHANNELS + i + 2 ] = z;
+ data[ index * CHANNELS + i + 3 ] = 1;
}
/**

examples/js/modifiers/EdgeSplitModifier.js

@@ -166,12 +166,6 @@
if ( geometry.index == null ) {
- if ( THREE.BufferGeometryUtils === undefined ) {
-
- throw 'THREE.EdgeSplitModifier relies on THREE.BufferGeometryUtils';
-
- }
-
geometry = THREE.BufferGeometryUtils.mergeVertices( geometry );
}

examples/js/modifiers/SimplifyModifier.js

@@ -13,16 +13,6 @@
class SimplifyModifier {
- constructor() {
-
- if ( THREE.BufferGeometryUtils === undefined ) {
-
- throw 'THREE.SimplifyModifier relies on THREE.BufferGeometryUtils';
-
- }
-
- }
-
modify( geometry, count ) {
if ( geometry.isGeometry === true ) {

examples/js/objects/Lensflare.js

@@ -15,8 +15,8 @@
const positionScreen = new THREE.Vector3();
const positionView = new THREE.Vector3(); // textures
- const tempMap = new THREE.FramebufferTexture( 16, 16, THREE.RGBFormat );
- const occlusionMap = new THREE.FramebufferTexture( 16, 16, THREE.RGBFormat ); // material
+ const tempMap = new THREE.FramebufferTexture( 16, 16, THREE.RGBAFormat );
+ const occlusionMap = new THREE.FramebufferTexture( 16, 16, THREE.RGBAFormat ); // material
const geometry = Lensflare.Geometry;
const material1a = new THREE.RawShaderMaterial( {

examples/js/objects/ReflectorForSSRPass.js

@@ -79,19 +79,9 @@
}
const parameters = {
- minFilter: THREE.LinearFilter,
- magFilter: THREE.LinearFilter,
- format: THREE.RGBFormat,
depthTexture: useDepthTexture ? depthTexture : null
};
const renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight, parameters );
-
- if ( ! THREE.MathUtils.isPowerOfTwo( textureWidth ) || ! THREE.MathUtils.isPowerOfTwo( textureHeight ) ) {
-
- renderTarget.texture.generateMipmaps = false;
-
- }
-
const material = new THREE.ShaderMaterial( {
transparent: useDepthTexture,
defines: Object.assign( {}, ReflectorForSSRPass.ReflectorShader.defines, {

examples/js/objects/Reflector.js

@@ -25,19 +25,7 @@
const q = new THREE.Vector4();
const textureMatrix = new THREE.Matrix4();
const virtualCamera = new THREE.PerspectiveCamera();
- const parameters = {
- minFilter: THREE.LinearFilter,
- magFilter: THREE.LinearFilter,
- format: THREE.RGBFormat
- };
- const renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight, parameters );
-
- if ( ! THREE.MathUtils.isPowerOfTwo( textureWidth ) || ! THREE.MathUtils.isPowerOfTwo( textureHeight ) ) {
-
- renderTarget.texture.generateMipmaps = false;
-
- }
-
+ const renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight );
const material = new THREE.ShaderMaterial( {
uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
fragmentShader: shader.fragmentShader,

examples/js/objects/Refractor.js

@@ -20,19 +20,7 @@
const refractorPlane = new THREE.Plane();
const textureMatrix = new THREE.Matrix4(); // render target
- const parameters = {
- minFilter: THREE.LinearFilter,
- magFilter: THREE.LinearFilter,
- format: THREE.RGBFormat
- };
- const renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight, parameters );
-
- if ( ! THREE.MathUtils.isPowerOfTwo( textureWidth ) || ! THREE.MathUtils.isPowerOfTwo( textureHeight ) ) {
-
- renderTarget.texture.generateMipmaps = false;
-
- } // material
-
+ const renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight ); // material
this.material = new THREE.ShaderMaterial( {
uniforms: THREE.UniformsUtils.clone( shader.uniforms ),

examples/js/objects/Water.js

@@ -39,19 +39,7 @@
const q = new THREE.Vector4();
const textureMatrix = new THREE.Matrix4();
const mirrorCamera = new THREE.PerspectiveCamera();
- const parameters = {
- minFilter: THREE.LinearFilter,
- magFilter: THREE.LinearFilter,
- format: THREE.RGBFormat
- };
- const renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight, parameters );
-
- if ( ! THREE.MathUtils.isPowerOfTwo( textureWidth ) || ! THREE.MathUtils.isPowerOfTwo( textureHeight ) ) {
-
- renderTarget.texture.generateMipmaps = false;
-
- }
-
+ const renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight );
const mirrorShader = {
uniforms: THREE.UniformsUtils.merge( [ THREE.UniformsLib[ 'fog' ], THREE.UniformsLib[ 'lights' ], {
'normalSampler': {

examples/js/postprocessing/GlitchPass.js

@@ -25,6 +25,7 @@
/*, deltaTime, maskActive */
) {
+ if ( renderer.capabilities.isWebGL2 === false ) this.uniforms[ 'tDisp' ].value.format = THREE.LuminanceFormat;
this.uniforms[ 'tDiffuse' ].value = readBuffer.texture;
this.uniforms[ 'seed' ].value = Math.random(); //default seeding
@@ -81,19 +82,17 @@
generateHeightmap( dt_size ) {
- const data_arr = new Float32Array( dt_size * dt_size * 3 );
+ const data_arr = new Float32Array( dt_size * dt_size );
const length = dt_size * dt_size;
for ( let i = 0; i < length; i ++ ) {
const val = THREE.MathUtils.randFloat( 0, 1 );
- data_arr[ i * 3 + 0 ] = val;
- data_arr[ i * 3 + 1 ] = val;
- data_arr[ i * 3 + 2 ] = val;
+ data_arr[ i ] = val;
}
- const texture = new THREE.DataTexture( data_arr, dt_size, dt_size, THREE.RGBFormat, THREE.FloatType );
+ const texture = new THREE.DataTexture( data_arr, dt_size, dt_size, THREE.RedFormat, THREE.FloatType );
texture.needsUpdate = true;
return texture;

examples/js/postprocessing/OutlinePass.js

@@ -25,10 +25,6 @@
};
const resx = Math.round( this.resolution.x / this.downSampleRatio );
const resy = Math.round( this.resolution.y / this.downSampleRatio );
- this.maskBufferMaterial = new THREE.MeshBasicMaterial( {
- color: 0xffffff
- } );
- this.maskBufferMaterial.side = THREE.DoubleSide;
this.renderTargetMaskBuffer = new THREE.WebGLRenderTarget( this.resolution.x, this.resolution.y, pars );
this.renderTargetMaskBuffer.texture.name = 'OutlinePass.mask';
this.renderTargetMaskBuffer.texture.generateMipmaps = false;
@@ -93,7 +89,7 @@
function replaceDepthToViewZ( string, camera ) {
- var type = camera.isPerspectiveCamera ? 'perspective' : 'orthographic';
+ const type = camera.isPerspectiveCamera ? 'perspective' : 'orthographic';
return string.replace( /DEPTH_TO_VIEW_Z/g, type + 'DepthToViewZ' );
}

examples/js/postprocessing/SavePass.js

@@ -18,11 +18,7 @@
if ( this.renderTarget === undefined ) {
- this.renderTarget = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, {
- minFilter: THREE.LinearFilter,
- magFilter: THREE.LinearFilter,
- format: THREE.RGBFormat
- } );
+ this.renderTarget = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight );
this.renderTarget.texture.name = 'SavePass.rt';
}

examples/js/postprocessing/SMAAPass.js

@@ -7,17 +7,11 @@
super(); // render targets
this.edgesRT = new THREE.WebGLRenderTarget( width, height, {
- depthBuffer: false,
- generateMipmaps: false,
- minFilter: THREE.LinearFilter,
- format: THREE.RGBFormat
+ depthBuffer: false
} );
this.edgesRT.texture.name = 'SMAAPass.edges';
this.weightsRT = new THREE.WebGLRenderTarget( width, height, {
- depthBuffer: false,
- generateMipmaps: false,
- minFilter: THREE.LinearFilter,
- format: THREE.RGBAFormat
+ depthBuffer: false
} );
this.weightsRT.texture.name = 'SMAAPass.weights'; // textures
@@ -35,7 +29,6 @@
this.areaTexture = new THREE.Texture();
this.areaTexture.name = 'SMAAPass.area';
this.areaTexture.image = areaTextureImage;
- this.areaTexture.format = THREE.RGBFormat;
this.areaTexture.minFilter = THREE.LinearFilter;
this.areaTexture.generateMipmaps = false;
this.areaTexture.flipY = false;

examples/js/postprocessing/SSAOPass.js

@@ -23,25 +23,17 @@
this.generateRandomKernelRotations(); // beauty render target
const depthTexture = new THREE.DepthTexture();
- depthTexture.type = THREE.UnsignedShortType;
- this.beautyRenderTarget = new THREE.WebGLRenderTarget( this.width, this.height, {
- minFilter: THREE.LinearFilter,
- magFilter: THREE.LinearFilter,
- format: THREE.RGBAFormat
- } ); // normal render target with depth buffer
+ depthTexture.format = THREE.DepthStencilFormat;
+ depthTexture.type = THREE.UnsignedInt248Type;
+ this.beautyRenderTarget = new THREE.WebGLRenderTarget( this.width, this.height ); // normal render target with depth buffer
this.normalRenderTarget = new THREE.WebGLRenderTarget( this.width, this.height, {
minFilter: THREE.NearestFilter,
magFilter: THREE.NearestFilter,
- format: THREE.RGBAFormat,
depthTexture: depthTexture
} ); // ssao render target
- this.ssaoRenderTarget = new THREE.WebGLRenderTarget( this.width, this.height, {
- minFilter: THREE.LinearFilter,
- magFilter: THREE.LinearFilter,
- format: THREE.RGBAFormat
- } );
+ this.ssaoRenderTarget = new THREE.WebGLRenderTarget( this.width, this.height );
this.blurRenderTarget = this.ssaoRenderTarget.clone(); // ssao material
if ( THREE.SSAOShader === undefined ) {
@@ -131,7 +123,8 @@
/*, readBuffer, deltaTime, maskActive */
) {
- // render beauty
+ if ( renderer.capabilities.isWebGL2 === false ) this.noiseTexture.format = THREE.LuminanceFormat; // render beauty
+
renderer.setRenderTarget( this.beautyRenderTarget );
renderer.clear();
renderer.render( this.scene, this.camera ); // render normals and depth (honor only meshes, points and lines do not contribute to SSAO)
@@ -297,23 +290,18 @@
const simplex = new THREE.SimplexNoise();
const size = width * height;
- const data = new Float32Array( size * 4 );
+ const data = new Float32Array( size );
for ( let i = 0; i < size; i ++ ) {
- const stride = i * 4;
const x = Math.random() * 2 - 1;
const y = Math.random() * 2 - 1;
const z = 0;
- const noise = simplex.noise3d( x, y, z );
- data[ stride ] = noise;
- data[ stride + 1 ] = noise;
- data[ stride + 2 ] = noise;
- data[ stride + 3 ] = 1;
+ data[ i ] = simplex.noise3d( x, y, z );
}
- this.noiseTexture = new THREE.DataTexture( data, width, height, THREE.RGBAFormat, THREE.FloatType );
+ this.noiseTexture = new THREE.DataTexture( data, width, height, THREE.RedFormat, THREE.FloatType );
this.noiseTexture.wrapS = THREE.RepeatWrapping;
this.noiseTexture.wrapT = THREE.RepeatWrapping;
this.noiseTexture.needsUpdate = true;

examples/js/renderers/CSS2DRenderer.js

@@ -102,6 +102,11 @@
if ( object.isCSS2DObject ) {
+ const visible = object.visible && _vector.z >= - 1 && _vector.z <= 1 && object.layers.test( camera.layers );
+ object.element.style.display = visible ? '' : 'none';
+
+ if ( visible ) {
+
object.onBeforeRender( _this, scene, camera );
_vector.setFromMatrixPosition( object.matrixWorld );
@@ -121,7 +126,6 @@
}
- element.style.display = object.visible && _vector.z >= - 1 && _vector.z <= 1 ? '' : 'none';
const objectData = {
distanceToCameraSquared: getDistanceToSquared( camera, object )
};
@@ -137,6 +141,8 @@
}
+ }
+
for ( let i = 0, l = object.children.length; i < l; i ++ ) {
renderObject( object.children[ i ], scene, camera );

examples/js/renderers/CSS3DRenderer.js

@@ -181,6 +181,11 @@
if ( object.isCSS3DObject ) {
+ const visible = object.visible && object.layers.test( camera.layers );
+ object.element.style.display = visible ? '' : 'none'; // only getObjectCSSMatrix when object.visible
+
+ if ( visible ) {
+
object.onBeforeRender( _this, scene, camera );
let style;
@@ -223,8 +228,6 @@
}
- element.style.display = object.visible ? '' : 'none';
-
if ( element.parentNode !== cameraElement ) {
cameraElement.appendChild( element );
@@ -235,6 +238,8 @@
}
+ }
+
for ( let i = 0, l = object.children.length; i < l; i ++ ) {
renderObject( object.children[ i ], scene, camera, cameraCSSMatrix );

examples/js/shaders/DigitalGlitch.js

@@ -90,7 +90,7 @@
float xs = floor(gl_FragCoord.x / 0.5);
float ys = floor(gl_FragCoord.y / 0.5);
//based on staffantans glitch shader for unity https://github.com/staffantan/unityglitch
- vec4 normal = texture2D (tDisp, p*seed*seed);
+ float disp = texture2D(tDisp, p*seed*seed).r;
if(p.y<distortion_x+col_s && p.y>distortion_x-col_s*seed) {
if(seed_x>0.){
p.y = 1. - (p.y + distortion_y);
@@ -107,8 +107,8 @@
p.x = 1. - (p.x + distortion_x);
}
}
- p.x+=normal.x*seed_x*(seed/5.);
- p.y+=normal.y*seed_y*(seed/5.);
+ p.x+=disp*seed_x*(seed/5.);
+ p.y+=disp*seed_y*(seed/5.);
//base from RGB shift shader
vec2 offset = amount * vec2( cos(angle), sin(angle));
vec4 cr = texture2D(tDiffuse, p + offset);

examples/js/shaders/MMDToonShader.js

@@ -55,7 +55,6 @@
vec3 y = cross( viewDir, x );
vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; // 0.495 to remove artifacts caused by undersized matcap disks
vec4 matcapColor = texture2D( matcap, uv );
- matcapColor = matcapTexelToLinear( matcapColor );
#ifdef MATCAP_BLENDING_MULTIPLY

examples/js/shaders/SSAOShader.js

@@ -155,7 +155,7 @@
vec3 viewNormal = getViewNormal( vUv );
vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 );
- vec3 random = texture2D( tNoise, vUv * noiseScale ).xyz;
+ vec3 random = vec3( texture2D( tNoise, vUv * noiseScale ).r );
// compute matrix used to reorient a kernel vector

examples/js/utils/LDrawUtils.js

@@ -0,0 +1,182 @@
+( function () {
+
+ class LDrawUtils {
+
+ static mergeObject( object ) {
+
+ // Merges geometries in object by materials and returns new object. Use on not indexed geometries.
+ // The object buffers reference the old object ones.
+ // Special treatment is done to the conditional lines generated by LDrawLoader.
+ function extractGroup( geometry, group, elementSize, isConditionalLine ) {
+
+ // Extracts a group from a geometry as a new geometry (with attribute buffers referencing original buffers)
+ const newGeometry = new THREE.BufferGeometry();
+ const originalPositions = geometry.getAttribute( 'position' ).array;
+ const originalNormals = elementSize === 3 ? geometry.getAttribute( 'normal' ).array : null;
+ const numVertsGroup = Math.min( group.count, Math.floor( originalPositions.length / 3 ) - group.start );
+ const vertStart = group.start * 3;
+ const vertEnd = ( group.start + numVertsGroup ) * 3;
+ const positions = originalPositions.subarray( vertStart, vertEnd );
+ const normals = originalNormals !== null ? originalNormals.subarray( vertStart, vertEnd ) : null;
+ newGeometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
+ if ( normals !== null ) newGeometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
+
+ if ( isConditionalLine ) {
+
+ const controlArray0 = geometry.getAttribute( 'control0' ).array.subarray( vertStart, vertEnd );
+ const controlArray1 = geometry.getAttribute( 'control1' ).array.subarray( vertStart, vertEnd );
+ const directionArray = geometry.getAttribute( 'direction' ).array.subarray( vertStart, vertEnd );
+ newGeometry.setAttribute( 'control0', new THREE.BufferAttribute( controlArray0, 3, false ) );
+ newGeometry.setAttribute( 'control1', new THREE.BufferAttribute( controlArray1, 3, false ) );
+ newGeometry.setAttribute( 'direction', new THREE.BufferAttribute( directionArray, 3, false ) );
+
+ }
+
+ return newGeometry;
+
+ }
+
+ function addGeometry( mat, geometry, geometries ) {
+
+ const geoms = geometries[ mat.uuid ];
+
+ if ( ! geoms ) {
+
+ geometries[ mat.uuid ] = {
+ mat: mat,
+ arr: [ geometry ]
+ };
+
+ } else {
+
+ geoms.arr.push( geometry );
+
+ }
+
+ }
+
+ function permuteAttribute( attribute, elemSize ) {
+
+ // Permutes first two vertices of each attribute element
+ if ( ! attribute ) return;
+ const verts = attribute.array;
+ const numVerts = Math.floor( verts.length / 3 );
+ let offset = 0;
+
+ for ( let i = 0; i < numVerts; i ++ ) {
+
+ const x = verts[ offset ];
+ const y = verts[ offset + 1 ];
+ const z = verts[ offset + 2 ];
+ verts[ offset ] = verts[ offset + 3 ];
+ verts[ offset + 1 ] = verts[ offset + 4 ];
+ verts[ offset + 2 ] = verts[ offset + 5 ];
+ verts[ offset + 3 ] = x;
+ verts[ offset + 4 ] = y;
+ verts[ offset + 5 ] = z;
+ offset += elemSize * 3;
+
+ }
+
+ } // Traverse the object hierarchy collecting geometries and transforming them to world space
+
+
+ const meshGeometries = {};
+ const linesGeometries = {};
+ const condLinesGeometries = {};
+ object.updateMatrixWorld( true );
+ const normalMatrix = new THREE.Matrix3();
+ object.traverse( c => {
+
+ if ( c.isMesh | c.isLineSegments ) {
+
+ const elemSize = c.isMesh ? 3 : 2;
+ const geometry = c.geometry.clone();
+ const matrixIsInverted = c.matrixWorld.determinant() < 0;
+
+ if ( matrixIsInverted ) {
+
+ permuteAttribute( geometry.attributes.position, elemSize );
+ permuteAttribute( geometry.attributes.normal, elemSize );
+
+ }
+
+ geometry.applyMatrix4( c.matrixWorld );
+
+ if ( c.isConditionalLine ) {
+
+ geometry.attributes.control0.applyMatrix4( c.matrixWorld );
+ geometry.attributes.control1.applyMatrix4( c.matrixWorld );
+ normalMatrix.getNormalMatrix( c.matrixWorld );
+ geometry.attributes.direction.applyNormalMatrix( normalMatrix );
+
+ }
+
+ const geometries = c.isMesh ? meshGeometries : c.isConditionalLine ? condLinesGeometries : linesGeometries;
+
+ if ( Array.isArray( c.material ) ) {
+
+ for ( const groupIndex in geometry.groups ) {
+
+ const group = geometry.groups[ groupIndex ];
+ const mat = c.material[ group.materialIndex ];
+ const newGeometry = extractGroup( geometry, group, elemSize, c.isConditionalLine );
+ addGeometry( mat, newGeometry, geometries );
+
+ }
+
+ } else {
+
+ addGeometry( c.material, geometry, geometries );
+
+ }
+
+ }
+
+ } ); // Create object with merged geometries
+
+ const mergedObject = new THREE.Group();
+ const meshMaterialsIds = Object.keys( meshGeometries );
+
+ for ( const i in meshMaterialsIds ) {
+
+ const meshGeometry = meshGeometries[ meshMaterialsIds[ i ] ];
+ const mergedGeometry = THREE.mergeBufferGeometries( meshGeometry.arr );
+ mergedObject.add( new THREE.Mesh( mergedGeometry, meshGeometry.mat ) );
+
+ }
+
+ const linesMaterialsIds = Object.keys( linesGeometries );
+
+ for ( const i in linesMaterialsIds ) {
+
+ const lineGeometry = linesGeometries[ linesMaterialsIds[ i ] ];
+ const mergedGeometry = THREE.mergeBufferGeometries( lineGeometry.arr );
+ mergedObject.add( new THREE.LineSegments( mergedGeometry, lineGeometry.mat ) );
+
+ }
+
+ const condLinesMaterialsIds = Object.keys( condLinesGeometries );
+
+ for ( const i in condLinesMaterialsIds ) {
+
+ const condLineGeometry = condLinesGeometries[ condLinesMaterialsIds[ i ] ];
+ const mergedGeometry = THREE.mergeBufferGeometries( condLineGeometry.arr );
+ const condLines = new THREE.LineSegments( mergedGeometry, condLineGeometry.mat );
+ condLines.isConditionalLine = true;
+ mergedObject.add( condLines );
+
+ }
+
+ mergedObject.userData.constructionStep = 0;
+ mergedObject.userData.numConstructionSteps = 1;
+ return mergedObject;
+
+ }
+
+ }
+
+ THREE.LDrawUtils = {};
+ THREE.LDrawUtils.LDrawUtils = LDrawUtils;
+
+} )();

examples/js/utils/RoughnessMipmapper.js

@@ -1,268 +0,0 @@
-( function () {
-
- /**
- * This class generates custom mipmaps for a roughness map by encoding the lost variation in the
- * normal map mip levels as increased roughness in the corresponding roughness mip levels. This
- * helps with rendering accuracy for MeshStandardMaterial, and also helps with anti-aliasing when
- * using PMREM. If the normal map is larger than the roughness map, the roughness map will be
- * enlarged to match the dimensions of the normal map.
- */
-
- const _mipmapMaterial = _getMipmapMaterial();
-
- const _mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), _mipmapMaterial );
-
- const _flatCamera = new THREE.OrthographicCamera( 0, 1, 0, 1, 0, 1 );
-
- let _tempTarget = null;
- let _renderer = null;
-
- class RoughnessMipmapper {
-
- constructor( renderer ) {
-
- _renderer = renderer;
-
- _renderer.compile( _mesh, _flatCamera );
-
- }
-
- generateMipmaps( material ) {
-
- if ( 'roughnessMap' in material === false ) return;
- const {
- roughnessMap,
- normalMap
- } = material;
- if ( roughnessMap === null || normalMap === null || ! roughnessMap.generateMipmaps || material.userData.roughnessUpdated ) return;
- material.userData.roughnessUpdated = true;
- let width = Math.max( roughnessMap.image.width, normalMap.image.width );
- let height = Math.max( roughnessMap.image.height, normalMap.image.height );
- if ( ! THREE.MathUtils.isPowerOfTwo( width ) || ! THREE.MathUtils.isPowerOfTwo( height ) ) return;
-
- const oldTarget = _renderer.getRenderTarget();
-
- const autoClear = _renderer.autoClear;
- _renderer.autoClear = false;
-
- if ( _tempTarget === null || _tempTarget.width !== width || _tempTarget.height !== height ) {
-
- if ( _tempTarget !== null ) _tempTarget.dispose();
- _tempTarget = new THREE.WebGLRenderTarget( width, height, {
- depthBuffer: false
- } );
- _tempTarget.scissorTest = true;
-
- }
-
- const newRoughnessTexture = new THREE.FramebufferTexture( width, height, roughnessMap.format );
- newRoughnessTexture.wrapS = roughnessMap.wrapS;
- newRoughnessTexture.wrapT = roughnessMap.wrapT;
- newRoughnessTexture.minFilter = roughnessMap.minFilter;
- newRoughnessTexture.magFilter = roughnessMap.magFilter;
- material.roughnessMap = newRoughnessTexture;
- if ( material.metalnessMap == roughnessMap ) material.metalnessMap = material.roughnessMap;
- if ( material.aoMap == roughnessMap ) material.aoMap = material.roughnessMap; // Copy UV transform parameters
-
- material.roughnessMap.offset.copy( roughnessMap.offset );
- material.roughnessMap.repeat.copy( roughnessMap.repeat );
- material.roughnessMap.center.copy( roughnessMap.center );
- material.roughnessMap.rotation = roughnessMap.rotation;
- material.roughnessMap.image = roughnessMap.image; // required for USDZExporter, see #22741
-
- material.roughnessMap.matrixAutoUpdate = roughnessMap.matrixAutoUpdate;
- material.roughnessMap.matrix.copy( roughnessMap.matrix );
- _mipmapMaterial.uniforms.roughnessMap.value = roughnessMap;
- _mipmapMaterial.uniforms.normalMap.value = normalMap;
- const position = new THREE.Vector2( 0, 0 );
- const texelSize = _mipmapMaterial.uniforms.texelSize.value;
-
- for ( let mip = 0; width >= 1 && height >= 1; ++ mip, width /= 2, height /= 2 ) {
-
- // Rendering to a mip level is not allowed in webGL1. Instead we must set
- // up a secondary texture to write the result to, then copy it back to the
- // proper mipmap level.
- texelSize.set( 1.0 / width, 1.0 / height );
- if ( mip == 0 ) texelSize.set( 0.0, 0.0 );
-
- _tempTarget.viewport.set( position.x, position.y, width, height );
-
- _tempTarget.scissor.set( position.x, position.y, width, height );
-
- _renderer.setRenderTarget( _tempTarget );
-
- _renderer.render( _mesh, _flatCamera );
-
- _renderer.copyFramebufferToTexture( position, material.roughnessMap, mip );
-
- _mipmapMaterial.uniforms.roughnessMap.value = material.roughnessMap;
-
- }
-
- roughnessMap.dispose();
-
- _renderer.setRenderTarget( oldTarget );
-
- _renderer.autoClear = autoClear;
-
- }
-
- dispose() {
-
- _mipmapMaterial.dispose();
-
- _mesh.geometry.dispose();
-
- if ( _tempTarget != null ) _tempTarget.dispose();
-
- }
-
- }
-
- function _getMipmapMaterial() {
-
- const shaderMaterial = new THREE.RawShaderMaterial( {
- uniforms: {
- roughnessMap: {
- value: null
- },
- normalMap: {
- value: null
- },
- texelSize: {
- value: new THREE.Vector2( 1, 1 )
- }
- },
- vertexShader:
- /* glsl */
- `
- precision mediump float;
- precision mediump int;
-
- attribute vec3 position;
- attribute vec2 uv;
-
- varying vec2 vUv;
-
- void main() {
-
- vUv = uv;
-
- gl_Position = vec4( position, 1.0 );
-
- }
- `,
- fragmentShader:
- /* glsl */
- `
- precision mediump float;
- precision mediump int;
-
- varying vec2 vUv;
-
- uniform sampler2D roughnessMap;
- uniform sampler2D normalMap;
- uniform vec2 texelSize;
-
- #define ENVMAP_TYPE_CUBE_UV
-
- vec4 envMapTexelToLinear( vec4 a ) { return a; }
-
- #include <cube_uv_reflection_fragment>
-
- float roughnessToVariance( float roughness ) {
-
- float variance = 0.0;
-
- if ( roughness >= r1 ) {
-
- variance = ( r0 - roughness ) * ( v1 - v0 ) / ( r0 - r1 ) + v0;
-
- } else if ( roughness >= r4 ) {
-
- variance = ( r1 - roughness ) * ( v4 - v1 ) / ( r1 - r4 ) + v1;
-
- } else if ( roughness >= r5 ) {
-
- variance = ( r4 - roughness ) * ( v5 - v4 ) / ( r4 - r5 ) + v4;
-
- } else {
-
- float roughness2 = roughness * roughness;
-
- variance = 1.79 * roughness2 * roughness2;
-
- }
-
- return variance;
-
- }
-
- float varianceToRoughness( float variance ) {
-
- float roughness = 0.0;
-
- if ( variance >= v1 ) {
-
- roughness = ( v0 - variance ) * ( r1 - r0 ) / ( v0 - v1 ) + r0;
-
- } else if ( variance >= v4 ) {
-
- roughness = ( v1 - variance ) * ( r4 - r1 ) / ( v1 - v4 ) + r1;
-
- } else if ( variance >= v5 ) {
-
- roughness = ( v4 - variance ) * ( r5 - r4 ) / ( v4 - v5 ) + r4;
-
- } else {
-
- roughness = pow( 0.559 * variance, 0.25 ); // 0.559 = 1.0 / 1.79
-
- }
-
- return roughness;
-
- }
-
- void main() {
-
- gl_FragColor = texture2D( roughnessMap, vUv, - 1.0 );
-
- if ( texelSize.x == 0.0 ) return;
-
- float roughness = gl_FragColor.g;
-
- float variance = roughnessToVariance( roughness );
-
- vec3 avgNormal;
-
- for ( float x = - 1.0; x < 2.0; x += 2.0 ) {
-
- for ( float y = - 1.0; y < 2.0; y += 2.0 ) {
-
- vec2 uv = vUv + vec2( x, y ) * 0.25 * texelSize;
-
- avgNormal += normalize( texture2D( normalMap, uv, - 1.0 ).xyz - 0.5 );
-
- }
-
- }
-
- variance += 1.0 - 0.25 * length( avgNormal );
-
- gl_FragColor.g = varianceToRoughness( variance );
-
- }
- `,
- blending: THREE.NoBlending,
- depthTest: false,
- depthWrite: false
- } );
- shaderMaterial.type = 'RoughnessMipmapper';
- return shaderMaterial;
-
- }
-
- THREE.RoughnessMipmapper = RoughnessMipmapper;
-
-} )();

examples/js/WebGL.js

@@ -1,90 +0,0 @@
-( function () {
-
- class WEBGL {
-
- static isWebGLAvailable() {
-
- try {
-
- const canvas = document.createElement( 'canvas' );
- return !! ( window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ) );
-
- } catch ( e ) {
-
- return false;
-
- }
-
- }
-
- static isWebGL2Available() {
-
- try {
-
- const canvas = document.createElement( 'canvas' );
- return !! ( window.WebGL2RenderingContext && canvas.getContext( 'webgl2' ) );
-
- } catch ( e ) {
-
- return false;
-
- }
-
- }
-
- static getWebGLErrorMessage() {
-
- return this.getErrorMessage( 1 );
-
- }
-
- static getWebGL2ErrorMessage() {
-
- return this.getErrorMessage( 2 );
-
- }
-
- static getErrorMessage( version ) {
-
- const names = {
- 1: 'WebGL',
- 2: 'WebGL 2'
- };
- const contexts = {
- 1: window.WebGLRenderingContext,
- 2: window.WebGL2RenderingContext
- };
- let message = 'Your $0 does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" style="color:#000">$1</a>';
- const element = document.createElement( 'div' );
- element.id = 'webglmessage';
- element.style.fontFamily = 'monospace';
- element.style.fontSize = '13px';
- element.style.fontWeight = 'normal';
- element.style.textAlign = 'center';
- element.style.background = '#fff';
- element.style.color = '#000';
- element.style.padding = '1.5em';
- element.style.width = '400px';
- element.style.margin = '5em auto 0';
-
- if ( contexts[ version ] ) {
-
- message = message.replace( '$0', 'graphics card' );
-
- } else {
-
- message = message.replace( '$0', 'browser' );
-
- }
-
- message = message.replace( '$1', names[ version ] );
- element.innerHTML = message;
- return element;
-
- }
-
- }
-
- THREE.WEBGL = WEBGL;
-
-} )();

examples/jsm/animation/MMDPhysics.js

@@ -894,7 +894,7 @@
return new Ammo.btCapsuleShape( p.width, p.height );
default:
- throw 'unknown shape type ' + p.shapeType;
+ throw new Error( 'unknown shape type ' + p.shapeType );
}

examples/jsm/cameras/CinematicCamera.js

@@ -1,10 +1,8 @@
import {
- LinearFilter,
Mesh,
OrthographicCamera,
PerspectiveCamera,
PlaneGeometry,
- RGBFormat,
Scene,
ShaderMaterial,
UniformsUtils,
@@ -125,9 +123,8 @@
this.postprocessing.scene.add( this.postprocessing.camera );
- const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBFormat };
- this.postprocessing.rtTextureDepth = new WebGLRenderTarget( window.innerWidth, window.innerHeight, pars );
- this.postprocessing.rtTextureColor = new WebGLRenderTarget( window.innerWidth, window.innerHeight, pars );
+ this.postprocessing.rtTextureDepth = new WebGLRenderTarget( window.innerWidth, window.innerHeight );
+ this.postprocessing.rtTextureColor = new WebGLRenderTarget( window.innerWidth, window.innerHeight );
const bokeh_shader = BokehShader;

examples/jsm/capabilities/WebGL.js

@@ -0,0 +1,91 @@
+class WebGL {
+
+ static isWebGLAvailable() {
+
+ try {
+
+ const canvas = document.createElement( 'canvas' );
+ return !! ( window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ) );
+
+ } catch ( e ) {
+
+ return false;
+
+ }
+
+ }
+
+ static isWebGL2Available() {
+
+ try {
+
+ const canvas = document.createElement( 'canvas' );
+ return !! ( window.WebGL2RenderingContext && canvas.getContext( 'webgl2' ) );
+
+ } catch ( e ) {
+
+ return false;
+
+ }
+
+ }
+
+ static getWebGLErrorMessage() {
+
+ return this.getErrorMessage( 1 );
+
+ }
+
+ static getWebGL2ErrorMessage() {
+
+ return this.getErrorMessage( 2 );
+
+ }
+
+ static getErrorMessage( version ) {
+
+ const names = {
+ 1: 'WebGL',
+ 2: 'WebGL 2'
+ };
+
+ const contexts = {
+ 1: window.WebGLRenderingContext,
+ 2: window.WebGL2RenderingContext
+ };
+
+ let message = 'Your $0 does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" style="color:#000">$1</a>';
+
+ const element = document.createElement( 'div' );
+ element.id = 'webglmessage';
+ element.style.fontFamily = 'monospace';
+ element.style.fontSize = '13px';
+ element.style.fontWeight = 'normal';
+ element.style.textAlign = 'center';
+ element.style.background = '#fff';
+ element.style.color = '#000';
+ element.style.padding = '1.5em';
+ element.style.width = '400px';
+ element.style.margin = '5em auto 0';
+
+ if ( contexts[ version ] ) {
+
+ message = message.replace( '$0', 'graphics card' );
+
+ } else {
+
+ message = message.replace( '$0', 'browser' );
+
+ }
+
+ message = message.replace( '$1', names[ version ] );
+
+ element.innerHTML = message;
+
+ return element;
+
+ }
+
+}
+
+export default WebGL;

examples/jsm/capabilities/WebGPU.js

@@ -0,0 +1,33 @@
+class WebGPU {
+
+ static isAvailable() {
+
+ return ( navigator.gpu !== undefined );
+
+ }
+
+ static getErrorMessage() {
+
+ const message = 'Your browser does not support <a href="https://gpuweb.github.io/gpuweb/" style="color:blue">WebGPU</a>';
+
+ const element = document.createElement( 'div' );
+ element.id = 'webgpumessage';
+ element.style.fontFamily = 'monospace';
+ element.style.fontSize = '13px';
+ element.style.fontWeight = 'normal';
+ element.style.textAlign = 'center';
+ element.style.background = '#fff';
+ element.style.color = '#000';
+ element.style.padding = '1.5em';
+ element.style.width = '400px';
+ element.style.margin = '5em auto 0';
+
+ element.innerHTML = message;
+
+ return element;
+
+ }
+
+}
+
+export default WebGPU;

examples/jsm/exporters/GLTFExporter.js

@@ -15,9 +15,9 @@
NearestMipmapNearestFilter,
PropertyBinding,
RGBAFormat,
- RGBFormat,
RepeatWrapping,
Scene,
+ Texture,
Vector3
} from 'three';
@@ -689,6 +689,79 @@
}
+ buildORMTexture( material ) {
+
+ const occlusion = material.aoMap?.image;
+ const roughness = material.roughnessMap?.image;
+ const metalness = material.metalnessMap?.image;
+
+ if ( occlusion === roughness && roughness === metalness ) return occlusion;
+
+ if ( occlusion || roughness || metalness ) {
+
+ const width = Math.max( occlusion?.width || 0, roughness?.width || 0, metalness?.width || 0 );
+ const height = Math.max( occlusion?.height || 0, roughness?.height || 0, metalness?.height || 0 );
+
+ const canvas = document.createElement( 'canvas' );
+ canvas.width = width;
+ canvas.height = height;
+
+ const context = canvas.getContext( '2d' );
+ context.fillStyle = '#ffffff';
+ context.fillRect( 0, 0, width, height );
+
+ const composite = context.getImageData( 0, 0, width, height );
+
+ if ( occlusion ) {
+
+ context.drawImage( occlusion, 0, 0, width, height );
+
+ const data = context.getImageData( 0, 0, width, height ).data;
+
+ for ( let i = 0; i < data.length; i += 4 ) {
+
+ composite.data[ i ] = data[ i ];
+
+ }
+
+ }
+
+ if ( roughness ) {
+
+ context.drawImage( roughness, 0, 0, width, height );
+
+ const data = context.getImageData( 0, 0, width, height ).data;
+
+ for ( let i = 1; i < data.length; i += 4 ) {
+
+ composite.data[ i ] = data[ i ];
+
+ }
+
+ }
+
+ if ( metalness ) {
+
+ context.drawImage( metalness, 0, 0, width, height );
+
+ const data = context.getImageData( 0, 0, width, height ).data;
+
+ for ( let i = 2; i < data.length; i += 4 ) {
+
+ composite.data[ i ] = data[ i ];
+
+ }
+
+ }
+
+ context.putImageData( composite, 0, 0 );
+
+ return new Texture( canvas );
+
+ }
+
+ }
+
/**
* Process a buffer to append to the default one.
* @param {ArrayBuffer} buffer
@@ -962,7 +1035,7 @@
/**
* Process image
* @param {Image} image to process
- * @param {Integer} format of the image (e.g. RGBFormat, RGBAFormat etc)
+ * @param {Integer} format of the image (RGBAFormat)
* @param {Boolean} flipY before writing out the image
* @return {Integer} Index of the processed texture in the "images" array
*/
@@ -1011,9 +1084,9 @@
} else {
- if ( format !== RGBAFormat && format !== RGBFormat ) {
+ if ( format !== RGBAFormat ) {
- console.error( 'GLTFExporter: Only RGB and RGBA formats are supported.' );
+ console.error( 'GLTFExporter: Only RGBAFormat is supported.' );
}
@@ -1025,8 +1098,6 @@
const data = new Uint8ClampedArray( image.height * image.width * 4 );
- if ( format === RGBAFormat ) {
-
for ( let i = 0; i < data.length; i += 4 ) {
data[ i + 0 ] = image.data[ i + 0 ];
@@ -1036,19 +1107,6 @@
}
- } else {
-
- for ( let i = 0, j = 0; i < data.length; i += 4, j += 3 ) {
-
- data[ i + 0 ] = image.data[ j + 0 ];
- data[ i + 1 ] = image.data[ j + 1 ];
- data[ i + 2 ] = image.data[ j + 2 ];
- data[ i + 3 ] = 255;
-
- }
-
- }
-
ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
}
@@ -1194,21 +1252,15 @@
}
+ const ormTexture = this.buildORMTexture( material );
+
// pbrMetallicRoughness.metallicRoughnessTexture
if ( material.metalnessMap || material.roughnessMap ) {
- if ( material.metalnessMap === material.roughnessMap ) {
-
- const metalRoughMapDef = { index: this.processTexture( material.metalnessMap ) };
- this.applyTextureTransform( metalRoughMapDef, material.metalnessMap );
+ const metalRoughMapDef = { index: this.processTexture( ormTexture ) };
+ this.applyTextureTransform( metalRoughMapDef, material.metalnessMap || material.roughnessMap );
materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
- } else {
-
- console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
-
- }
-
}
// pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture
@@ -1273,7 +1325,7 @@
if ( material.aoMap ) {
const occlusionMapDef = {
- index: this.processTexture( material.aoMap ),
+ index: this.processTexture( ormTexture ),
texCoord: 1
};

examples/jsm/exporters/MMDExporter.js

@@ -186,7 +186,7 @@
if ( value === undefined ) {
- throw 'cannot convert charcode 0x' + code.toString( 16 );
+ throw new Error( 'cannot convert charcode 0x' + code.toString( 16 ) );
} else if ( value > 0xff ) {

examples/jsm/geometries/ConvexGeometry.js

@@ -6,7 +6,7 @@
class ConvexGeometry extends BufferGeometry {
- constructor( points ) {
+ constructor( points = [] ) {
super();

examples/jsm/geometries/TextGeometry.js

@@ -16,7 +16,6 @@
*/
import {
- BufferGeometry,
ExtrudeGeometry
} from 'three';
@@ -26,12 +25,11 @@
const font = parameters.font;
- if ( ! ( font && font.isFont ) ) {
+ if ( font === undefined ) {
- console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
- return new BufferGeometry();
+ super(); // generate default extrude geometry
- }
+ } else {
const shapes = font.generateShapes( text, parameters.size );
@@ -47,6 +45,8 @@
super( shapes, parameters );
+ }
+
this.type = 'TextGeometry';
}

examples/jsm/interactive/HTMLMesh.js

@@ -20,7 +20,7 @@
function onEvent( event ) {
- material.map.dispatchEvent( event );
+ material.map.dispatchDOMEvent( event );
}
@@ -29,6 +29,20 @@
this.addEventListener( 'mouseup', onEvent );
this.addEventListener( 'click', onEvent );
+ this.dispose = function () {
+
+ geometry.dispose();
+ material.dispose();
+
+ material.map.dispose();
+
+ this.removeEventListener( 'mousedown', onEvent );
+ this.removeEventListener( 'mousemove', onEvent );
+ this.removeEventListener( 'mouseup', onEvent );
+ this.removeEventListener( 'click', onEvent );
+
+ };
+
}
}
@@ -48,7 +62,7 @@
}
- dispatchEvent( event ) {
+ dispatchDOMEvent( event ) {
htmlevent( this.dom, event.type, event.data.x, event.data.y );

examples/jsm/libs/flow.module.js

@@ -16,7 +16,7 @@
}
-__flow__addCSS( `@keyframes f-animation-open { 0% { transform: scale(.5); opacity: 0; } 100% { transform: scale(1); opacity: 1; }}f-canvas,f-canvas canvas { position: absolute; top: 0; left: 0; margin: 0; padding: 0; width: 100%; height: 100%; -webkit-touch-callout: none; }f-canvas { overflow: auto; cursor: grab;}f-canvas canvas.front { z-index: 10;}body.dragging f-canvas,body.connecting f-canvas { overflow: hidden !important;}body.dragging *:not(.drag) { pointer-events: none !important;}f-canvas.grabbing * { cursor: grabbing; user-select: none;}f-canvas canvas { position: fixed; overflow: hidden; pointer-events: none;}f-canvas::-webkit-scrollbar { width: 8px; height: 8px;}f-canvas::-webkit-scrollbar-thumb:hover{ background: #014fc5;}f-canvas::-webkit-scrollbar-track { background: #363636;}f-canvas::-webkit-scrollbar-thumb { background-color: #666666; border-radius: 10px; border: 0;}f-canvas f-content,f-canvas f-area { position: absolute; display: block;}f-node { position: absolute; margin: 0; padding: 0; user-select: none; width: 320px; z-index: 1; cursor: auto; filter: drop-shadow(0 0 10px #00000061); backdrop-filter: blur(4px);}f-node.selected { z-index: 2;}f-node.selected,f-canvas.dragging-rio f-node:hover,f-canvas.dragging-lio f-node:hover { filter: drop-shadow(0 0 10px #00000061) drop-shadow(0 0 8px #4444dd);}f-node.closed f-element:not(:first-child) { display: none;}f-node.center { top: 50%; left: 50%; transform: translate( -50%, -50% );}f-node.top-right { top: 0; right: 0;}f-node.top-center { top: 0; left: 50%; transform: translateX( -50% );}f-node.top-left { top: 0; left: 0;}f-node { transition: filter 0.2s ease;}f-node { animation: .2s f-animation-open 1 alternate ease-out;}f-drop,f-menu,f-menu button,f-element,f-element input,f-element select,f-element button,f-element textarea { font-family: 'Open Sans', sans-serif; font-size: 13px; text-transform: capitalize; color: #eeeeee; outline: solid 0px #000; letter-spacing: .2px; margin: 0; padding: 0; border: 0; user-select: none; -webkit-tap-highlight-color: transparent; transition: background 0.2s ease;}f-element input { transition: background 0.1s ease;}f-element input,f-element select,f-element button,f-element textarea { background-color: #242427;}f-element { position: relative; width: calc( 100% - 14px ); background: rgba(45, 45, 48, 0.95); pointer-events: auto; border-bottom: 2px solid #232323; display: flex; padding-left: 7px; padding-right: 7px; padding-top: 2px; padding-bottom: 2px;}f-element { height: 24px;}f-element input { margin-top: 2px; margin-bottom: 2px; box-shadow: inset 0px 1px 1px rgb(0 0 0 / 20%), 0px 1px 0px rgb(255 255 255 / 5%); margin-left: 2px; margin-right: 2px; width: 100%; padding-left: 4px; padding-right: 4px;}f-element input.number { cursor: col-resize;}f-element input:focus[type='text'], f-element input:focus[type='range'], f-element input:focus[type='color'] { background: rgba( 0, 0, 0, 0.6 ); outline: solid 1px rgba( 0, 80, 200, 0.98 );}f-element input[type='color'] { appearance: none; padding: 0; margin-left: 2px; margin-right: 2px; height: calc( 100% - 4px ); margin-top: 2px; border: none; }f-element input[type='color']::-webkit-color-swatch-wrapper { padding: 2px;}f-element input[type='color']::-webkit-color-swatch { border: none; cursor: alias;}f-element input[type='range'] { appearance: none; width: 100%; overflow: hidden; padding: 0; cursor: ew-resize;}f-element input[type='range']::-webkit-slider-runnable-track { appearance: none; height: 10px; color: #13bba4; margin: 0;}f-element input[type='range']::-webkit-slider-thumb { appearance: none; width: 0; background: #434343; box-shadow: -500px 0 0 500px rgba( 0, 120, 255, 0.98 ); border-radius: 50%; border: 0 !important;}f-element input[type='range']::-webkit-slider-runnable-track { margin-left: -4px; margin-right: -5px;}f-element input[type='checkbox'] { appearance: none; cursor: pointer;}f-element input[type='checkbox'].toggle { height: 20px; width: 45px; border-radius: 16px; display: inline-block; position: relative; margin: 0; margin-top: 2px; background: linear-gradient( 0deg, #292929 0%, #0a0a0ac2 100% ); transition: all 0.2s ease;}f-element input[type='checkbox'].toggle:after { content: ""; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%; background: white; box-shadow: 0 1px 2px rgba(44, 44, 44, 0.2); transition: all 0.2s cubic-bezier(0.5, 0.1, 0.75, 1.35);}f-element input[type='checkbox'].toggle:checked { background: linear-gradient( 0deg, #0177fb 0%, #0177fb 100% );}f-element input[type='checkbox'].toggle:checked:after { transform: translatex(25px);}f-element.auto-height { display: table;}f-element textarea { width: calc( 100% - 18px ); padding-top: 1px; padding-bottom: 3px; padding-left: 3px; padding-right: 8px; margin-top: 2px; margin-left: 2px; height: calc( 100% - 8px ); max-height: 300px; border-radius: 2px; resize: none; box-shadow: inset 0px 1px 1px rgb(0 0 0 / 20%), 0px 1px 0px rgb(255 255 255 / 5%);}f-element.auto-height textarea { resize: auto;}f-element select { width: 100%; margin-top: 2px; margin-bottom: 2px; margin-left: 2px; margin-right: 2px; padding-left: 5px; cursor: pointer; box-shadow: inset 0px 1px 1px rgb(0 0 0 / 20%), 0px 1px 0px rgb(255 255 255 / 5%);}f-element f-toolbar { position: absolute; display: flex; top: 0; width: 100%; height: 100%; align-content: space-around;}f-element.output-right f-toolbar { right: 7px; float: right; justify-content: end;}f-element f-toolbar { margin-top: auto; margin-bottom: auto; margin-left: 3px; margin-right: 3px; font-size: 18px; line-height: 18px;}f-element f-toolbar button { opacity: .7; cursor: pointer; font-size: 14px; width: unset; height: unset; border-radius: unset; border: unset; outline: 0; background-color: unset; box-shadow: unset;}f-element f-toolbar button:hover,f-element f-toolbar button:active { opacity: 1; border: 0; background-color: unset;}f-element input.range-value { width: 60px; text-align: center;}f-menu.context button,f-element button { width: 100%; height: calc( 100% - 4px ); margin-left: 2px; margin-right: 2px; margin-top: 2px; border-radius: 3px; cursor: pointer;}f-element button { box-shadow: inset 1px 1px 1px 0 rgb(255 255 255 / 17%), inset -2px -2px 2px 0 rgb(0 0 0 / 26%);}f-element button:hover { color: #fff; background-color: #2a2a2a;}f-element button:active { border: 1px solid rgba( 0, 120, 255, 0.98 );}f-element f-inputs,f-element f-subinputs { display: flex; width: 100%;}f-element f-inputs { left: 100px; top: 50%; transform: translateY(-50%); position: absolute; width: calc( 100% - 106px ); height: calc( 100% - 4px ); z-index: 1;}f-element.inputs-disable f-inputs { filter: grayscale(100%); opacity: .5;}f-element.inputs-disable f-inputs input { pointer-events: none;}f-element f-label,f-element span { margin: auto; text-shadow: 1px 1px 0px #0007;}f-element f-label { padding-left: 4px; white-space: nowrap; position: absolute; top: 50%; transform: translateY(-50%); width: calc( 100% - 20px );}f-element.right f-label { text-align: right;}f-element f-label i { float: left; font-size: 18px; margin-right: 6px;}f-element f-label.center { width: 100%; text-align: center; display: block;}f-element.title { height: 29px; background-color: #3a3a3ab0; background-color: #3b3b43ed; cursor: all-scroll; border-top-left-radius: 6px; border-top-right-radius: 6px;}f-element.blue { background-color: #014fc5;}f-element.red { background-color: #bd0b0b;}f-element.green { background-color: #148d05;}f-element.yellow { background-color: #d6b100;}f-element.title.left { text-align: left; display: inline-grid; justify-content: start;}f-element.title span { text-align: center; font-size: 15px; padding-top: 2px;}f-element.title i { font-size: 18px; position: absolute; right: 10px; top: 50%; transform: translateY(-50%); opacity: .5;}f-element.output-right.title i { left: 10px; right: unset;}f-element.title.left span { text-align: left;}f-element f-io { border: 2px solid #dadada; width: 7px; height: 7px; position: absolute; background: #242427; border-radius: 8px; float: left; left: -7px; top: calc( 50% - 5px ); cursor: alias; box-shadow: 0 0 3px 2px #0000005e; z-index: 1;}f-element f-io.connect,f-canvas.dragging-rio f-element:hover f-io.lio,f-canvas.dragging-lio f-element:hover f-io.rio { border: 2px solid #0177fb; zoom: 1.4;}f-node.io-connect f-io:not(.connect) { border: 2px solid #dadada !important; zoom: 1 !important;}f-element f-io.rio { float: right; right: -7px; left: unset;}f-element f-disconnect { position: absolute; left: -35px; top: 50%; font-size: 22px; transform: translateY( -50% ); filter: drop-shadow(0 0 5px #000); text-shadow: 0px 0px 5px black; cursor: pointer;}f-element.output-right f-disconnect { right: -35px; left: unset;}f-element f-disconnect:hover { color: #ff3300;}f-element textarea::-webkit-scrollbar { width: 6px;}f-element textarea::-webkit-scrollbar-track { background: #111; } f-element textarea::-webkit-scrollbar-thumb { background: #0177fb; }f-element textarea::-webkit-scrollbar-thumb:hover { background: #1187ff; }f-element.small { height: 18px;}f-element.large { height: 36px;}body.connecting f-node:not(.io-connect) f-element:hover,f-element.select { background-color: rgba(61, 70, 82, 0.98);}f-drop { width: 100%; height: 100%; position: sticky; left: 0; top: 0; background: #02358417; text-align: center; justify-content: center; align-items: center; display: flex; box-shadow: inset 0 0 20px 10px #464ace17; pointer-events: none; transition: all .07s; opacity: 0; visibility: hidden;}f-drop.visible { visibility: unset; opacity: unset; transition: all .23s;}f-drop span { opacity: .5; font-size: 40px; text-shadow: 0px 0px 5px #000; font-weight: bold;}f-tooltip { pointer-events: none;}f-tooltip { position: absolute; left: 0; top: 0; background: rgba(0,0,0,.8); backdrop-filter: blur(4px); font-size: 14px; padding: 7px; border-radius: 10px; top: 50%; transform: translateY(-50%); visibility: hidden; pointer-events: none; opacity: 0; transition: all 0.3s ease; z-index: 150; white-space: nowrap;}f-menu.context { position: absolute; width: 170px; padding: 2px; margin: 0; background: #17171794; z-index: 110; font-size: 12px; border-radius: 6px; backdrop-filter: blur(6px); border: 1px solid #7e7e7e45; box-shadow: 3px 3px 6px rgba(0,0,0,.2); transition: opacity 0.2s ease, transform 0.1s ease;}f-menu.context.hidden { visibility: hidden; opacity: 0;}f-menu.context f-item { display: block; position: relative; margin: 0; padding: 0; white-space: nowrap;}f-menu.context f-item.submenu::after { content: ""; position: absolute; right: 6px; top: 50%; -webkit-transform: translateY(-50%); transform: translateY(-50%); border: 5px solid transparent; border-left-color: #808080;}f-menu.context f-item:hover > f-menu,f-menu.context f-item.active > f-menu { visibility: unset; transform: unset; opacity: unset;}f-menu.context f-menu { top: 0px; left: calc( 100% - 4px );}f-menu.context f-item button { overflow: visible; display: block; width: calc( 100% - 6px ); text-align: left; cursor: pointer; white-space: nowrap; padding: 6px 8px; border-radius: 3px; background: #2d2d32; border: 0; color: #ddd; margin: 3px; text-shadow: 1px 1px 0px #0007;}f-menu.context f-item button i { float: left; font-size: 16px;}f-menu.context f-item button span { margin-left: 6px;}f-menu.context f-item:hover > button,f-menu.context f-item.active > button { color: #fff; background: #313136;}f-menu.context f-item button:active { outline: solid 1px rgba( 0, 80, 200, 0.98 );}f-menu.context f-item f-tooltip { margin-left: 120px;}f-menu.circle { position: absolute; left: 30px; top: 30px; z-index: 100;}f-menu.circle f-item { display: flex; justify-content: end; align-content: space-around; margin-bottom: 12px;}f-menu.circle f-item button { width: 50px; height: 50px; font-size: 26px; background: #17171794; border-radius: 50%; backdrop-filter: blur(6px); border: 1px solid #7e7e7e45; line-height: 100%; cursor: pointer; box-shadow: 3px 3px 6px rgba(0,0,0,.2);}f-menu.circle f-item f-tooltip { margin-left: 50px;}.f-rounded f-node f-element,.f-rounded f-node f-element.title.left { border-radius: 10px 5px 10px 5px;}.f-rounded f-node f-element input, .f-rounded f-node f-element select,.f-rounded f-node f-element button,.f-rounded f-node f-element textarea,.f-rounded f-node f-element input[type='checkbox'].toggle,.f-rounded f-node f-element input[type='checkbox'].toggle:after { border-radius: 20px 10px;}.f-rounded f-node f-element input { padding-left: 7px; padding-right: 7px;}.f-rounded f-menu.context,.f-rounded f-menu.context f-item button { border-radius: 20px 10px;}@media (hover: hover) and (pointer: fine) { f-node:not(.selected):hover { filter: drop-shadow(0 0 6px #66666630); } f-element f-toolbar { visibility: hidden; opacity: 0; transition: opacity 0.2s ease; } f-node:hover > f-element f-toolbar { visibility: visible; opacity: 1; } f-element f-io:hover { border: 2px solid #0177fb; zoom: 1.4; } f-menu.circle f-item button:hover { background-color: #2a2a2a; } f-menu.circle f-item button:hover > f-tooltip, f-menu.context f-item button:hover > f-tooltip { visibility: visible; transform: translate(10px, -50%); opacity: 1; } f-menu.circle f-item button:focus > f-tooltip, f-menu.context f-item button:focus > f-tooltip { visibility: hidden; opacity: 0; }}f-canvas { will-change: top, left;}f-node { will-change: transform !important;}` );
+__flow__addCSS( `@keyframes f-animation-open { 0% { transform: scale(.5); opacity: 0; } 100% { transform: scale(1); opacity: 1; }}f-canvas,f-canvas canvas { position: absolute; top: 0; left: 0; margin: 0; padding: 0; width: 100%; height: 100%; -webkit-touch-callout: none; }f-canvas { overflow: auto; cursor: grab;}f-canvas canvas.front { z-index: 10;}body.dragging *:not(.drag) { pointer-events: none !important;}f-canvas.grabbing * { cursor: grabbing; user-select: none;}f-canvas canvas { position: fixed; overflow: hidden; pointer-events: none;}f-canvas::-webkit-scrollbar { width: 8px; height: 8px;}f-canvas::-webkit-scrollbar-thumb:hover{ background: #014fc5;}f-canvas::-webkit-scrollbar-track { background: #363636;}f-canvas::-webkit-scrollbar-thumb { background-color: #666666; border-radius: 10px; border: 0;}f-canvas f-content,f-canvas f-area { position: absolute; display: block;}f-node { position: absolute; margin: 0; padding: 0; user-select: none; width: 320px; z-index: 1; cursor: auto; filter: drop-shadow(0 0 10px #00000061); backdrop-filter: blur(4px);}f-node.selected { z-index: 2;}f-node.selected,f-canvas.dragging-rio f-node:hover,f-canvas.dragging-lio f-node:hover { filter: drop-shadow(0 0 10px #00000061) drop-shadow(0 0 8px #4444dd);}f-node.closed f-element:not(:first-child) { display: none;}f-node.center { top: 50%; left: 50%; transform: translate( -50%, -50% );}f-node.top-right { top: 0; right: 0;}f-node.top-center { top: 0; left: 50%; transform: translateX( -50% );}f-node.top-left { top: 0; left: 0;}f-node { transition: filter 0.2s ease;}f-node { animation: .2s f-animation-open 1 alternate ease-out;}f-tips,f-drop,f-menu,f-menu input,f-menu button,f-element,f-element input,f-element select,f-element button,f-element textarea { font-family: 'Open Sans', sans-serif; font-size: 13px; text-transform: capitalize; color: #eeeeee; outline: solid 0px #000; margin: 0; padding: 0; border: 0; user-select: none; -webkit-tap-highlight-color: transparent; transition: background 0.2s ease, filter 0.2s ease;}f-element input:read-only { color: #666;}f-element input,f-element textarea { text-transform: initial;}f-element input { transition: background 0.1s ease;}f-element input,f-element select,f-element button,f-element textarea { background-color: #232324d1;}f-element { position: relative; width: calc( 100% - 14px ); background: rgba(45, 45, 48, 0.95); pointer-events: auto; border-bottom: 2px solid #232323; display: flex; padding-left: 7px; padding-right: 7px; padding-top: 2px; padding-bottom: 2px;}f-element:after,f-element:before { transition: opacity .17s; opacity: 0; content: '';}f-element[tooltip]:hover:after,f-element[tooltip]:focus-within:after { font-size: 14px !important; display: flex; justify-content: center; position: fixed; margin-left: -7px; width: calc( 100% ); background: #1d1d1de8; border: 1px solid #444444a1; border-radius: 6px; color: #dadada; content: attr( tooltip ); margin-top: -41px; font-size: 16px; padding-top: 3px; padding-bottom: 3px; z-index: 10; opacity: 1; backdrop-filter: blur(4px); white-space: nowrap; overflow: hidden; text-shadow: 1px 1px 0px #0007;}f-element[tooltip]:hover:before,f-element[tooltip]:focus-within:before { border: solid; border-color: #1d1d1de8 transparent; border-width: 12px 6px 0 6px; left: calc( 50% - 6px ); bottom: 30px; position: absolute; opacity: 1; z-index: 11;}f-element[error] { background-color: #ff0000;}f-element[error]:hover:after,f-element[error]:focus-within:after { border: none; background-color: #ff0000bb; filter: drop-shadow( 2px 2px 5px #000 ); color: #fff;}f-element[error]:hover:before,f-element[error]:focus-within:before { border-color: #ff0000bb transparent;}f-element { height: 24px;}f-element input { margin-top: 2px; margin-bottom: 2px; box-shadow: inset 0px 1px 1px rgb(0 0 0 / 20%), 0px 1px 0px rgb(255 255 255 / 5%); margin-left: 2px; margin-right: 2px; width: 100%; padding-left: 4px; padding-right: 4px;}f-element input.number { cursor: col-resize;}f-element input:focus[type='text'], f-element input:focus[type='range'], f-element input:focus[type='color'] { background: rgba( 0, 0, 0, 0.6 ); outline: solid 1px rgba( 0, 80, 200, 0.98 );}f-element input[type='color'] { appearance: none; padding: 0; margin-left: 2px; margin-right: 2px; height: calc( 100% - 4px ); margin-top: 2px; border: none;}f-element input[type='color']::-webkit-color-swatch-wrapper { padding: 2px;}f-element input[type='color']::-webkit-color-swatch { border: none; cursor: alias;}f-element input[type='range'] { appearance: none; width: 100%; overflow: hidden; padding: 0; cursor: ew-resize;}f-element input[type='range']::-webkit-slider-runnable-track { appearance: none; height: 10px; color: #13bba4; margin: 0;}f-element input[type='range']::-webkit-slider-thumb { appearance: none; width: 0; background: #434343; box-shadow: -500px 0 0 500px rgba( 0, 120, 255, 0.98 ); border-radius: 50%; border: 0 !important;}f-element input[type='range']::-webkit-slider-runnable-track { margin-left: -4px; margin-right: -5px;}f-element input[type='checkbox'] { appearance: none; cursor: pointer;}f-element input[type='checkbox'].toggle { height: 20px; width: 45px; border-radius: 16px; display: inline-block; position: relative; margin: 0; margin-top: 2px; background: linear-gradient( 0deg, #292929 0%, #0a0a0ac2 100% ); transition: all 0.2s ease;}f-element input[type='checkbox'].toggle:after { content: ""; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%; background: white; box-shadow: 0 1px 2px rgba(44, 44, 44, 0.2); transition: all 0.2s cubic-bezier(0.5, 0.1, 0.75, 1.35);}f-element input[type='checkbox'].toggle:checked { background: linear-gradient( 0deg, #0177fb 0%, #0177fb 100% );}f-element input[type='checkbox'].toggle:checked:after { transform: translatex(25px);}f-element.auto-height { display: table;}f-element textarea { width: calc( 100% - 18px ); padding-top: 1px; padding-bottom: 3px; padding-left: 3px; padding-right: 8px; margin-top: 2px; margin-left: 2px; height: calc( 100% - 8px ); max-height: 300px; border-radius: 2px; resize: none; box-shadow: inset 0px 1px 1px rgb(0 0 0 / 20%), 0px 1px 0px rgb(255 255 255 / 5%);}f-element.auto-height textarea { resize: auto;}f-element select { width: 100%; margin-top: 2px; margin-bottom: 2px; margin-left: 2px; margin-right: 2px; cursor: pointer; box-shadow: inset 0px 1px 1px rgb(0 0 0 / 20%), 0px 1px 0px rgb(255 255 255 / 5%);}f-element f-toolbar { position: absolute; display: flex; top: 0; width: 100%; height: 100%; align-content: space-around;}f-element.input-right f-toolbar { right: 7px; float: right; justify-content: end;}f-element f-toolbar { margin-top: auto; margin-bottom: auto; margin-left: 3px; margin-right: 3px; font-size: 18px; line-height: 18px;}f-element f-toolbar button { opacity: .7; cursor: pointer; font-size: 14px; width: unset; height: unset; border-radius: unset; border: unset; outline: 0; background-color: unset; box-shadow: unset;}f-element f-toolbar button:hover,f-element f-toolbar button:active { opacity: 1; border: 0; background-color: unset;}f-element input.range-value { width: 60px; text-align: center;}f-menu.context button,f-element button { width: 100%; height: calc( 100% - 4px ); margin-left: 2px; margin-right: 2px; margin-top: 2px; border-radius: 3px; cursor: pointer;}f-element button { box-shadow: inset 1px 1px 1px 0 rgb(255 255 255 / 17%), inset -2px -2px 2px 0 rgb(0 0 0 / 26%);}f-element button:hover { color: #fff; background-color: #2a2a2a;}f-element button:active { border: 1px solid rgba( 0, 120, 255, 0.98 );}f-element f-inputs,f-element f-subinputs { display: flex; width: 100%;}f-element f-inputs { left: 100px; top: 50%; transform: translateY(-50%); position: absolute; width: calc( 100% - 106px ); height: calc( 100% - 4px ); z-index: 1;}f-element.inputs-disable f-inputs { filter: grayscale(100%); opacity: .5;}f-element.inputs-disable f-inputs input { pointer-events: none;}f-element f-label,f-element span { margin: auto; text-shadow: 1px 1px 0px #0007;}f-element f-label { padding-left: 4px; white-space: nowrap; position: absolute; top: 50%; transform: translateY(-50%); width: calc( 100% - 20px );}f-element.right f-label { text-align: right;}f-element.center f-label { text-align: center;}f-element f-label i { float: left; font-size: 18px; margin-right: 6px;}f-element f-label.center { width: 100%; text-align: center; display: block;}f-element.title { height: 29px; background-color: #3a3a3ab0; background-color: #3b3b43ed; cursor: all-scroll; border-top-left-radius: 6px; border-top-right-radius: 6px;}f-element.blue { background-color: #014fc5;}f-element.red { background-color: #bd0b0b;}f-element.green { background-color: #148d05;}f-element.yellow { background-color: #d6b100;}f-element.title.left { text-align: left; display: inline-grid; justify-content: start;}f-element.title span { text-align: center; font-size: 15px; padding-top: 2px;}f-element.title i { font-size: 18px; position: absolute; right: 10px; top: 50%; transform: translateY(-50%); opacity: .5;}f-element.title f-toolbar i { font-size: 20px; right: unset; left: 0px;}f-element.input-right.title i { left: 10px; right: unset;}f-element.title.left span { text-align: left;}f-element f-io { border: 2px solid #dadada; width: 7px; height: 7px; position: absolute; background: #242427; border-radius: 8px; float: left; left: -7px; top: calc( 50% - 5px ); cursor: alias; box-shadow: 0 0 3px 2px #0000005e; z-index: 1;}f-element f-io.connect,f-canvas.dragging-rio f-element:hover f-io.lio,f-canvas.dragging-lio f-element:hover f-io.rio { zoom: 1.4;}f-node.io-connect f-io:not(.connect) { border: 2px solid #dadada !important; zoom: 1 !important;}f-element f-io.rio { float: right; right: -7px; left: unset;}f-element f-disconnect { position: absolute; left: -35px; top: 50%; font-size: 22px; transform: translateY( -50% ); filter: drop-shadow(0 0 5px #000); text-shadow: 0px 0px 5px black; cursor: pointer; transition: all .2s;}f-element.input-right f-disconnect { right: -35px; left: unset;}f-element f-disconnect:hover { color: #ff3300;}f-element textarea::-webkit-scrollbar { width: 6px;}f-element textarea::-webkit-scrollbar-track { background: #111; } f-element textarea::-webkit-scrollbar-thumb { background: #0177fb; }f-element textarea::-webkit-scrollbar-thumb:hover { background: #1187ff; }f-element.small { height: 18px;}f-element.large { height: 36px;}body.connecting f-node:not(.io-connect) f-element:hover,f-element.select { background-color: rgba(61, 70, 82, 0.98);}f-element.invalid > f-io { zoom: 1 !important;}f-element.invalid::after { font-size: 14px !important; display: flex; justify-content: center; align-items:center; margin: auto; position: absolute; width: 100%; height: 100%; background: #bd0b0b77; vertical-align: middle; color: #fff; content: 'Not Compatible'; opacity: .95; backdrop-filter: grayscale(100%); white-space: nowrap; overflow: hidden; left: 0; top: 0; text-transform: initial;}f-element.invalid > f-inputs,f-element.invalid > f-label { opacity: .1;}f-drop { width: 100%; height: 100%; position: sticky; left: 0; top: 0; background: #02358417; text-align: center; justify-content: center; align-items: center; display: flex; box-shadow: inset 0 0 20px 10px #464ace17; pointer-events: none; transition: all .07s; opacity: 0; visibility: hidden;}f-drop.visible { visibility: unset; opacity: unset; transition: all .23s;}f-drop span { opacity: .5; font-size: 40px; text-shadow: 0px 0px 5px #000; font-weight: bold;}f-tooltip { pointer-events: none;}f-tooltip { position: absolute; left: 0; top: 0; background: rgba(0,0,0,.8); backdrop-filter: blur(4px); font-size: 14px; padding: 7px; left: 50%; border-radius: 10px; transform: translateX(-50%); visibility: hidden; pointer-events: none; opacity: 0; transition: all 0.3s ease; z-index: 150; white-space: nowrap;}f-menu.context,f-menu.search { position: absolute;}f-menu.context { width: 170px; z-index: 110;}f-menu.search { bottom: 85px; left: 50%; transform: translateX(-50%); z-index: 10; width: 300px;}f-menu.context f-list { display: block; margin: 0; background: #171717e6; font-size: 12px; border-radius: 6px; backdrop-filter: blur(6px); border: 1px solid #7e7e7e45; box-shadow: 3px 3px 6px rgba(0,0,0,.2); transition: opacity 0.2s ease, transform 0.1s ease;}f-menu.search f-list { margin: 0 6px 0 6px; display: flex; flex-direction: column-reverse; margin-bottom: 5px;}f-menu.context.hidden { visibility: hidden; opacity: 0;}f-menu.context f-item,f-menu.search f-item { display: block; position: relative; margin: 0; padding: 0; white-space: nowrap;}f-menu.search f-item { opacity: 0;}f-menu.context f-item.submenu::after { content: ""; position: absolute; right: 6px; top: 50%; -webkit-transform: translateY(-50%); transform: translateY(-50%); border: 5px solid transparent; border-left-color: #808080;}f-menu.context f-item:hover > f-menu,f-menu.context f-item.active > f-menu { visibility: unset; transform: unset; opacity: unset;}f-menu.context f-menu { top: 0px; left: calc( 100% - 4px );}f-menu.context f-item button,f-menu.search f-item button { overflow: visible; display: block; width: calc( 100% - 6px ); text-align: left; cursor: pointer; white-space: nowrap; padding: 6px 8px; border-radius: 3px; background: rgba(45, 45, 48, 0.95); border: 0; color: #ddd; margin: 3px; text-shadow: 1px 1px 0px #0007;}f-menu.context f-item button i,f-menu.search f-item button i { float: left; font-size: 16px;}f-menu.context f-item button span,f-menu.search f-item button span { margin-left: 6px;}f-menu.context f-item:hover > button,f-menu.search f-item:hover > button,f-menu.search f-item.active > button { color: #fff; background-color: rgba(61, 70, 82, 0.98);}f-menu.search f-item:hover,f-menu.search f-item.active { opacity: 1 !important;}f-menu.context f-item button:active { outline: solid 1px rgba( 0, 80, 200, 0.98 );}f-menu.context f-item f-tooltip { margin-left: 85px; top: -50px;}f-menu.search f-item { display: none;}f-menu.search f-item:nth-child(1) { opacity: 1; display: unset;}f-menu.search f-item:nth-child(2) { opacity: .8; display: unset;}f-menu.search f-item:nth-child(3) { opacity: .6; display: unset;}f-menu.search f-item:nth-child(4) { opacity: .4; display: unset;}f-menu.search f-item button { border-radius: 14px;}f-tips { right: 10px; top: 10px; position: absolute; z-index: 100; pointer-events: none; display: flex; flex-direction: column;}f-tips f-tip { width: 450px; font-size: 13px; border-radius: 6px; text-align: center; display: block; height: auto; color: #ffffffe0; margin: 4px; padding: 4px; background: #17171794; border: 1px solid #7e7e7e38; line-height: 100%; backdrop-filter: blur(6px); transition: all 0.2s ease; text-transform: initial; opacity: 0;}f-tips f-tip:nth-child(1) { opacity: 1;}f-tips f-tip:nth-child(2) { opacity: .75;}f-tips f-tip:nth-child(3) { opacity: .25;}f-tips f-tip:nth-child(4) { opacity: .1;}f-tips f-tip.error { background: #b900005e;}f-menu.search input { width: calc( 100% - 28px ); height: 41px; position: absolute; z-index: 10; border-radius: 20px; padding-left: 14px; padding-right: 14px; font-size: 15px; background-color: #17171794; border: 1px solid #7e7e7e45; backdrop-filter: blur(6px); box-shadow: 3px 3px 6px rgb(0 0 0 / 20%); text-transform: initial;}f-menu.circle { position: absolute; left: 40px; bottom: 40px; z-index: 100;}f-menu.circle f-item { align-content: space-around; margin-right: 20px;}f-menu.circle f-item button { width: 47px; height: 47px; font-size: 22px; background: #17171794; border-radius: 50%; backdrop-filter: blur(6px); border: 1px solid #7e7e7e45; line-height: 100%; cursor: pointer; box-shadow: 3px 3px 6px rgba(0,0,0,.2);}f-menu.circle f-item f-tooltip { margin-top: -60px;}.f-rounded f-node f-element,.f-rounded f-node f-element.title.left { border-radius: 10px 5px 10px 5px;}.f-rounded f-node f-element input, .f-rounded f-node f-element select,.f-rounded f-node f-element button,.f-rounded f-node f-element textarea,.f-rounded f-node f-element input[type='checkbox'].toggle,.f-rounded f-node f-element input[type='checkbox'].toggle:after { border-radius: 20px 10px;}.f-rounded f-node f-element input { padding-left: 7px; padding-right: 7px;}.f-rounded f-menu.context,.f-rounded f-menu.context f-item button { border-radius: 20px 10px;}@media (hover: hover) and (pointer: fine) { f-node:not(.selected):hover { filter: drop-shadow(0 0 6px #66666630); } f-element f-toolbar { visibility: hidden; opacity: 0; transition: opacity 0.2s ease; } f-node:hover > f-element f-toolbar { visibility: visible; opacity: 1; } f-element f-io:hover { zoom: 1.4; } f-menu.circle f-item button:hover { background-color: #2a2a2a; } f-menu.search input:hover, f-menu.search input:focus { background-color: #1a1a1a; filter: drop-shadow(0 0 6px #66666630); } f-menu.search input:focus { filter: drop-shadow(0 0 8px #4444dd); } f-menu.circle f-item button:hover > f-tooltip, f-menu.context f-item button:hover > f-tooltip { visibility: visible; opacity: 1; } f-menu.circle f-item button:hover > f-tooltip { margin-top: -50px; } f-menu.context f-item button:hover > f-tooltip { top: -30px; } f-menu.circle f-item button:focus > f-tooltip, f-menu.context f-item button:focus > f-tooltip { visibility: hidden; opacity: 0; }}@media (hover: none) and (pointer: coarse) { body.dragging f-canvas, body.connecting f-canvas { overflow: hidden !important; }}f-canvas { will-change: top, left;}f-node { will-change: transform !important;}` );
const REVISION = '1';
@@ -114,6 +114,50 @@
}
+class PointerMonitor {
+
+ started = false;
+
+ constructor() {
+
+ this.x = 0;
+ this.y = 0;
+
+ this._onMoveEvent = ( e ) => {
+
+ const event = e.touches ? e.touches[ 0 ] : e;
+
+ this.x = event.x;
+ this.y = event.y;
+
+ };
+
+ }
+
+ start() {
+
+ if ( this.started ) return;
+
+ this.started = true;
+
+ window.addEventListener( 'wheel', this._onMoveEvent, true );
+
+ window.addEventListener( 'mousedown', this._onMoveEvent, true );
+ window.addEventListener( 'touchstart', this._onMoveEvent, true );
+
+ window.addEventListener( 'mousemove', this._onMoveEvent, true );
+ window.addEventListener( 'touchmove', this._onMoveEvent, true );
+
+ window.addEventListener( 'dragover', this._onMoveEvent, true );
+
+ return this;
+
+ }
+
+}
+
+const pointer = new PointerMonitor().start();
+
const draggableDOM = ( dom, callback = null, className = 'dragging' ) => {
let dragData = null;
@@ -259,10 +303,16 @@
for ( const callback of list ) {
- callback( ...params );
+ if ( callback( ...params ) === false ) {
+
+ return false;
+
+ }
}
+ return true;
+
};
const toPX = ( val ) => {
@@ -291,6 +341,7 @@
var Utils = /*#__PURE__*/Object.freeze({
__proto__: null,
+ pointer: pointer,
draggableDOM: draggableDOM,
dispatchEventList: dispatchEventList,
toPX: toPX,
@@ -370,8 +421,18 @@
}
+ const type = e.type;
+
+ if ( ( type === 'mouseout' ) && selected === element ) {
+
+ selected = null;
+
+ } else {
+
selected = element;
+ }
+
};
if ( draggable === false ) {
@@ -385,6 +446,9 @@
}
dom.addEventListener( 'mouseup', onSelect, true );
+ dom.addEventListener( 'mouseover', onSelect );
+ dom.addEventListener( 'mouseout', onSelect );
+ dom.addEventListener( 'touchmove', onSelect );
dom.addEventListener( 'touchend', onSelect );
this.inputs = [];
@@ -398,14 +462,15 @@
this.events = {
'connect': [],
- 'connectChildren': []
+ 'connectChildren': [],
+ 'valid': []
};
this.node = null;
this.style = '';
- this.extra = null;
+ this.objectCallback = null;
this.enabledInputs = true;
@@ -418,10 +483,10 @@
this.lioDOM = this._createIO( 'lio' );
this.rioDOM = this._createIO( 'rio' );
- this.dom.classList.add( `output-${ Link.InputDirection }` );
+ this.dom.classList.add( `input-${ Link.InputDirection }` );
- this.dom.appendChild( this.lioDOM );
- this.dom.appendChild( this.rioDOM );
+ this.dom.append( this.lioDOM );
+ this.dom.append( this.rioDOM );
this.addEventListener( 'connect', ( ) => {
@@ -437,6 +502,22 @@
}
+ setAttribute( name, value ) {
+
+ this.dom.setAttribute( name, value );
+
+ return this;
+
+ }
+
+ onValid( callback ) {
+
+ this.events.valid.push( callback );
+
+ return this;
+
+ }
+
onConnect( callback, childrens = false ) {
this.events.connect.push( callback );
@@ -451,17 +532,17 @@
}
- setExtra( value ) {
+ setObjectCallback( callback ) {
- this.extra = value;
+ this.objectCallback = callback;
return this;
}
- getExtra() {
+ getObject( output = null ) {
- return this.extra;
+ return this.objectCallback ? this.objectCallback( output ) : null;
}
@@ -485,9 +566,9 @@
const dom = this.dom;
- if ( !this.enabledInputs ) dom.classList.remove( 'inputs-disable');
+ if ( ! this.enabledInputs ) dom.classList.remove( 'inputs-disable' );
- if ( !value ) dom.classList.add( 'inputs-disable' );
+ if ( ! value ) dom.classList.add( 'inputs-disable' );
this.enabledInputs = value;
@@ -501,6 +582,14 @@
}
+ setColor( color ) {
+
+ this.dom.style[ 'background-color' ] = toHex( color );
+
+ return this;
+
+ }
+
setStyle( style ) {
const dom = this.dom;
@@ -529,6 +618,20 @@
}
+ setInputColor( color ) {
+
+ if ( Link.InputDirection === 'left' ) {
+
+ return this.setLIOColor( color );
+
+ } else {
+
+ return this.setRIOColor( color );
+
+ }
+
+ }
+
setOutput( length ) {
if ( Link.InputDirection === 'left' ) {
@@ -543,6 +646,20 @@
}
+ setOutputColor( color ) {
+
+ if ( Link.InputDirection === 'left' ) {
+
+ return this.setRIOColor( color );
+
+ } else {
+
+ return this.setLIOColor( color );
+
+ }
+
+ }
+
get inputLength() {
if ( Link.InputDirection === 'left' ) {
@@ -571,6 +688,14 @@
}
+ setLIOColor( color ) {
+
+ this.lioDOM.style[ 'border-color' ] = toHex( color );
+
+ return this;
+
+ }
+
setLIO( length ) {
this.lioLength = length;
@@ -581,6 +706,26 @@
}
+ getLIOColor() {
+
+ return this.lioDOM.style[ 'border-color' ];
+
+ }
+
+ setRIOColor( color ) {
+
+ this.rioDOM.style[ 'border-color' ] = toHex( color );
+
+ return this;
+
+ }
+
+ getRIOColor() {
+
+ return this.rioDOM.style[ 'border-color' ];
+
+ }
+
setRIO( length ) {
this.rioLength = length;
@@ -597,7 +742,7 @@
input.element = this;
- this.inputsDOM.appendChild( input.dom );
+ this.inputsDOM.append( input.dom );
return this;
@@ -629,6 +774,12 @@
if ( element !== null ) {
+ if ( dispatchEventList( this.events.valid, this, element, 'connect' ) === false ) {
+
+ return false;
+
+ }
+
const link = new Link( this, element );
this.links.push( link );
@@ -638,7 +789,7 @@
this.disconnectDOM = document.createElement( 'f-disconnect' );
this.disconnectDOM.innerHTML = Styles.icons.unlink ? `<i class='${ Styles.icons.unlink }'></i>` : '✖';
- this.dom.appendChild( this.disconnectDOM );
+ this.dom.append( this.disconnectDOM );
const onDisconnect = () => {
@@ -694,7 +846,7 @@
this.dispatchEvent( new Event( 'connect' ) );
- return this;
+ return true;
}
@@ -802,23 +954,23 @@
}
- get linkedExtra() {
+ getLinkedObject( output = null ) {
- const linkedElement = this.linkedElement;
+ const linkedElement = this.getLinkedElement();
- return linkedElement ? linkedElement.getExtra() : null;
+ return linkedElement ? linkedElement.getObject( output ) : null;
}
- get linkedElement() {
+ getLinkedElement() {
- const link = this.link;
+ const link = this.getLink();
return link ? link.outputElement : null;
}
- get link() {
+ getLink() {
return this.links[ 0 ];
@@ -850,32 +1002,67 @@
const defaultOutput = Link.InputDirection === 'left' ? 'lio' : 'rio';
const link = type === defaultOutput ? new Link( this ) : new Link( null, this );
+ const previewLink = new Link( link.inputElement, link.outputElement );
this.links.push( link );
draggableDOM( e, ( data ) => {
- if ( data.dragging === false ) {
+ if ( previewLink.outputElement )
+ previewLink.outputElement.dom.classList.remove( 'invalid' );
- nodeDOM.classList.remove( 'io-connect' );
+ if ( previewLink.inputElement )
+ previewLink.inputElement.dom.classList.remove( 'invalid' );
- ioDOM.classList.remove( 'connect' );
- dom.classList.remove( 'select' );
+ previewLink.inputElement = link.inputElement;
+ previewLink.outputElement = link.outputElement;
- this.links.splice( this.links.indexOf( link ), 1 );
+ if ( type === defaultOutput ) {
+
+ previewLink.outputElement = selected;
- if ( selected !== null ) {
+ } else {
+
+ previewLink.inputElement = selected;
+
+ }
+
+ const isInvalid = previewLink.inputElement !== null && previewLink.outputElement !== null &&
+ previewLink.inputElement.inputLength > 0 && previewLink.outputElement.outputLength > 0 &&
+ dispatchEventList( previewLink.inputElement.events.valid, previewLink.inputElement, previewLink.outputElement, data.dragging ? 'dragging' : 'dragged' ) === false;
+
+ if ( data.dragging && isInvalid ) {
if ( type === defaultOutput ) {
- link.outputElement = selected;
+ if ( previewLink.outputElement )
+ previewLink.outputElement.dom.classList.add( 'invalid' );
} else {
- link.inputElement = selected;
+ if ( previewLink.inputElement )
+ previewLink.inputElement.dom.classList.add( 'invalid' );
}
+ return;
+
+ }
+
+ if ( ! data.dragging ) {
+
+ nodeDOM.classList.remove( 'io-connect' );
+
+ ioDOM.classList.remove( 'connect' );
+ dom.classList.remove( 'select' );
+
+ this.links.splice( this.links.indexOf( link ), 1 );
+
+ if ( selected !== null && ! isInvalid ) {
+
+ link.inputElement = previewLink.inputElement;
+ link.outputElement = previewLink.outputElement;
+
// check if is an is circular link
if ( link.outputElement.node.isCircular( link.inputElement.node ) ) {
@@ -923,6 +1110,8 @@
this.extra = null;
+ this.tagColor = null;
+
this.events = {
'change': [],
'click': []
@@ -956,12 +1145,28 @@
}
+ setTagColor( color ) {
+
+ this.tagColor = color;
+
+ this.dom.style[ 'border-left' ] = `2px solid ${color}`;
+
+ return this;
+
+ }
+
+ getTagColor() {
+
+ return this.tagColor;
+
+ }
+
setToolTip( text ) {
const div = document.createElement( 'f-tooltip' );
div.innerText = text;
- this.dom.appendChild( div );
+ this.dom.append( div );
return this;
@@ -983,6 +1188,20 @@
}
+ setReadOnly( value ) {
+
+ this.dom.readOnly = value;
+
+ return this;
+
+ }
+
+ getReadOnly() {
+
+ return this.dom.readOnly;
+
+ }
+
setValue( value, dispatch = true ) {
this.dom.value = value;
@@ -1161,7 +1380,7 @@
element.addEventListener( 'connect', this._onConnect );
element.addEventListener( 'connectChildren', this._onConnectChildren );
- this.dom.appendChild( element.dom );
+ this.dom.append( element.dom );
return this;
@@ -1347,9 +1566,9 @@
this.iconDOM = iconDOM;
this.toolbarDOM = toolbarDOM;
- dom.appendChild( spanDOM );
- dom.appendChild( iconDOM );
- dom.appendChild( toolbarDOM );
+ dom.append( spanDOM );
+ dom.append( iconDOM );
+ dom.append( toolbarDOM );
}
@@ -1385,7 +1604,7 @@
this.buttons.push( button );
- this.toolbarDOM.appendChild( button.dom );
+ this.toolbarDOM.append( button.dom );
return this;
@@ -1424,9 +1643,11 @@
}
-const drawLine = ( p1x, p1y, p2x, p2y, invert, size, color, ctx ) => {
+const drawLine = ( p1x, p1y, p2x, p2y, invert, size, colorA, ctx, colorB = null ) => {
- const offset = 100 * ( invert ? - 1 : 1 );
+ const dx = p2x - p1x;
+ const dy = p2y - p1y;
+ const offset = Math.sqrt( dx*dx + dy*dy ) * (invert ? -.3 : .3) ;
ctx.beginPath();
@@ -1438,8 +1659,21 @@
p2x, p2y
);
+ if ( colorB !== null && colorA !== colorB ) {
+
+ const gradient = ctx.createLinearGradient( p1x, p1y, p2x, p2y );
+ gradient.addColorStop( 0, colorA );
+ gradient.addColorStop( 1, colorB );
+
+ ctx.strokeStyle = gradient;
+
+ } else {
+
+ ctx.strokeStyle = colorA;
+
+ }
+
ctx.lineWidth = size;
- ctx.strokeStyle = color;
ctx.stroke();
};
@@ -1514,11 +1748,11 @@
dropDOM.innerHTML = '<span>drop your file</span>';
- dom.appendChild( dropDOM );
- dom.appendChild( canvas );
- dom.appendChild( frontCanvas );
- dom.appendChild( contentDOM );
- dom.appendChild( areaDOM );
+ dom.append( dropDOM );
+ dom.append( canvas );
+ dom.append( frontCanvas );
+ dom.append( contentDOM );
+ dom.append( areaDOM );
/*
let zoomTouchData = null;
@@ -1790,11 +2024,13 @@
add( node ) {
+ if ( node.canvas === this ) return;
+
this.nodes.push( node );
node.canvas = this;
- this.contentDOM.appendChild( node.dom );
+ this.contentDOM.append( node.dom );
return this;
@@ -1818,6 +2054,8 @@
this.contentDOM.removeChild( node.dom );
+ node.dispatchEvent( new Event( 'remove' ) );
+
return this;
}
@@ -1842,7 +2080,13 @@
for ( const link of links ) {
- if ( link.outputElement && link.outputElement.node === node ) {
+ if ( link.inputElement && link.outputElement ) {
+
+ if ( link.inputElement.node === node ) {
+
+ link.inputElement.connect();
+
+ } else if ( link.outputElement.node === node ) {
link.inputElement.connect();
@@ -1852,6 +2096,8 @@
}
+ }
+
getLinks() {
const links = [];
@@ -1989,24 +2235,36 @@
if ( draggingLink || length === 1 ) {
+ let colorA = null,
+ colorB = null;
+
if ( draggingLink === 'rio' ) {
+ colorA = colorB = lioElement.getRIOColor();
+
aPos.x += offsetIORadius;
bPos.x /= zoom;
bPos.y /= zoom;
} else if ( draggingLink === 'lio' ) {
+ colorA = colorB = rioElement.getLIOColor();
+
bPos.x -= offsetIORadius;
aPos.x /= zoom;
aPos.y /= zoom;
+ } else {
+
+ colorA = lioElement.getRIOColor();
+ colorB = rioElement.getLIOColor();
+
}
drawLine(
aPos.x * zoom, aPos.y * zoom,
bPos.x * zoom, bPos.y * zoom,
- false, 2, '#ffffff', drawContext
+ false, 2, colorA || '#ffffff', drawContext, colorB || '#ffffff'
);
} else {
@@ -2022,6 +2280,9 @@
const rioLength = Math.min( lioElement.rioLength, length );
const lioLength = Math.min( rioElement.lioLength, length );
+ const colorA = lioElement.getRIOColor() || color;
+ const colorB = rioElement.getLIOColor() || color;
+
const aCenterY = ( ( rioLength * marginY ) * .5 ) - ( marginY / 2 );
const bCenterY = ( ( lioLength * marginY ) * .5 ) - ( marginY / 2 );
@@ -2034,7 +2295,7 @@
drawLine(
aPos.x * zoom, ( ( aPos.y + aPosY ) - aCenterY ) * zoom,
bPos.x * zoom, ( ( bPos.y + bPosY ) - bCenterY ) * zoom,
- false, 2, color, drawContext
+ false, 2, colorA, drawContext, colorB
);
}
@@ -2093,10 +2354,10 @@
const dom = document.createElement( 'button' );
const spanDOM = document.createElement( 'span' );
- dom.appendChild( spanDOM );
+ dom.append( spanDOM );
const iconDOM = document.createElement( 'i' );
- dom.appendChild( iconDOM );
+ dom.append( iconDOM );
super( dom );
@@ -2149,14 +2410,15 @@
class ObjectNode extends Node {
- constructor( name, inputLength, extra = null, width = 300 ) {
+ constructor( name, inputLength, callback = null, width = 300 ) {
super();
this.setWidth( width );
const title = new TitleElement( name )
- .setExtra( extra )
+ .setObjectCallback( callback )
+ .setSerializable( false )
.setOutput( inputLength );
const closeButton = new ButtonInput( Styles.icons.close || '✕' ).onClick( () => {
@@ -2174,17 +2436,43 @@
}
- setExtra( value ) {
+ setName( value ) {
+
+ this.title.setTitle( value );
+
+ return this;
- this.title.setExtra( value );
+ }
+
+ getName() {
+
+ return this.title.getTitle();
+
+ }
+
+ setObjectCallback( callback ) {
+
+ this.title.setObjectCallback( callback );
return this;
}
- getExtra( value ) {
+ getObject( callback ) {
- return this.title.getExtra();
+ return this.title.getObject( callback );
+
+ }
+
+ setColor( color ) {
+
+ return this.title.setColor( color );
+
+ }
+
+ setOutputColor( color ) {
+
+ return this.title.setOutputColor( color );
}
@@ -2327,6 +2615,14 @@
}
+ setStep( step ) {
+
+ this.step = step;
+
+ return this;
+
+ }
+
setRange( min, max, step ) {
this.min = min;
@@ -2452,8 +2748,8 @@
} );
- dom.appendChild( rangeDOM );
- dom.appendChild( field.dom );
+ dom.append( rangeDOM );
+ dom.append( field.dom );
this.rangeDOM = rangeDOM;
this.field = field;
@@ -2625,11 +2921,13 @@
this.spanDOM = spanDOM;
this.iconDOM = iconDOM;
- this.labelDOM.appendChild( this.spanDOM );
- this.labelDOM.appendChild( this.iconDOM );
+ this.labelDOM.append( this.spanDOM );
+ this.labelDOM.append( this.iconDOM );
- this.dom.appendChild( this.labelDOM );
- this.dom.appendChild( this.inputsDOM );
+ this.dom.append( this.labelDOM );
+ this.dom.append( this.inputsDOM );
+
+ this.serializeLabel = false;
this.setLabel( label );
this.setAlign( align );
@@ -2672,6 +2970,8 @@
super.serialize( data );
+ if ( this.serializeLabel ) {
+
const label = this.getLabel();
const icon = this.getIcon();
@@ -2685,10 +2985,14 @@
}
+ }
+
deserialize( data ) {
super.deserialize( data );
+ if ( this.serializeLabel ) {
+
this.setLabel( data.label );
if ( data.icon !== undefined ) {
@@ -2699,6 +3003,8 @@
}
+ }
+
}
class PanelNode extends Node {
@@ -2824,29 +3130,129 @@
class Menu extends EventTarget {
- constructor( className, target = null ) {
+ constructor( className ) {
super();
const dom = document.createElement( 'f-menu' );
dom.className = className + ' hidden';
+ const listDOM = document.createElement( 'f-list' );
+
+ dom.append( listDOM );
+
this.dom = dom;
+ this.listDOM = listDOM;
this.visible = false;
this.subMenus = new WeakMap();
this.domButtons = new WeakMap();
- this.events = {
- 'context': []
- };
+ this.buttons = [];
- this.addEventListener( 'context', ( ) => {
+ this.events = {};
- dispatchEventList( this.events.context, this );
+ }
- } );
+ onContext( callback ) {
+
+ this.events.context.push( callback );
+
+ return this;
+
+ }
+
+ show() {
+
+ this.dom.classList.remove( 'hidden' );
+
+ this.visible = true;
+
+ this.dispatchEvent( new Event( 'show' ) );
+
+ return this;
+
+ }
+
+ hide() {
+
+ this.dom.classList.add( 'hidden' );
+
+ this.dispatchEvent( new Event( 'hide' ) );
+
+ this.visible = false;
+
+ }
+
+ add( button, submenu = null ) {
+
+ const liDOM = document.createElement( 'f-item' );
+
+ if ( submenu !== null ) {
+
+ liDOM.classList.add( 'submenu' );
+
+ liDOM.append( submenu.dom );
+
+ this.subMenus.set( button, submenu );
+
+ button.dom.addEventListener( 'mouseover', () => submenu.show() );
+ button.dom.addEventListener( 'mouseout', () => submenu.hide() );
+
+ }
+
+ liDOM.append( button.dom );
+
+ this.buttons.push( button );
+
+ this.listDOM.append( liDOM );
+
+ this.domButtons.set( button, liDOM );
+
+ return this;
+
+ }
+
+ clear() {
+
+ this.buttons = [];
+
+ this.subMenus = new WeakMap();
+ this.domButtons = new WeakMap();
+
+ while ( this.listDOM.firstChild ) {
+
+ this.listDOM.firstChild.remove();
+
+ }
+
+ }
+
+}
+
+let lastContext = null;
+
+const onCloseLastContext = ( e ) => {
+
+ if ( lastContext && lastContext.visible === true && e.target.closest( 'f-menu.context' ) === null ) {
+
+ lastContext.hide();
+
+ }
+
+};
+
+document.body.addEventListener( 'mousedown', onCloseLastContext, true );
+document.body.addEventListener( 'touchstart', onCloseLastContext, true );
+
+class ContextMenu extends Menu {
+
+ constructor( target = null ) {
+
+ super( 'context', target );
+
+ this.events.context = [];
this._lastButtonClick = null;
@@ -2888,45 +3294,50 @@
};
+ this.addEventListener( 'context', ( ) => {
+
+ dispatchEventList( this.events.context, this );
+
+ } );
+
this.setTarget( target );
}
- onContext( callback ) {
+ openFrom( dom ) {
- this.events.context.push( callback );
+ const rect = dom.getBoundingClientRect();
- return this;
+ return this.open( rect.x + ( rect.width / 2 ), rect.y + ( rect.height / 2 ) );
}
- show( x = null, y = null ) {
+ open( x = pointer.x, y = pointer.y ) {
- this._onButtonClick();
-
- if ( x !== null && y !== null ) {
+ if ( lastContext !== null ) {
- this.setPosition( x, y );
+ lastContext.hide();
}
- this.dom.classList.remove( 'hidden' );
+ lastContext = this;
- this.visible = true;
+ this.setPosition( x, y );
- this.dispatchEvent( new Event( 'show' ) );
+ document.body.append( this.dom );
- return this;
+ return this.show();
}
- hide() {
+ setPosition( x, y ) {
- this.dom.classList.add( 'hidden' );
+ const dom = this.dom;
- this.dispatchEvent( new Event( 'hide' ) );
+ dom.style.left = toPX( x );
+ dom.style.top = toPX( y );
- this.visible = false;
+ return this;
}
@@ -2940,72 +3351,143 @@
if ( e.pointerType !== 'mouse' || ( e.pageX === 0 && e.pageY === 0 ) ) return;
- const rect = this.target.getBoundingClientRect();
-
this.dispatchEvent( new Event( 'context' ) );
- this.show( e.pageX - rect.left, e.pageY - rect.top );
+ this.open();
};
- const onDown = ( e ) => {
-
- if ( this.visible === true && e.target.closest( 'f-menu' ) === null ) {
+ this.target = target;
- this.hide();
+ target.addEventListener( 'contextmenu', onContextMenu, false );
}
- };
+ return this;
- this.target = target;
+ }
- target.addEventListener( 'mousedown', onDown, true );
- target.addEventListener( 'touchstart', onDown, true );
+ show() {
- target.addEventListener( 'contextmenu', onContextMenu, false );
+ if ( ! this.opened ) {
- target.appendChild( this.dom );
+ this.dom.style.left = '';
+ this.dom.style.transform = '';
}
- return this;
+ const domRect = this.dom.getBoundingClientRect();
+
+ let offsetX = Math.min( window.innerWidth - ( domRect.x + domRect.width + 10 ), 0 );
+ let offsetY = Math.min( window.innerHeight - ( domRect.y + domRect.height + 10 ), 0 );
+
+ if ( this.opened ) {
+
+ if ( offsetX < 0 ) offsetX = - domRect.width;
+ if ( offsetY < 0 ) offsetY = - domRect.height;
+
+ this.setPosition( domRect.x + offsetX, domRect.y + offsetY );
+
+ } else {
+
+ // flip submenus
+
+ if ( offsetX < 0 ) this.dom.style.left = '-100%';
+ if ( offsetY < 0 ) this.dom.style.transform = 'translateY( calc( 32px - 100% ) )';
}
- add( button, submenu = null ) {
+ return super.show();
- const liDOM = document.createElement( 'f-item' );
+ }
- if ( submenu !== null ) {
+ hide() {
- liDOM.classList.add( 'submenu' );
+ if ( this.opened ) {
+
+ lastContext = null;
- liDOM.appendChild( submenu.dom );
+ }
- this.subMenus.set( button, submenu );
+ return super.hide();
}
- liDOM.appendChild( button.dom );
+ add( button, submenu = null ) {
button.addEventListener( 'click', this._onButtonClick );
button.addEventListener( 'mouseover', this._onButtonMouseOver );
- this.dom.appendChild( liDOM );
+ return super.add( button, submenu );
- this.domButtons.set( liDOM, button );
+ }
- return this;
+ get opened() {
+
+ return lastContext === this;
}
- setPosition( x, y ) {
+}
- const dom = this.dom;
+class CircleMenu extends Menu {
- dom.style.left = toPX( x );
- dom.style.top = toPX( y );
+ constructor( target = null ) {
+
+ super( 'circle', target );
+
+ }
+
+}
+
+class Tips extends EventTarget {
+
+ constructor() {
+
+ super();
+
+ const dom = document.createElement( 'f-tips' );
+
+ this.dom = dom;
+
+ this.time = 0;
+ this.duration = 3000;
+
+ }
+
+ message( str ) {
+
+ return this.tip( str );
+
+ }
+
+ error( str ) {
+
+ return this.tip( str, 'error' );
+
+ }
+
+ tip( html, className = '' ) {
+
+ const dom = document.createElement( 'f-tip' );
+ dom.className = className;
+ dom.innerHTML = html;
+
+ this.dom.prepend( dom );
+
+ //requestAnimationFrame( () => dom.style.opacity = 1 );
+
+ this.time = Math.min( this.time + this.duration, this.duration );
+
+ setTimeout( () => {
+
+ this.time -= this.duration;
+
+ dom.style.opacity = 0;
+
+ setTimeout( () => dom.remove(), 250 );
+
+ }, this.time );
return this;
@@ -3013,49 +3495,304 @@
}
-let lastContext = null;
+const filterString = ( str ) => {
-class ContextMenu extends Menu {
+ return str.trim().toLowerCase().replace( /\s\s+/g, ' ' );
- constructor( target = null ) {
+};
- super( 'context', target );
+class Search extends Menu {
+
+ constructor() {
+
+ super( 'search' );
+
+ this.events.submit = [];
+ this.events.filter = [];
+
+ const inputDOM = document.createElement( 'input' );
+ inputDOM.placeholder = 'Type here';
+
+ let filter = true;
+ let filterNeedUpdate = true;
+
+ inputDOM.addEventListener( 'focusout', () => {
+
+ filterNeedUpdate = true;
+
+ this.setValue( '' );
+
+ } );
+
+ inputDOM.onkeydown = ( e ) => {
+
+ const keyCode = e.keyCode;
+
+ if ( keyCode === 38 ) {
+
+ const index = this.filteredIndex;
+
+ if ( this.forceAutoComplete ) {
+
+ this.filteredIndex = index !== null ? ( index + 1 ) % ( this.filtered.length || 1 ) : 0;
+
+ } else {
+
+ this.filteredIndex = index !== null ? Math.min( index + 1, this.filtered.length - 1 ) : 0;
}
- show( x, y ) {
+ e.preventDefault();
+
+ filter = false;
- if ( lastContext !== null ) {
+ } else if ( keyCode === 40 ) {
- lastContext.hide();
+ const index = this.filteredIndex;
+
+ if ( this.forceAutoComplete ) {
+
+ this.filteredIndex = index - 1;
+
+ if ( this.filteredIndex === null ) this.filteredIndex = this.filtered.length - 1;
+
+ } else {
+
+ this.filteredIndex = index !== null ? index - 1 : null;
}
- lastContext = this;
+ e.preventDefault();
+
+ filter = false;
+
+ } else if ( keyCode === 13 ) {
+
+ this.value = this.currentFiltered ? this.currentFiltered.button.getValue() : inputDOM.value;
- return super.show( x, y );
+ this.submit();
+
+ e.preventDefault();
+
+ filter = false;
+
+ } else {
+
+ filter = true;
}
- hide() {
+ };
- if ( lastContext === this ) {
+ inputDOM.onkeyup = () => {
- lastContext = null;
+ if ( filter ) {
+
+ if ( filterNeedUpdate ) {
+
+ this.dispatchEvent( new Event( 'filter' ) );
+
+ filterNeedUpdate = false;
}
- return super.hide();
+ this.filter( inputDOM.value );
}
-}
+ };
-class CircleMenu extends Menu {
+ this.filtered = [];
+ this.currentFiltered = null;
- constructor( target = null ) {
+ this.value = '';
- super( 'circle', target );
+ this.forceAutoComplete = false;
+
+ this.dom.append( inputDOM );
+
+ this.inputDOM = inputDOM;
+
+ this.addEventListener( 'filter', ( ) => {
+
+ dispatchEventList( this.events.filter, this );
+
+ } );
+
+ this.addEventListener( 'submit', ( ) => {
+
+ dispatchEventList( this.events.submit, this );
+
+ } );
+
+ }
+
+ submit() {
+
+ this.dispatchEvent( new Event( 'submit' ) );
+
+ return this.setValue( '' );
+
+ }
+
+ setValue( value ) {
+
+ this.inputDOM.value = value;
+
+ this.filter( value );
+
+ return this;
+
+ }
+
+ getValue() {
+
+ return this.value;
+
+ }
+
+ onFilter( callback ) {
+
+ this.events.filter.push( callback );
+
+ return this;
+
+ }
+
+ onSubmit( callback ) {
+
+ this.events.submit.push( callback );
+
+ return this;
+
+ }
+
+ getFilterByButton( button ) {
+
+ for ( const filter of this.filtered ) {
+
+ if ( filter.button === button ) {
+
+ return filter;
+
+ }
+
+ }
+
+ return null;
+
+ }
+
+ add( button ) {
+
+ super.add( button );
+
+ const onDown = ( e ) => {
+
+ const filter = this.getFilterByButton( button );
+
+ this.filteredIndex = this.filtered.indexOf( filter );
+ this.value = button.getValue();
+
+ this.submit();
+
+ };
+
+ button.dom.addEventListener( 'mousedown', onDown );
+ button.dom.addEventListener( 'touchstart', onDown );
+
+ this.domButtons.get( button ).remove();
+
+ return this;
+
+ }
+
+ set filteredIndex( index ) {
+
+ if ( this.currentFiltered ) {
+
+ const buttonDOM = this.domButtons.get( this.currentFiltered.button );
+
+ buttonDOM.classList.remove( 'active' );
+
+ this.currentFiltered = null;
+
+ }
+
+ const filteredItem = this.filtered[ index ];
+
+ if ( filteredItem ) {
+
+ const buttonDOM = this.domButtons.get( filteredItem.button );
+
+ buttonDOM.classList.add( 'active' );
+
+ this.currentFiltered = filteredItem;
+
+ }
+
+ this.updateFilter();
+
+ }
+
+ get filteredIndex() {
+
+ return this.currentFiltered ? this.filtered.indexOf( this.currentFiltered ) : null;
+
+ }
+
+ filter( text ) {
+
+ text = filterString( text );
+
+ const filtered = [];
+
+ for ( const button of this.buttons ) {
+
+ const buttonDOM = this.domButtons.get( button );
+
+ buttonDOM.remove();
+
+ const label = filterString( button.getValue() );
+
+ if ( text && label.includes( text ) === true ) {
+
+ const score = text.length / label.length;
+
+ filtered.push( {
+ button,
+ score
+ } );
+
+ }
+
+ }
+
+ filtered.sort( ( a, b ) => b.score - a.score );
+
+ this.filtered = filtered;
+ this.filteredIndex = this.forceAutoComplete ? 0 : null;
+
+ }
+
+ updateFilter() {
+
+ const filteredIndex = Math.min( this.filteredIndex, this.filteredIndex - 3 );
+
+ for ( let i = 0; i < this.filtered.length; i ++ ) {
+
+ const button = this.filtered[ i ].button;
+ const buttonDOM = this.domButtons.get( button );
+
+ buttonDOM.remove();
+
+ if ( i >= filteredIndex ) {
+
+ this.listDOM.append( buttonDOM );
+
+ }
+
+ }
}
@@ -3063,7 +3800,7 @@
class SelectInput extends Input {
- constructor( options = [] ) {
+ constructor( options = [], value = null ) {
const dom = document.createElement( 'select' );
super( dom );
@@ -3074,16 +3811,24 @@
};
- this.setOptions( options );
+ dom.onmousedown = dom.ontouchstart = ( e ) => {
+
+ this.dispatchEvent( new Event( 'click' ) );
+
+ };
+
+ this.setOptions( options, value );
}
- setOptions( options ) {
+ setOptions( options, value = null ) {
const dom = this.dom;
+ const defaultValue = dom.value;
- this.options = options;
+ let containsDefaultValue = false;
+ this.options = options;
dom.innerHTML = '';
for ( let index = 0; index < options.length; index ++ ) {
@@ -3100,10 +3845,18 @@
option.innerText = opt.name;
option.value = opt.value;
- dom.appendChild( option );
+ if ( containsDefaultValue === false && defaultValue === opt.value ) {
+
+ containsDefaultValue = true;
}
+ dom.append( option );
+
+ }
+
+ dom.value = value !== null ? value : containsDefaultValue ? defaultValue : '';
+
return this;
}
@@ -3126,7 +3879,7 @@
const currentOptions = this.options;
- if ( currentOptions.length > 0 ) {
+ if ( currentOptions.length === 0 ) {
this.setOptions( data.options );
@@ -3182,6 +3935,8 @@
Menu: Menu,
ContextMenu: ContextMenu,
CircleMenu: CircleMenu,
+ Tips: Tips,
+ Search: Search,
DraggableElement: DraggableElement,
LabelElement: LabelElement,
TitleElement: TitleElement,
@@ -3291,6 +4046,12 @@
const Class = lib && lib[ obj.type ] ? lib[ obj.type ] : Flow[ obj.type ];
+ if ( ! Class ) {
+
+ console.error( `Class "${ obj.type }" not found!` );
+
+ }
+
objects[ id ] = new Class();
}
@@ -3335,4 +4096,4 @@
Loader.DEFAULT = 'default';
Loader.OBJECTS = 'objects';
-export { ButtonInput, Canvas, CircleMenu, ColorInput, ContextMenu, DraggableElement, Element, Input, LabelElement, Loader, Menu, Node, NumberInput, ObjectNode, PanelNode, REVISION, SelectInput, Serializer, SliderInput, StringInput, Styles, TextInput, TitleElement, ToggleInput, Utils };
+export { ButtonInput, Canvas, CircleMenu, ColorInput, ContextMenu, DraggableElement, Element, Input, LabelElement, Loader, Menu, Node, NumberInput, ObjectNode, PanelNode, REVISION, Search, SelectInput, Serializer, SliderInput, StringInput, Styles, TextInput, Tips, TitleElement, ToggleInput, Utils };

examples/jsm/libs/lil-gui.module.min.js

@@ -1,8 +1,8 @@
/**
* lil-gui
* https://lil-gui.georgealways.com
- * @version 0.11.0
+ * @version 0.16.0
* @author George Michael Brower
* @license MIT
*/
-class t{constructor(e,i,s,r,n="div"){this.parent=e,this.object=i,this.property=s,this._disabled=!1,this.initialValue=this.getValue(),this.domElement=document.createElement("div"),this.domElement.classList.add("controller"),this.domElement.classList.add(r),this.$name=document.createElement("div"),this.$name.classList.add("name"),t.nextNameID=t.nextNameID||0,this.$name.id="lil-gui-name-"+ ++t.nextNameID,this.$widget=document.createElement(n),this.$widget.classList.add("widget"),this.$disable=this.$widget,this.domElement.appendChild(this.$name),this.domElement.appendChild(this.$widget),this.parent.children.push(this),this.parent.controllers.push(this),this.parent.$children.appendChild(this.domElement),this._listenCallback=this._listenCallback.bind(this),this.name(s)}name(t){return this._name=t,this.$name.innerHTML=t,this}onChange(t){return this._onChange=t,this}_callOnChange(){this.parent._callOnChange(this),void 0!==this._onChange&&this._onChange.call(this,this.getValue())}onFinishChange(t){return this.onChange(t)}reset(){return this.setValue(this.initialValue),this}enable(t=!0){return this.disable(!t)}disable(t=!0){return t===this._disabled||(this._disabled=t,this.domElement.classList.toggle("disabled",t),t?this.$disable.setAttribute("disabled","disabled"):this.$disable.removeAttribute("disabled")),this}options(t){const e=this.parent.add(this.object,this.property,t);return e.name(this._name),this.destroy(),e}min(t){return this}max(t){return this}step(t){return this}listen(t=!0){return this._listening=t,void 0!==this._listenCallbackID&&(cancelAnimationFrame(this._listenCallbackID),this._listenCallbackID=void 0),this._listening&&this._listenCallback(),this}_listenCallback(){this._listenCallbackID=requestAnimationFrame(this._listenCallback);const t=this.getValue();t===this._listenValuePrev&&Object(t)!==t||this.updateDisplay(),this._listenValuePrev=t}getValue(){return this.object[this.property]}setValue(t){return this.object[this.property]=t,this._callOnChange(),this.updateDisplay(),this}updateDisplay(){return this}load(t){this.setValue(t)}save(){return this.getValue()}destroy(){this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.controllers.splice(this.parent.controllers.indexOf(this),1),this.parent.$children.removeChild(this.domElement)}}class e extends t{constructor(t,e,i){super(t,e,i,"boolean","label"),this.$input=document.createElement("input"),this.$input.setAttribute("type","checkbox"),this.$widget.appendChild(this.$input),this.$input.addEventListener("change",()=>{this.setValue(this.$input.checked)}),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.checked=this.getValue(),this}}function i(t){let e,i;return(e=t.match(/(#|0x)?([a-f0-9]{6})/i))?i=e[2]:(e=t.match(/rgb\(\s*(\d*)\s*,\s*(\d*)\s*,\s*(\d*)\s*\)/))?i=parseInt(e[1]).toString(16).padStart(2,0)+parseInt(e[2]).toString(16).padStart(2,0)+parseInt(e[3]).toString(16).padStart(2,0):(e=t.match(/^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i))&&(i=e[1]+e[1]+e[2]+e[2]+e[3]+e[3]),!!i&&"#"+i}const s={isPrimitive:!0,match:t=>"string"==typeof t,fromHexString:i,toHexString:i},r={isPrimitive:!0,match:t=>"number"==typeof t,fromHexString:t=>parseInt(t.substring(1),16),toHexString:t=>"#"+t.toString(16).padStart(6,0)},n={isPrimitive:!1,match:Array.isArray,fromHexString(t,e,i=1){const s=r.fromHexString(t);e[0]=(s>>16&255)/255*i,e[1]=(s>>8&255)/255*i,e[2]=(255&s)/255*i},toHexString:([t,e,i],s=1)=>r.toHexString(t*(s=255/s)<<16^e*s<<8^i*s<<0)},l={isPrimitive:!1,match:t=>Object(t)===t,fromHexString(t,e,i=1){const s=r.fromHexString(t);e.r=(s>>16&255)/255*i,e.g=(s>>8&255)/255*i,e.b=(255&s)/255*i},toHexString:({r:t,g:e,b:i},s=1)=>r.toHexString(t*(s=255/s)<<16^e*s<<8^i*s<<0)},o=[s,r,n,l];class a extends t{constructor(t,e,s,r){var n;super(t,e,s,"color"),this.$input=document.createElement("input"),this.$input.setAttribute("type","color"),this.$input.setAttribute("tabindex",-1),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$text=document.createElement("input"),this.$text.setAttribute("type","text"),this.$text.setAttribute("spellcheck","false"),this.$text.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$display.appendChild(this.$input),this.$widget.appendChild(this.$display),this.$widget.appendChild(this.$text),this._format=(n=this.initialValue,o.find(t=>t.match(n))),this._rgbScale=r,this._initialValueHexString=this.save(),this._textFocused=!1;const l=()=>{this._setValueFromHexString(this.$input.value)};this.$input.addEventListener("change",l),this.$input.addEventListener("input",l),this.$input.addEventListener("focus",()=>{this.$display.classList.add("focus")}),this.$input.addEventListener("blur",()=>{this.$display.classList.remove("focus")}),this.$text.addEventListener("input",()=>{const t=i(this.$text.value);t&&this._setValueFromHexString(t)}),this.$text.addEventListener("focus",()=>{this._textFocused=!0,this.$text.select()}),this.$text.addEventListener("blur",()=>{this._textFocused=!1,this.updateDisplay()}),this.$disable=this.$text,this.updateDisplay()}reset(){return this._setValueFromHexString(this._initialValueHexString),this}_setValueFromHexString(t){if(this._format.isPrimitive){const e=this._format.fromHexString(t);this.setValue(e)}else this._format.fromHexString(t,this.getValue(),this._rgbScale),this._callOnChange(),this.updateDisplay()}save(){return this._format.toHexString(this.getValue(),this._rgbScale)}load(t){this._setValueFromHexString(t)}updateDisplay(){return this.$input.value=this._format.toHexString(this.getValue(),this._rgbScale),this._textFocused||(this.$text.value=this.$input.value.substring(1)),this.$display.style.backgroundColor=this.$input.value,this}}class h extends t{constructor(t,e,i){super(t,e,i,"function"),this.$button=document.createElement("button"),this.$button.appendChild(this.$name),this.$widget.appendChild(this.$button),this.$button.addEventListener("click",t=>{t.preventDefault(),this.getValue().call(this.object)}),this.$button.addEventListener("touchstart",()=>{}),this.$disable=this.$button}}class d extends t{constructor(t,e,i,s,r,n){super(t,e,i,"number"),this._initInput(),this.min(s),this.max(r);const l=void 0!==n;this.step(l?n:this._getImplicitStep(),l),this.updateDisplay()}min(t){return this._min=t,this._onUpdateMinMax(),this}max(t){return this._max=t,this._onUpdateMinMax(),this}step(t,e=!0){return this._step=t,this._stepExplicit=e,this}updateDisplay(){const t=this.getValue();if(this._hasSlider){const e=(t-this._min)/(this._max-this._min);this.$fill.style.setProperty("width",100*e+"%")}return this._inputFocused||(this.$input.value=t),this}_initInput(){this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("inputmode","numeric"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$widget.appendChild(this.$input),this.$disable=this.$input;const t=t=>{const e=parseFloat(this.$input.value);isNaN(e)||(this._snapClampSetValue(e+t),this.$input.value=this.getValue())};this.$input.addEventListener("focus",()=>{this._inputFocused=!0}),this.$input.addEventListener("input",()=>{const t=parseFloat(this.$input.value);isNaN(t)||this.setValue(this._clamp(t))}),this.$input.addEventListener("blur",()=>{this._inputFocused=!1,this.updateDisplay()}),this.$input.addEventListener("keydown",e=>{"Enter"===e.code&&this.$input.blur(),"ArrowUp"===e.code&&(e.preventDefault(),t(this._step*this._arrowKeyMultiplier(e))),"ArrowDown"===e.code&&(e.preventDefault(),t(-1*this._step*this._arrowKeyMultiplier(e)))}),this.$input.addEventListener("wheel",e=>{this._inputFocused&&(e.preventDefault(),t(this._normalizeMouseWheel(e)*this._step))},{passive:!1})}_initSlider(){this._hasSlider=!0,this.$slider=document.createElement("div"),this.$slider.classList.add("slider"),this.$fill=document.createElement("div"),this.$fill.classList.add("fill"),this.$slider.appendChild(this.$fill),this.$widget.insertBefore(this.$slider,this.$input),this.domElement.classList.add("hasSlider");const t=t=>{const e=this.$slider.getBoundingClientRect();let i=(s=t,r=e.left,n=e.right,l=this._min,o=this._max,(s-r)/(n-r)*(o-l)+l);var s,r,n,l,o;this._snapClampSetValue(i)},e=e=>{t(e.clientX)},i=()=>{this._setActiveStyle(!1),window.removeEventListener("mousemove",e),window.removeEventListener("mouseup",i)};this.$slider.addEventListener("mousedown",s=>{t(s.clientX),this._setActiveStyle(!0),window.addEventListener("mousemove",e),window.addEventListener("mouseup",i)});let s,r,n=!1;const l=e=>{if(n){const i=e.touches[0].clientX-s,a=e.touches[0].clientY-r;Math.abs(i)>Math.abs(a)?(e.preventDefault(),t(e.touches[0].clientX),this._setActiveStyle(!0),n=!1):(window.removeEventListener("touchmove",l),window.removeEventListener("touchend",o))}else e.preventDefault(),t(e.touches[0].clientX)},o=()=>{this._setActiveStyle(!1),window.removeEventListener("touchmove",l),window.removeEventListener("touchend",o)};this.$slider.addEventListener("touchstart",e=>{e.touches.length>1||(this._hasScrollBar?(s=e.touches[0].clientX,r=e.touches[0].clientY,n=!0):(e.preventDefault(),t(e.touches[0].clientX),this._setActiveStyle(!0),n=!1),window.addEventListener("touchmove",l,{passive:!1}),window.addEventListener("touchend",o))});this.$slider.addEventListener("wheel",t=>{if(Math.abs(t.deltaX)<Math.abs(t.deltaY)&&this._hasScrollBar)return;t.preventDefault();const e=this._normalizeMouseWheel(t)*this._step;this._snapClampSetValue(this.getValue()+e)},{passive:!1})}_setActiveStyle(t){this.$slider.classList.toggle("active",t),document.body.classList.toggle("lil-gui-slider-active",t)}_getImplicitStep(){return this._hasMin&&this._hasMax?(this._max-this._min)/1e3:.1}_onUpdateMinMax(){!this._hasSlider&&this._hasMin&&this._hasMax&&(this._stepExplicit||this.step(this._getImplicitStep(),!1),this._initSlider(),this.updateDisplay())}_normalizeMouseWheel(t){let{deltaX:e,deltaY:i}=t;Math.floor(t.deltaY)!==t.deltaY&&t.wheelDelta&&(e=0,i=-t.wheelDelta/120);return e+-i}_arrowKeyMultiplier(t){return this._stepExplicit?t.shiftKey?10:1:t.shiftKey?100:t.altKey?1:10}_snap(t){const e=Math.round(t/this._step)*this._step;return parseFloat(e.toPrecision(15))}_clamp(t){const e=this._hasMin?this._min:-1/0,i=this._hasMax?this._max:1/0;return Math.max(e,Math.min(i,t))}_snapClampSetValue(t){this.setValue(this._clamp(this._snap(t)))}get _hasScrollBar(){const t=this.parent.root.$children;return t.scrollHeight>t.clientHeight}get _hasMin(){return void 0!==this._min}get _hasMax(){return void 0!==this._max}}class c extends t{constructor(t,e,i,s){super(t,e,i,"option"),this.$select=document.createElement("select"),this.$select.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this._values=Array.isArray(s)?s:Object.values(s),this._names=Array.isArray(s)?s:Object.keys(s),this._names.forEach(t=>{const e=document.createElement("option");e.innerHTML=t,this.$select.appendChild(e)}),this.$select.addEventListener("change",()=>{this.setValue(this._values[this.$select.selectedIndex])}),this.$select.addEventListener("focus",()=>{this.$display.classList.add("focus")}),this.$select.addEventListener("blur",()=>{this.$display.classList.remove("focus")}),this.$widget.appendChild(this.$select),this.$widget.appendChild(this.$display),this.$disable=this.$select,this.updateDisplay()}updateDisplay(){const t=this.getValue(),e=this._values.indexOf(t);return this.$select.selectedIndex=e,this.$display.innerHTML=-1===e?t:this._names[e],this}}class u extends t{constructor(t,e,i){super(t,e,i,"string"),this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$input.addEventListener("input",()=>{this.setValue(this.$input.value)}),this.$input.addEventListener("keydown",t=>{"Enter"===t.code&&this.$input.blur()}),this.$widget.appendChild(this.$input),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.value=this.getValue(),this}}let p=!1;class g{constructor({parent:t,autoPlace:e=void 0===t,touchStyles:i=!0,container:s,injectStyles:r=!0,title:n="Controls",width:l}={}){if(this.parent=t,this.root=t?t.root:this,this.children=[],this.controllers=[],this.folders=[],this._closed=!1,this.domElement=document.createElement("div"),this.domElement.classList.add("lil-gui"),this.$title=document.createElement("div"),this.$title.classList.add("title"),this.$title.setAttribute("role","button"),this.$title.setAttribute("aria-expanded",!0),this.$title.setAttribute("tabindex",0),this.$title.addEventListener("click",()=>this.openAnimated(this._closed)),this.$title.addEventListener("keydown",t=>{"Enter"!==t.code&&"Space"!==t.code||(t.preventDefault(),this.$title.click())}),this.$title.addEventListener("touchstart",()=>{}),this.$children=document.createElement("div"),this.$children.classList.add("children"),this.domElement.appendChild(this.$title),this.domElement.appendChild(this.$children),this.title(n),this.parent)return this.parent.children.push(this),this.parent.folders.push(this),void this.parent.$children.appendChild(this.domElement);this.domElement.classList.add("root"),!p&&r&&(!function(t){const e=document.createElement("style");e.innerHTML=t;const i=document.querySelector("head link[rel=stylesheet], head style");i?document.head.insertBefore(e,i):document.head.appendChild(e)}('.lil-gui{font-family:var(--font-family);font-size:var(--font-size);line-height:1;font-weight:normal;font-style:normal;text-align:left;background-color:var(--background-color);color:var(--text-color);user-select:none;-webkit-user-select:none;touch-action:manipulation;--background-color:#1f1f1f;--text-color:#ebebeb;--title-background-color:#111;--title-text-color:#ebebeb;--widget-color:#424242;--hover-color:#4f4f4f;--focus-color:#595959;--number-color:#2cc9ff;--string-color:#a2db3c;--font-size:11px;--input-font-size:11px;--font-family:-apple-system,BlinkMacSystemFont,"Lucida Grande","Segoe UI",Roboto,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";--font-family-mono:Menlo,Monaco,Consolas,"Droid Sans Mono",monospace,"Droid Sans Fallback";--padding:4px;--spacing:4px;--widget-height:20px;--name-width:45%;--slider-knob-width:2px;--slider-input-width:27%;--color-input-width:27%;--slider-input-min-width:45px;--color-input-min-width:45px;--folder-indent:7px;--widget-padding:0 0 0 3px;--widget-border-radius:2px;--checkbox-size:calc(.75*var(--widget-height));--scrollbar-width: 5px}.lil-gui,.lil-gui *{box-sizing:border-box;margin:0}.lil-gui.root{width:var(--width, 245px);display:flex;flex-direction:column}.lil-gui.root>.title{background:var(--title-background-color);color:var(--title-text-color)}.lil-gui.root>.children{overflow:auto}.lil-gui.root>.children::-webkit-scrollbar{width:var(--scrollbar-width);height:var(--scrollbar-width);background:var(--background-color)}.lil-gui.root>.children::-webkit-scrollbar-thumb{border-radius:var(--scrollbar-width);background:var(--focus-color)}.lil-gui .lil-gui{--background-color:inherit;--text-color:inherit;--title-background-color:inherit;--title-text-color:inherit;--widget-color:inherit;--hover-color:inherit;--focus-color:inherit;--number-color:inherit;--string-color:inherit;--font-size:inherit;--input-font-size:inherit;--font-family:inherit;--font-family-mono:inherit;--padding:inherit;--spacing:inherit;--widget-height:inherit;--name-width:inherit;--slider-knob-width:inherit;--slider-input-width:inherit;--color-input-width:inherit;--slider-input-min-width:inherit;--color-input-min-width:inherit;--folder-indent:inherit;--widget-padding:inherit;--widget-border-radius:inherit;--checkbox-size:inherit}@media(pointer: coarse){.lil-gui.allow-touch-styles{--widget-height: 28px;--padding: 6px;--spacing: 6px;--font-size: 13px;--input-font-size: 16px;--folder-indent: 10px;--widget-padding: 0 0 0 3px;--scrollbar-width: 7px;--slider-input-min-width: 50px;--color-input-min-width: 65px}}.lil-gui.force-touch-styles{--widget-height: 28px;--padding: 6px;--spacing: 6px;--font-size: 13px;--input-font-size: 16px;--folder-indent: 10px;--widget-padding: 0 0 0 3px;--scrollbar-width: 7px;--slider-input-min-width: 50px;--color-input-min-width: 65px}.lil-gui.autoPlace{max-height:100%;position:fixed;top:0;right:15px;z-index:1001}.lil-gui .controller{display:flex;align-items:center;padding:0 var(--padding);margin:var(--spacing) 0}.lil-gui .controller.disabled{opacity:.5}.lil-gui .controller.disabled,.lil-gui .controller.disabled *{pointer-events:none !important}.lil-gui .controller .name{min-width:var(--name-width);flex-shrink:0;white-space:pre;padding-right:var(--spacing);line-height:var(--widget-height)}.lil-gui .controller .widget{position:relative;display:flex;align-items:center;width:100%;min-height:var(--widget-height)}.lil-gui .controller.function .name{line-height:unset;padding:0}.lil-gui .controller.string input{color:var(--string-color)}.lil-gui .controller.boolean .widget{cursor:pointer}.lil-gui .controller.color .display{width:100%;height:var(--widget-height);border-radius:var(--widget-border-radius);position:relative}@media(hover: hover){.lil-gui .controller.color .display:hover:before{content:" ";display:block;position:absolute;border-radius:var(--widget-border-radius);border:1px solid #fff9;left:0;right:0;top:0;bottom:0}}.lil-gui .controller.color input[type=color]{opacity:0;width:100%;height:100%;cursor:pointer}.lil-gui .controller.color input[type=text]{margin-left:var(--spacing);font-family:var(--font-family-mono);min-width:var(--color-input-min-width);width:var(--color-input-width);flex-shrink:0}.lil-gui .controller.option select{opacity:0;position:absolute;width:100%;max-width:100%}.lil-gui .controller.option .display{position:relative;pointer-events:none;border-radius:var(--widget-border-radius);height:var(--widget-height);line-height:var(--widget-height);max-width:100%;overflow:hidden;word-break:break-all;padding-left:.55em;padding-right:1.75em;background:var(--widget-color)}@media(hover: hover){.lil-gui .controller.option .display.focus{background:var(--focus-color)}}.lil-gui .controller.option .display.active{background:var(--focus-color)}.lil-gui .controller.option .display:after{font-family:"lil-gui";content:"↕";position:absolute;top:0;right:0;bottom:0;padding-right:.375em}.lil-gui .controller.option .widget,.lil-gui .controller.option select{cursor:pointer}@media(hover: hover){.lil-gui .controller.option .widget:hover .display{background:var(--hover-color)}}.lil-gui .controller.number input{color:var(--number-color)}.lil-gui .controller.number.hasSlider input{margin-left:var(--spacing);width:var(--slider-input-width);min-width:var(--slider-input-min-width);flex-shrink:0}.lil-gui .controller.number .slider{width:100%;height:var(--widget-height);background-color:var(--widget-color);border-radius:var(--widget-border-radius);padding-right:var(--slider-knob-width);overflow:hidden;cursor:ew-resize;touch-action:pan-y}@media(hover: hover){.lil-gui .controller.number .slider:hover{background-color:var(--hover-color)}}.lil-gui .controller.number .slider.active{background-color:var(--focus-color)}.lil-gui .controller.number .slider.active .fill{opacity:.95}.lil-gui .controller.number .fill{height:100%;border-right:var(--slider-knob-width) solid var(--number-color);box-sizing:content-box}.lil-gui-slider-active .lil-gui{--hover-color: var(--widget-color)}.lil-gui-slider-active *{cursor:ew-resize !important}.lil-gui .title{--title-height: calc(var(--widget-height) + var(--spacing) * 1.25);height:var(--title-height);line-height:calc(var(--title-height) - 4px);font-weight:600;padding:0 var(--padding);-webkit-tap-highlight-color:transparent;cursor:pointer;outline:none;text-decoration-skip:objects}.lil-gui .title:before{font-family:"lil-gui";content:"▾";padding-right:2px;display:inline-block}.lil-gui .title:active{background:var(--title-background-color);opacity:.75}@media(hover: hover){.lil-gui .title:hover{background:var(--title-background-color);opacity:.85}.lil-gui .title:focus{text-decoration:underline var(--focus-color)}}.lil-gui.root>.title:focus{text-decoration:none !important}.lil-gui.closed>.title:before{content:"▸"}.lil-gui.closed>.children{transform:translateY(-7px);opacity:0}.lil-gui.closed:not(.transition)>.children{display:none}.lil-gui.transition>.children{transition-duration:300ms;transition-property:height,opacity,transform;transition-timing-function:cubic-bezier(0.215, 0.61, 0.355, 1);overflow:hidden;pointer-events:none}.lil-gui .children:empty:before{content:"Empty";padding:0 var(--padding);margin:var(--spacing) 0;display:block;height:var(--widget-height);font-style:italic;line-height:var(--widget-height);opacity:.5}.lil-gui.root>.children>.lil-gui>.title{border:0 solid var(--widget-color);border-width:1px 0;transition:border-color 300ms}.lil-gui.root>.children>.lil-gui.closed>.title{border-bottom-color:transparent}.lil-gui+.controller{border-top:1px solid var(--widget-color);margin-top:0;padding-top:var(--spacing)}.lil-gui .lil-gui .lil-gui>.title{border:none}.lil-gui .lil-gui .lil-gui>.children{border:none;margin-left:var(--folder-indent);border-left:2px solid var(--widget-color)}.lil-gui .lil-gui .controller{border:none}.lil-gui input{-webkit-tap-highlight-color:transparent;border:0;outline:none;font-family:var(--font-family);font-size:var(--input-font-size);border-radius:var(--widget-border-radius);height:var(--widget-height);background:var(--widget-color);color:var(--text-color);width:100%}@media(hover: hover){.lil-gui input:hover{background:var(--hover-color)}.lil-gui input:active{background:var(--focus-color)}}.lil-gui input[type=text]{padding:var(--widget-padding)}.lil-gui input[type=text]:focus{background:var(--focus-color)}.lil-gui input[type=checkbox]{appearance:none;-webkit-appearance:none;height:var(--checkbox-size);width:var(--checkbox-size);border-radius:var(--widget-border-radius);text-align:center}.lil-gui input[type=checkbox]:checked:before{font-family:"lil-gui";content:"✓";font-size:var(--checkbox-size);line-height:var(--checkbox-size)}@media(hover: hover){.lil-gui input[type=checkbox]:focus{box-shadow:inset 0 0 0 1px var(--focus-color)}}.lil-gui button{-webkit-tap-highlight-color:transparent;outline:none;cursor:pointer;font-family:var(--font-family);font-size:var(--font-size);color:var(--text-color);width:100%;height:var(--widget-height);text-transform:none;background:var(--widget-color);border-radius:var(--widget-border-radius);border:1px solid var(--widget-color);text-align:center;line-height:calc(var(--widget-height)*.725)}@media(hover: hover){.lil-gui button:hover{background:var(--hover-color);border-color:var(--hover-color)}.lil-gui button:focus{border-color:var(--focus-color)}}.lil-gui button:active{background:var(--focus-color)}@font-face{font-family:"lil-gui";src:url("data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAAUsAAsAAAAACJwAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAAH4AAADAImwmYE9TLzIAAAGIAAAAPwAAAGBKqH5SY21hcAAAAcgAAAD0AAACrukyyJBnbHlmAAACvAAAAF8AAACEIZ5WI2hlYWQAAAMcAAAAJwAAADZfcj23aGhlYQAAA0QAAAAYAAAAJAC5AHhobXR4AAADXAAAABAAAABMAZAAAGxvY2EAAANsAAAAFAAAACgCEgIybWF4cAAAA4AAAAAeAAAAIAEfABJuYW1lAAADoAAAASIAAAIK9SUU/XBvc3QAAATEAAAAZgAAAJCTcMc2eJxVjbEOgjAURU+hFRBK1dGRL+ALnAiToyMLEzFpnPz/eAshwSa97517c/MwwJmeB9kwPl+0cf5+uGPZXsqPu4nvZabcSZldZ6kfyWnomFY/eScKqZNWupKJO6kXN3K9uCVoL7iInPr1X5baXs3tjuMqCtzEuagm/AAlzQgPAAB4nGNgYRBlnMDAysDAYM/gBiT5oLQBAwuDJAMDEwMrMwNWEJDmmsJwgCFeXZghBcjlZMgFCzOiKOIFAB71Bb8AeJy1kjFuwkAQRZ+DwRAwBtNQRUGKQ8OdKCAWUhAgKLhIuAsVSpWz5Bbkj3dEgYiUIszqWdpZe+Z7/wB1oCYmIoboiwiLT2WjKl/jscrHfGg/pKdMkyklC5Zs2LEfHYpjcRoPzme9MWWmk3dWbK9ObkWkikOetJ554fWyoEsmdSlt+uR0pCJR34b6t/TVg1SY3sYvdf8vuiKrpyaDXDISiegp17p7579Gp3p++y7HPAiY9pmTibljrr85qSidtlg4+l25GLCaS8e6rRxNBmsnERunKbaOObRz7N72ju5vdAjYpBXHgJylOAVsMseDAPEP8LYoUHicY2BiAAEfhjAGJgZWBgZ7RnFRdnVJELCRlBSRlATJMoLV2DK4glSYs6ubq5vbKrJLSbGrgEmovDuDJVhe3VzcXFwNLCOILB/C4IuQ1xTn5FPilBTj5FPmBAB76woyAHicY2BkYGAA4sklsQ/j+W2+MnAzpDBgAyEMYUCSg4EJxAEAvVwFCgB4nGNgZGBgSGFggJMhDIwMqEAYAByHATJ4nGNgAIIUNEwmAABl3AGReJxjYAACIQYlBiMGJ3wQAEcQBEV4nGNgZGBgEGZgY2BiAAEQyQWEDAz/wXwGAAsPATIAAHicXdBNSsNAHAXwl35iA0UQXYnMShfS9GPZA7T7LgIu03SSpkwzYTIt1BN4Ak/gKTyAeCxfw39jZkjymzcvAwmAW/wgwHUEGDb36+jQQ3GXGot79L24jxCP4gHzF/EIr4jEIe7wxhOC3g2TMYy4Q7+Lu/SHuEd/ivt4wJd4wPxbPEKMX3GI5+DJFGaSn4qNzk8mcbKSR6xdXdhSzaOZJGtdapd4vVPbi6rP+cL7TGXOHtXKll4bY1Xl7EGnPtp7Xy2n00zyKLVHfkHBa4IcJ2oD3cgggWvt/V/FbDrUlEUJhTn/0azVWbNTNr0Ens8de1tceK9xZmfB1CPjOmPH4kitmvOubcNpmVTN3oFJyjzCvnmrwhJTzqzVj9jiSX911FjeAAB4nG3HMRKCMBBA0f0giiKi4DU8k0V2GWbIZDOh4PoWWvq6J5V8If9NVNQcaDhyouXMhY4rPTcG7jwYmXhKq8Wz+p762aNaeYXom2n3m2dLTVgsrCgFJ7OTmIkYbwIbC6vIB7WmFfAAAA==") format("woff")}'),p=!0),s?s.appendChild(this.domElement):e&&(this.domElement.classList.add("autoPlace"),document.body.appendChild(this.domElement)),i&&this.domElement.classList.add("allow-touch-styles"),l&&this.domElement.style.setProperty("--width",l+"px")}add(t,i,s,r,n){if(Object(s)===s)return new c(this,t,i,s);const l=t[i];switch(typeof l){case"number":return new d(this,t,i,s,r,n);case"boolean":return new e(this,t,i);case"string":return new u(this,t,i);case"function":return new h(this,t,i)}console.error(`Failed to add controller for "${i}"`,l,t)}addColor(t,e,i=1){return new a(this,t,e,i)}addFolder(t){return new g({parent:this,title:t})}load(t,e=!0){if(!("controllers"in t))throw new Error('Invalid load object. Should contain a "controllers" key.');return this.controllers.forEach(e=>{e instanceof h||e._name in t.controllers&&e.load(t.controllers[e._name])}),e&&t.folders&&this.folders.forEach(e=>{e._title in t.folders&&e.load(t.folders[e._title])}),this}save(t=!0){const e={controllers:{},folders:{}};return this.controllers.forEach(t=>{if(!(t instanceof h)){if(t._name in e.controllers)throw new Error(`Cannot save GUI with duplicate property "${t._name}"`);e.controllers[t._name]=t.save()}}),t&&this.folders.forEach(t=>{if(t._title in e.folders)throw new Error(`Cannot save GUI with duplicate folder "${t._title}"`);e.folders[t._title]=t.save()}),e}open(t=!0){return this._closed=!t,this.$title.setAttribute("aria-expanded",!this._closed),this.domElement.classList.toggle("closed",this._closed),this}close(){return this.open(!1)}openAnimated(t=!0){return this._closed=!t,this.$title.setAttribute("aria-expanded",!this._closed),requestAnimationFrame(()=>{const e=this.$children.clientHeight;this.$children.style.height=e+"px",this.domElement.classList.add("transition");const i=t=>{t.target===this.$children&&(this.$children.style.height="",this.domElement.classList.remove("transition"),this.$children.removeEventListener("transitionend",i))};this.$children.addEventListener("transitionend",i);const s=t?this.$children.scrollHeight:0;this.domElement.classList.toggle("closed",!t),requestAnimationFrame(()=>{this.$children.style.height=s+"px"})}),this}title(t){return this._title=t,this.$title.innerHTML=t,this}reset(t=!0){return(t?this.controllersRecursive():this.controllers).forEach(t=>t.reset()),this}onChange(t){return this._onChange=t,this}_callOnChange(t){this.parent&&this.parent._callOnChange(t),void 0!==this._onChange&&this._onChange.call(this,{object:t.object,property:t.property,value:t.getValue(),controller:t})}destroy(){this.parent&&(this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.folders.splice(this.parent.folders.indexOf(this),1)),this.domElement.parentElement&&this.domElement.parentElement.removeChild(this.domElement),Array.from(this.children).forEach(t=>t.destroy()),this._onResize&&window.removeEventListener("resize",this._onResize)}controllersRecursive(){let t=Array.from(this.controllers);return this.folders.forEach(e=>{t=t.concat(e.controllersRecursive())}),t}foldersRecursive(){let t=Array.from(this.folders);return this.folders.forEach(e=>{t=t.concat(e.foldersRecursive())}),t}}export default g;export{e as BooleanController,a as ColorController,t as Controller,h as FunctionController,g as GUI,d as NumberController,c as OptionController,u as StringController};
+class t{constructor(i,e,s,n,r="div"){this.parent=i,this.object=e,this.property=s,this._disabled=!1,this.initialValue=this.getValue(),this.domElement=document.createElement("div"),this.domElement.classList.add("controller"),this.domElement.classList.add(n),this.$name=document.createElement("div"),this.$name.classList.add("name"),t.nextNameID=t.nextNameID||0,this.$name.id="lil-gui-name-"+ ++t.nextNameID,this.$widget=document.createElement(r),this.$widget.classList.add("widget"),this.$disable=this.$widget,this.domElement.appendChild(this.$name),this.domElement.appendChild(this.$widget),this.parent.children.push(this),this.parent.controllers.push(this),this.parent.$children.appendChild(this.domElement),this._listenCallback=this._listenCallback.bind(this),this.name(s)}name(t){return this._name=t,this.$name.innerHTML=t,this}onChange(t){return this._onChange=t,this}_callOnChange(){this.parent._callOnChange(this),void 0!==this._onChange&&this._onChange.call(this,this.getValue()),this._changed=!0}onFinishChange(t){return this._onFinishChange=t,this}_callOnFinishChange(){this._changed&&(this.parent._callOnFinishChange(this),void 0!==this._onFinishChange&&this._onFinishChange.call(this,this.getValue())),this._changed=!1}reset(){return this.setValue(this.initialValue),this._callOnFinishChange(),this}enable(t=!0){return this.disable(!t)}disable(t=!0){return t===this._disabled||(this._disabled=t,this.domElement.classList.toggle("disabled",t),this.$disable.toggleAttribute("disabled",t)),this}options(t){const i=this.parent.add(this.object,this.property,t);return i.name(this._name),this.destroy(),i}min(t){return this}max(t){return this}step(t){return this}listen(t=!0){return this._listening=t,void 0!==this._listenCallbackID&&(cancelAnimationFrame(this._listenCallbackID),this._listenCallbackID=void 0),this._listening&&this._listenCallback(),this}_listenCallback(){this._listenCallbackID=requestAnimationFrame(this._listenCallback),this.updateDisplay()}getValue(){return this.object[this.property]}setValue(t){return this.object[this.property]=t,this._callOnChange(),this.updateDisplay(),this}updateDisplay(){return this}load(t){return this.setValue(t),this._callOnFinishChange(),this}save(){return this.getValue()}destroy(){this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.controllers.splice(this.parent.controllers.indexOf(this),1),this.parent.$children.removeChild(this.domElement)}}class i extends t{constructor(t,i,e){super(t,i,e,"boolean","label"),this.$input=document.createElement("input"),this.$input.setAttribute("type","checkbox"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$widget.appendChild(this.$input),this.$input.addEventListener("change",()=>{this.setValue(this.$input.checked),this._callOnFinishChange()}),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.checked=this.getValue(),this}}function e(t){let i,e;return(i=t.match(/(#|0x)?([a-f0-9]{6})/i))?e=i[2]:(i=t.match(/rgb\(\s*(\d*)\s*,\s*(\d*)\s*,\s*(\d*)\s*\)/))?e=parseInt(i[1]).toString(16).padStart(2,0)+parseInt(i[2]).toString(16).padStart(2,0)+parseInt(i[3]).toString(16).padStart(2,0):(i=t.match(/^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i))&&(e=i[1]+i[1]+i[2]+i[2]+i[3]+i[3]),!!e&&"#"+e}const s={isPrimitive:!0,match:t=>"string"==typeof t,fromHexString:e,toHexString:e},n={isPrimitive:!0,match:t=>"number"==typeof t,fromHexString:t=>parseInt(t.substring(1),16),toHexString:t=>"#"+t.toString(16).padStart(6,0)},r={isPrimitive:!1,match:Array.isArray,fromHexString(t,i,e=1){const s=n.fromHexString(t);i[0]=(s>>16&255)/255*e,i[1]=(s>>8&255)/255*e,i[2]=(255&s)/255*e},toHexString:([t,i,e],s=1)=>n.toHexString(t*(s=255/s)<<16^i*s<<8^e*s<<0)},l={isPrimitive:!1,match:t=>Object(t)===t,fromHexString(t,i,e=1){const s=n.fromHexString(t);i.r=(s>>16&255)/255*e,i.g=(s>>8&255)/255*e,i.b=(255&s)/255*e},toHexString:({r:t,g:i,b:e},s=1)=>n.toHexString(t*(s=255/s)<<16^i*s<<8^e*s<<0)},o=[s,n,r,l];class a extends t{constructor(t,i,s,n){var r;super(t,i,s,"color"),this.$input=document.createElement("input"),this.$input.setAttribute("type","color"),this.$input.setAttribute("tabindex",-1),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$text=document.createElement("input"),this.$text.setAttribute("type","text"),this.$text.setAttribute("spellcheck","false"),this.$text.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$display.appendChild(this.$input),this.$widget.appendChild(this.$display),this.$widget.appendChild(this.$text),this._format=(r=this.initialValue,o.find(t=>t.match(r))),this._rgbScale=n,this._initialValueHexString=this.save(),this._textFocused=!1,this.$input.addEventListener("input",()=>{this._setValueFromHexString(this.$input.value)}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$text.addEventListener("input",()=>{const t=e(this.$text.value);t&&this._setValueFromHexString(t)}),this.$text.addEventListener("focus",()=>{this._textFocused=!0,this.$text.select()}),this.$text.addEventListener("blur",()=>{this._textFocused=!1,this.updateDisplay(),this._callOnFinishChange()}),this.$disable=this.$text,this.updateDisplay()}reset(){return this._setValueFromHexString(this._initialValueHexString),this}_setValueFromHexString(t){if(this._format.isPrimitive){const i=this._format.fromHexString(t);this.setValue(i)}else this._format.fromHexString(t,this.getValue(),this._rgbScale),this._callOnChange(),this.updateDisplay()}save(){return this._format.toHexString(this.getValue(),this._rgbScale)}load(t){return this._setValueFromHexString(t),this._callOnFinishChange(),this}updateDisplay(){return this.$input.value=this._format.toHexString(this.getValue(),this._rgbScale),this._textFocused||(this.$text.value=this.$input.value.substring(1)),this.$display.style.backgroundColor=this.$input.value,this}}class h extends t{constructor(t,i,e){super(t,i,e,"function"),this.$button=document.createElement("button"),this.$button.appendChild(this.$name),this.$widget.appendChild(this.$button),this.$button.addEventListener("click",t=>{t.preventDefault(),this.getValue().call(this.object)}),this.$button.addEventListener("touchstart",()=>{}),this.$disable=this.$button}}class d extends t{constructor(t,i,e,s,n,r){super(t,i,e,"number"),this._initInput(),this.min(s),this.max(n);const l=void 0!==r;this.step(l?r:this._getImplicitStep(),l),this.updateDisplay()}min(t){return this._min=t,this._onUpdateMinMax(),this}max(t){return this._max=t,this._onUpdateMinMax(),this}step(t,i=!0){return this._step=t,this._stepExplicit=i,this}updateDisplay(){const t=this.getValue();if(this._hasSlider){let i=(t-this._min)/(this._max-this._min);i=Math.max(0,Math.min(i,1)),this.$fill.style.width=100*i+"%"}return this._inputFocused||(this.$input.value=t),this}_initInput(){this.$input=document.createElement("input"),this.$input.setAttribute("type","number"),this.$input.setAttribute("step","any"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$widget.appendChild(this.$input),this.$disable=this.$input;const t=t=>{const i=parseFloat(this.$input.value);isNaN(i)||(this._snapClampSetValue(i+t),this.$input.value=this.getValue())};let i,e,s,n,r,l=!1;const o=t=>{if(l){const s=t.clientX-i,n=t.clientY-e;Math.abs(n)>5?(t.preventDefault(),this.$input.blur(),l=!1,this._setDraggingStyle(!0,"vertical")):Math.abs(s)>5&&a()}if(!l){const i=t.clientY-s;r-=i*this._step*this._arrowKeyMultiplier(t),n+r>this._max?r=this._max-n:n+r<this._min&&(r=this._min-n),this._snapClampSetValue(n+r)}s=t.clientY},a=()=>{this._setDraggingStyle(!1,"vertical"),this._callOnFinishChange(),window.removeEventListener("mousemove",o),window.removeEventListener("mouseup",a)};this.$input.addEventListener("input",()=>{const t=parseFloat(this.$input.value);isNaN(t)||this.setValue(this._clamp(t))}),this.$input.addEventListener("keydown",i=>{"Enter"===i.code&&this.$input.blur(),"ArrowUp"===i.code&&(i.preventDefault(),t(this._step*this._arrowKeyMultiplier(i))),"ArrowDown"===i.code&&(i.preventDefault(),t(this._step*this._arrowKeyMultiplier(i)*-1))}),this.$input.addEventListener("wheel",i=>{this._inputFocused&&(i.preventDefault(),t(this._step*this._normalizeMouseWheel(i)))}),this.$input.addEventListener("mousedown",t=>{i=t.clientX,e=s=t.clientY,l=!0,n=this.getValue(),r=0,window.addEventListener("mousemove",o),window.addEventListener("mouseup",a)}),this.$input.addEventListener("focus",()=>{this._inputFocused=!0}),this.$input.addEventListener("blur",()=>{this._inputFocused=!1,this.updateDisplay(),this._callOnFinishChange()})}_initSlider(){this._hasSlider=!0,this.$slider=document.createElement("div"),this.$slider.classList.add("slider"),this.$fill=document.createElement("div"),this.$fill.classList.add("fill"),this.$slider.appendChild(this.$fill),this.$widget.insertBefore(this.$slider,this.$input),this.domElement.classList.add("hasSlider");const t=t=>{const i=this.$slider.getBoundingClientRect();let e=(s=t,n=i.left,r=i.right,l=this._min,o=this._max,(s-n)/(r-n)*(o-l)+l);var s,n,r,l,o;this._snapClampSetValue(e)},i=i=>{t(i.clientX)},e=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",e)};let s,n,r=!1;const l=i=>{i.preventDefault(),this._setDraggingStyle(!0),t(i.touches[0].clientX),r=!1},o=i=>{if(r){const t=i.touches[0].clientX-s,e=i.touches[0].clientY-n;Math.abs(t)>Math.abs(e)?l(i):(window.removeEventListener("touchmove",o),window.removeEventListener("touchend",a))}else i.preventDefault(),t(i.touches[0].clientX)},a=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("touchmove",o),window.removeEventListener("touchend",a)},h=this._callOnFinishChange.bind(this);let d;this.$slider.addEventListener("mousedown",s=>{this._setDraggingStyle(!0),t(s.clientX),window.addEventListener("mousemove",i),window.addEventListener("mouseup",e)}),this.$slider.addEventListener("touchstart",t=>{t.touches.length>1||(this._hasScrollBar?(s=t.touches[0].clientX,n=t.touches[0].clientY,r=!0):l(t),window.addEventListener("touchmove",o),window.addEventListener("touchend",a))}),this.$slider.addEventListener("wheel",t=>{if(Math.abs(t.deltaX)<Math.abs(t.deltaY)&&this._hasScrollBar)return;t.preventDefault();const i=this._normalizeMouseWheel(t)*this._step;this._snapClampSetValue(this.getValue()+i),this.$input.value=this.getValue(),clearTimeout(d),d=setTimeout(h,400)})}_setDraggingStyle(t,i="horizontal"){this.$slider&&this.$slider.classList.toggle("active",t),document.body.classList.toggle("lil-gui-dragging",t),document.body.classList.toggle("lil-gui-"+i,t)}_getImplicitStep(){return this._hasMin&&this._hasMax?(this._max-this._min)/1e3:.1}_onUpdateMinMax(){!this._hasSlider&&this._hasMin&&this._hasMax&&(this._stepExplicit||this.step(this._getImplicitStep(),!1),this._initSlider(),this.updateDisplay())}_normalizeMouseWheel(t){let{deltaX:i,deltaY:e}=t;Math.floor(t.deltaY)!==t.deltaY&&t.wheelDelta&&(i=0,e=-t.wheelDelta/120,e*=this._stepExplicit?1:10);return i+-e}_arrowKeyMultiplier(t){let i=this._stepExplicit?1:10;return t.shiftKey?i*=10:t.altKey&&(i/=10),i}_snap(t){const i=Math.round(t/this._step)*this._step;return parseFloat(i.toPrecision(15))}_clamp(t){return t<this._min&&(t=this._min),t>this._max&&(t=this._max),t}_snapClampSetValue(t){this.setValue(this._clamp(this._snap(t)))}get _hasScrollBar(){const t=this.parent.root.$children;return t.scrollHeight>t.clientHeight}get _hasMin(){return void 0!==this._min}get _hasMax(){return void 0!==this._max}}class c extends t{constructor(t,i,e,s){super(t,i,e,"option"),this.$select=document.createElement("select"),this.$select.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this._values=Array.isArray(s)?s:Object.values(s),this._names=Array.isArray(s)?s:Object.keys(s),this._names.forEach(t=>{const i=document.createElement("option");i.innerHTML=t,this.$select.appendChild(i)}),this.$select.addEventListener("change",()=>{this.setValue(this._values[this.$select.selectedIndex]),this._callOnFinishChange()}),this.$select.addEventListener("focus",()=>{this.$display.classList.add("focus")}),this.$select.addEventListener("blur",()=>{this.$display.classList.remove("focus")}),this.$widget.appendChild(this.$select),this.$widget.appendChild(this.$display),this.$disable=this.$select,this.updateDisplay()}updateDisplay(){const t=this.getValue(),i=this._values.indexOf(t);return this.$select.selectedIndex=i,this.$display.innerHTML=-1===i?t:this._names[i],this}}class u extends t{constructor(t,i,e){super(t,i,e,"string"),this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$input.addEventListener("input",()=>{this.setValue(this.$input.value)}),this.$input.addEventListener("keydown",t=>{"Enter"===t.code&&this.$input.blur()}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$widget.appendChild(this.$input),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.value=this.getValue(),this}}let p=!1;class g{constructor({parent:t,autoPlace:i=void 0===t,container:e,width:s,title:n="Controls",injectStyles:r=!0,touchStyles:l=!0}={}){if(this.parent=t,this.root=t?t.root:this,this.children=[],this.controllers=[],this.folders=[],this._closed=!1,this._hidden=!1,this.domElement=document.createElement("div"),this.domElement.classList.add("lil-gui"),this.$title=document.createElement("div"),this.$title.classList.add("title"),this.$title.setAttribute("role","button"),this.$title.setAttribute("aria-expanded",!0),this.$title.setAttribute("tabindex",0),this.$title.addEventListener("click",()=>this.openAnimated(this._closed)),this.$title.addEventListener("keydown",t=>{"Enter"!==t.code&&"Space"!==t.code||(t.preventDefault(),this.$title.click())}),this.$title.addEventListener("touchstart",()=>{}),this.$children=document.createElement("div"),this.$children.classList.add("children"),this.domElement.appendChild(this.$title),this.domElement.appendChild(this.$children),this.title(n),l&&this.domElement.classList.add("allow-touch-styles"),this.parent)return this.parent.children.push(this),this.parent.folders.push(this),void this.parent.$children.appendChild(this.domElement);this.domElement.classList.add("root"),!p&&r&&(!function(t){const i=document.createElement("style");i.innerHTML=t;const e=document.querySelector("head link[rel=stylesheet], head style");e?document.head.insertBefore(i,e):document.head.appendChild(i)}('.lil-gui{--background-color:#1f1f1f;--text-color:#ebebeb;--title-background-color:#111;--title-text-color:#ebebeb;--widget-color:#424242;--hover-color:#4f4f4f;--focus-color:#595959;--number-color:#2cc9ff;--string-color:#a2db3c;--font-size:11px;--input-font-size:11px;--font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif;--font-family-mono:Menlo,Monaco,Consolas,"Droid Sans Mono",monospace;--padding:4px;--spacing:4px;--widget-height:20px;--name-width:45%;--slider-knob-width:2px;--slider-input-width:27%;--color-input-width:27%;--slider-input-min-width:45px;--color-input-min-width:45px;--folder-indent:7px;--widget-padding:0 0 0 3px;--widget-border-radius:2px;--checkbox-size:calc(var(--widget-height)*0.75);--scrollbar-width:5px;background-color:var(--background-color);color:var(--text-color);font-family:var(--font-family);font-size:var(--font-size);font-style:normal;font-weight:400;line-height:1;text-align:left;touch-action:manipulation;user-select:none;-webkit-user-select:none}.lil-gui,.lil-gui *{box-sizing:border-box;margin:0;padding:0}.lil-gui.root{display:flex;flex-direction:column;width:var(--width,245px)}.lil-gui.root>.title{background:var(--title-background-color);color:var(--title-text-color)}.lil-gui.root>.children{overflow-x:hidden;overflow-y:auto}.lil-gui.root>.children::-webkit-scrollbar{background:var(--background-color);height:var(--scrollbar-width);width:var(--scrollbar-width)}.lil-gui.root>.children::-webkit-scrollbar-thumb{background:var(--focus-color);border-radius:var(--scrollbar-width)}.lil-gui.force-touch-styles{--widget-height:28px;--padding:6px;--spacing:6px;--font-size:13px;--input-font-size:16px;--folder-indent:10px;--scrollbar-width:7px;--slider-input-min-width:50px;--color-input-min-width:65px}.lil-gui.autoPlace{max-height:100%;position:fixed;right:15px;top:0;z-index:1001}.lil-gui .controller{align-items:center;display:flex;margin:var(--spacing) 0;padding:0 var(--padding)}.lil-gui .controller.disabled{opacity:.5}.lil-gui .controller.disabled,.lil-gui .controller.disabled *{pointer-events:none!important}.lil-gui .controller>.name{flex-shrink:0;line-height:var(--widget-height);min-width:var(--name-width);padding-right:var(--spacing);white-space:pre}.lil-gui .controller .widget{align-items:center;display:flex;min-height:var(--widget-height);position:relative;width:100%}.lil-gui .controller.string input{color:var(--string-color)}.lil-gui .controller.boolean .widget{cursor:pointer}.lil-gui .controller.color .display{border-radius:var(--widget-border-radius);height:var(--widget-height);position:relative;width:100%}.lil-gui .controller.color input[type=color]{cursor:pointer;height:100%;opacity:0;width:100%}.lil-gui .controller.color input[type=text]{flex-shrink:0;font-family:var(--font-family-mono);margin-left:var(--spacing);min-width:var(--color-input-min-width);width:var(--color-input-width)}.lil-gui .controller.option select{max-width:100%;opacity:0;position:absolute;width:100%}.lil-gui .controller.option .display{background:var(--widget-color);border-radius:var(--widget-border-radius);height:var(--widget-height);line-height:var(--widget-height);max-width:100%;overflow:hidden;padding-left:.55em;padding-right:1.75em;pointer-events:none;position:relative;word-break:break-all}.lil-gui .controller.option .display.active{background:var(--focus-color)}.lil-gui .controller.option .display:after{bottom:0;content:"↕";font-family:lil-gui;padding-right:.375em;position:absolute;right:0;top:0}.lil-gui .controller.option .widget,.lil-gui .controller.option select{cursor:pointer}.lil-gui .controller.number input{color:var(--number-color)}.lil-gui .controller.number.hasSlider input{flex-shrink:0;margin-left:var(--spacing);min-width:var(--slider-input-min-width);width:var(--slider-input-width)}.lil-gui .controller.number .slider{background-color:var(--widget-color);border-radius:var(--widget-border-radius);cursor:ew-resize;height:var(--widget-height);overflow:hidden;padding-right:var(--slider-knob-width);touch-action:pan-y;width:100%}.lil-gui .controller.number .slider.active{background-color:var(--focus-color)}.lil-gui .controller.number .slider.active .fill{opacity:.95}.lil-gui .controller.number .fill{border-right:var(--slider-knob-width) solid var(--number-color);box-sizing:content-box;height:100%}.lil-gui-dragging .lil-gui{--hover-color:var(--widget-color)}.lil-gui-dragging *{cursor:ew-resize!important}.lil-gui-dragging.lil-gui-vertical *{cursor:ns-resize!important}.lil-gui .title{--title-height:calc(var(--widget-height) + var(--spacing)*1.25);-webkit-tap-highlight-color:transparent;text-decoration-skip:objects;cursor:pointer;font-weight:600;height:var(--title-height);line-height:calc(var(--title-height) - 4px);outline:none;padding:0 var(--padding)}.lil-gui .title:before{content:"▾";display:inline-block;font-family:lil-gui;padding-right:2px}.lil-gui .title:active{background:var(--title-background-color);opacity:.75}.lil-gui.root>.title:focus{text-decoration:none!important}.lil-gui.closed>.title:before{content:"▸"}.lil-gui.closed>.children{opacity:0;transform:translateY(-7px)}.lil-gui.closed:not(.transition)>.children{display:none}.lil-gui.transition>.children{overflow:hidden;pointer-events:none;transition-duration:.3s;transition-property:height,opacity,transform;transition-timing-function:cubic-bezier(.2,.6,.35,1)}.lil-gui .children:empty:before{content:"Empty";display:block;font-style:italic;height:var(--widget-height);line-height:var(--widget-height);margin:var(--spacing) 0;opacity:.5;padding:0 var(--padding)}.lil-gui.root>.children>.lil-gui>.title{border-width:0;border-bottom:1px solid var(--widget-color);border-left:0 solid var(--widget-color);border-right:0 solid var(--widget-color);border-top:1px solid var(--widget-color);transition:border-color .3s}.lil-gui.root>.children>.lil-gui.closed>.title{border-bottom-color:transparent}.lil-gui+.controller{border-top:1px solid var(--widget-color);margin-top:0;padding-top:var(--spacing)}.lil-gui .lil-gui .lil-gui>.title{border:none}.lil-gui .lil-gui .lil-gui>.children{border:none;border-left:2px solid var(--widget-color);margin-left:var(--folder-indent)}.lil-gui .lil-gui .controller{border:none}.lil-gui input{-webkit-tap-highlight-color:transparent;background:var(--widget-color);border:0;border-radius:var(--widget-border-radius);color:var(--text-color);font-family:var(--font-family);font-size:var(--input-font-size);height:var(--widget-height);outline:none;width:100%}.lil-gui input:disabled{opacity:1}.lil-gui input[type=number],.lil-gui input[type=text]{padding:var(--widget-padding)}.lil-gui input[type=number]:focus,.lil-gui input[type=text]:focus{background:var(--focus-color)}.lil-gui input::-webkit-inner-spin-button,.lil-gui input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.lil-gui input[type=number]{-moz-appearance:textfield}.lil-gui input[type=checkbox]{appearance:none;-webkit-appearance:none;border-radius:var(--widget-border-radius);cursor:pointer;height:var(--checkbox-size);text-align:center;width:var(--checkbox-size)}.lil-gui input[type=checkbox]:checked:before{content:"✓";font-family:lil-gui;font-size:var(--checkbox-size);line-height:var(--checkbox-size)}.lil-gui button{-webkit-tap-highlight-color:transparent;background:var(--widget-color);border:1px solid var(--widget-color);border-radius:var(--widget-border-radius);color:var(--text-color);cursor:pointer;font-family:var(--font-family);font-size:var(--font-size);height:var(--widget-height);line-height:calc(var(--widget-height) - 4px);outline:none;text-align:center;text-transform:none;width:100%}.lil-gui button:active{background:var(--focus-color)}@font-face{font-family:lil-gui;src:url("data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAAUsAAsAAAAACJwAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAAH4AAADAImwmYE9TLzIAAAGIAAAAPwAAAGBKqH5SY21hcAAAAcgAAAD0AAACrukyyJBnbHlmAAACvAAAAF8AAACEIZpWH2hlYWQAAAMcAAAAJwAAADZfcj2zaGhlYQAAA0QAAAAYAAAAJAC5AHhobXR4AAADXAAAABAAAABMAZAAAGxvY2EAAANsAAAAFAAAACgCEgIybWF4cAAAA4AAAAAeAAAAIAEfABJuYW1lAAADoAAAASIAAAIK9SUU/XBvc3QAAATEAAAAZgAAAJCTcMc2eJxVjbEOgjAURU+hFRBK1dGRL+ALnAiToyMLEzFpnPz/eAshwSa97517c/MwwJmeB9kwPl+0cf5+uGPZXsqPu4nvZabcSZldZ6kfyWnomFY/eScKqZNWupKJO6kXN3K9uCVoL7iInPr1X5baXs3tjuMqCtzEuagm/AAlzQgPAAB4nGNgYRBlnMDAysDAYM/gBiT5oLQBAwuDJAMDEwMrMwNWEJDmmsJwgCFeXZghBcjlZMgFCzOiKOIFAB71Bb8AeJy1kjFuwkAQRZ+DwRAwBtNQRUGKQ8OdKCAWUhAgKLhIuAsVSpWz5Bbkj3dEgYiUIszqWdpZe+Z7/wB1oCYmIoboiwiLT2WjKl/jscrHfGg/pKdMkyklC5Zs2LEfHYpjcRoPzme9MWWmk3dWbK9ObkWkikOetJ554fWyoEsmdSlt+uR0pCJR34b6t/TVg1SY3sYvdf8vuiKrpyaDXDISiegp17p7579Gp3p++y7HPAiY9pmTibljrr85qSidtlg4+l25GLCaS8e6rRxNBmsnERunKbaOObRz7N72ju5vdAjYpBXHgJylOAVsMseDAPEP8LYoUHicY2BiAAEfhiAGJgZWBgZ7RnFRdnVJELCQlBSRlATJMoLV2DK4glSYs6ubq5vbKrJLSbGrgEmovDuDJVhe3VzcXFwNLCOILB/C4IuQ1xTn5FPilBTj5FPmBAB4WwoqAHicY2BkYGAA4sk1sR/j+W2+MnAzpDBgAyEMQUCSg4EJxAEAwUgFHgB4nGNgZGBgSGFggJMhDIwMqEAYAByHATJ4nGNgAIIUNEwmAABl3AGReJxjYAACIQYlBiMGJ3wQAEcQBEV4nGNgZGBgEGZgY2BiAAEQyQWEDAz/wXwGAAsPATIAAHicXdBNSsNAHAXwl35iA0UQXYnMShfS9GPZA7T7LgIu03SSpkwzYTIt1BN4Ak/gKTyAeCxfw39jZkjymzcvAwmAW/wgwHUEGDb36+jQQ3GXGot79L24jxCP4gHzF/EIr4jEIe7wxhOC3g2TMYy4Q7+Lu/SHuEd/ivt4wJd4wPxbPEKMX3GI5+DJFGaSn4qNzk8mcbKSR6xdXdhSzaOZJGtdapd4vVPbi6rP+cL7TGXOHtXKll4bY1Xl7EGnPtp7Xy2n00zyKLVHfkHBa4IcJ2oD3cgggWvt/V/FbDrUlEUJhTn/0azVWbNTNr0Ens8de1tceK9xZmfB1CPjOmPH4kitmvOubcNpmVTN3oFJyjzCvnmrwhJTzqzVj9jiSX911FjeAAB4nG3HMRKCMBBA0f0giiKi4DU8k0V2GWbIZDOh4PoWWvq6J5V8If9NVNQcaDhyouXMhY4rPTcG7jwYmXhKq8Wz+p762aNaeYXom2n3m2dLTVgsrCgFJ7OTmIkYbwIbC6vIB7WmFfAAAA==") format("woff")}@media (pointer:coarse){.lil-gui.allow-touch-styles{--widget-height:28px;--padding:6px;--spacing:6px;--font-size:13px;--input-font-size:16px;--folder-indent:10px;--scrollbar-width:7px;--slider-input-min-width:50px;--color-input-min-width:65px}}@media (hover:hover){.lil-gui .controller.color .display:hover:before{border:1px solid #fff9;border-radius:var(--widget-border-radius);bottom:0;content:" ";display:block;left:0;position:absolute;right:0;top:0}.lil-gui .controller.option .display.focus{background:var(--focus-color)}.lil-gui .controller.option .widget:hover .display{background:var(--hover-color)}.lil-gui .controller.number .slider:hover{background-color:var(--hover-color)}body:not(.lil-gui-dragging) .lil-gui .title:hover{background:var(--title-background-color);opacity:.85}.lil-gui .title:focus{text-decoration:underline var(--focus-color)}.lil-gui input:hover{background:var(--hover-color)}.lil-gui input:active{background:var(--focus-color)}.lil-gui input[type=checkbox]:focus{box-shadow:inset 0 0 0 1px var(--focus-color)}.lil-gui button:hover{background:var(--hover-color);border-color:var(--hover-color)}.lil-gui button:focus{border-color:var(--focus-color)}}'),p=!0),e?e.appendChild(this.domElement):i&&(this.domElement.classList.add("autoPlace"),document.body.appendChild(this.domElement)),s&&this.domElement.style.setProperty("--width",s+"px"),this.domElement.addEventListener("keydown",t=>t.stopPropagation()),this.domElement.addEventListener("keyup",t=>t.stopPropagation())}add(t,e,s,n,r){if(Object(s)===s)return new c(this,t,e,s);const l=t[e];switch(typeof l){case"number":return new d(this,t,e,s,n,r);case"boolean":return new i(this,t,e);case"string":return new u(this,t,e);case"function":return new h(this,t,e)}console.error("gui.add failed\n\tproperty:",e,"\n\tobject:",t,"\n\tvalue:",l)}addColor(t,i,e=1){return new a(this,t,i,e)}addFolder(t){return new g({parent:this,title:t})}load(t,i=!0){return t.controllers&&this.controllers.forEach(i=>{i instanceof h||i._name in t.controllers&&i.load(t.controllers[i._name])}),i&&t.folders&&this.folders.forEach(i=>{i._title in t.folders&&i.load(t.folders[i._title])}),this}save(t=!0){const i={controllers:{},folders:{}};return this.controllers.forEach(t=>{if(!(t instanceof h)){if(t._name in i.controllers)throw new Error(`Cannot save GUI with duplicate property "${t._name}"`);i.controllers[t._name]=t.save()}}),t&&this.folders.forEach(t=>{if(t._title in i.folders)throw new Error(`Cannot save GUI with duplicate folder "${t._title}"`);i.folders[t._title]=t.save()}),i}open(t=!0){return this._closed=!t,this.$title.setAttribute("aria-expanded",!this._closed),this.domElement.classList.toggle("closed",this._closed),this}close(){return this.open(!1)}show(t=!0){return this._hidden=!t,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}openAnimated(t=!0){return this._closed=!t,this.$title.setAttribute("aria-expanded",!this._closed),requestAnimationFrame(()=>{const i=this.$children.clientHeight;this.$children.style.height=i+"px",this.domElement.classList.add("transition");const e=t=>{t.target===this.$children&&(this.$children.style.height="",this.domElement.classList.remove("transition"),this.$children.removeEventListener("transitionend",e))};this.$children.addEventListener("transitionend",e);const s=t?this.$children.scrollHeight:0;this.domElement.classList.toggle("closed",!t),requestAnimationFrame(()=>{this.$children.style.height=s+"px"})}),this}title(t){return this._title=t,this.$title.innerHTML=t,this}reset(t=!0){return(t?this.controllersRecursive():this.controllers).forEach(t=>t.reset()),this}onChange(t){return this._onChange=t,this}_callOnChange(t){this.parent&&this.parent._callOnChange(t),void 0!==this._onChange&&this._onChange.call(this,{object:t.object,property:t.property,value:t.getValue(),controller:t})}onFinishChange(t){return this._onFinishChange=t,this}_callOnFinishChange(t){this.parent&&this.parent._callOnFinishChange(t),void 0!==this._onFinishChange&&this._onFinishChange.call(this,{object:t.object,property:t.property,value:t.getValue(),controller:t})}destroy(){this.parent&&(this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.folders.splice(this.parent.folders.indexOf(this),1)),this.domElement.parentElement&&this.domElement.parentElement.removeChild(this.domElement),Array.from(this.children).forEach(t=>t.destroy())}controllersRecursive(){let t=Array.from(this.controllers);return this.folders.forEach(i=>{t=t.concat(i.controllersRecursive())}),t}foldersRecursive(){let t=Array.from(this.folders);return this.folders.forEach(i=>{t=t.concat(i.foldersRecursive())}),t}}export default g;export{i as BooleanController,a as ColorController,t as Controller,h as FunctionController,g as GUI,d as NumberController,c as OptionController,u as StringController};

examples/jsm/loaders/BasisTextureLoader.js

@@ -48,6 +48,13 @@
this.workerSourceURL = '';
this.workerConfig = null;
+ console.warn(
+
+ 'THREE.BasisTextureLoader: This loader is deprecated, and will be removed in a future release. '
+ + 'Instead, use Basis Universal compression in KTX2 (.ktx2) files with THREE.KTX2Loader.'
+
+ );
+
}
setTranscoderPath( path ) {

examples/jsm/loaders/EXRLoader.js

@@ -230,7 +230,7 @@
if ( p.value - inOffset.value > ni ) {
- throw 'Something wrong with hufUnpackEncTable';
+ throw new Error( 'Something wrong with hufUnpackEncTable' );
}
@@ -242,7 +242,7 @@
if ( im + zerun > iM + 1 ) {
- throw 'Something wrong with hufUnpackEncTable';
+ throw new Error( 'Something wrong with hufUnpackEncTable' );
}
@@ -256,7 +256,7 @@
if ( im + zerun > iM + 1 ) {
- throw 'Something wrong with hufUnpackEncTable';
+ throw new Error( 'Something wrong with hufUnpackEncTable' );
}
@@ -293,7 +293,7 @@
if ( c >> l ) {
- throw 'Invalid table entry';
+ throw new Error( 'Invalid table entry' );
}
@@ -303,7 +303,7 @@
if ( pl.len ) {
- throw 'Invalid table entry';
+ throw new Error( 'Invalid table entry' );
}
@@ -338,7 +338,7 @@
if ( pl.len || pl.p ) {
- throw 'Invalid table entry';
+ throw new Error( 'Invalid table entry' );
}
@@ -626,7 +626,7 @@
if ( ! pl.p ) {
- throw 'hufDecode issues';
+ throw new Error( 'hufDecode issues' );
}
@@ -666,7 +666,7 @@
if ( j == pl.lit ) {
- throw 'hufDecode issues';
+ throw new Error( 'hufDecode issues' );
}
@@ -696,7 +696,7 @@
} else {
- throw 'hufDecode issues';
+ throw new Error( 'hufDecode issues' );
}
@@ -722,7 +722,7 @@
if ( im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE ) {
- throw 'Something wrong with HUF_ENCSIZE';
+ throw new Error( 'Something wrong with HUF_ENCSIZE' );
}
@@ -737,7 +737,7 @@
if ( nBits > 8 * ( nCompressed - ( inOffset.value - initialInOffset ) ) ) {
- throw 'Something wrong with hufUncompress';
+ throw new Error( 'Something wrong with hufUncompress' );
}
@@ -1299,7 +1299,7 @@
if ( maxNonZero >= BITMAP_SIZE ) {
- throw 'Something is wrong with PIZ_COMPRESSION BITMAP_SIZE';
+ throw new Error( 'Something is wrong with PIZ_COMPRESSION BITMAP_SIZE' );
}
@@ -1470,7 +1470,7 @@
};
if ( dwaHeader.version < 2 )
- throw 'EXRLoader.parse: ' + EXRHeader.compression + ' version ' + dwaHeader.version + ' is unsupported';
+ throw new Error( 'EXRLoader.parse: ' + EXRHeader.compression + ' version ' + dwaHeader.version + ' is unsupported' );
// Read channel ruleset information
var channelRules = new Array();
@@ -1655,7 +1655,7 @@
case LOSSY_DCT: // skip
default:
- throw 'EXRLoader.parse: unsupported channel compression';
+ throw new Error( 'EXRLoader.parse: unsupported channel compression' );
}
@@ -1756,15 +1756,25 @@
}
- function parseInt64( dataView, offset ) {
+ const parseInt64 = function ( dataView, offset ) {
- var int = Number( dataView.getBigInt64( offset.value, true ) );
+ let int;
+
+ if ( 'getBigInt64' in DataView.prototype ) {
+
+ int = Number( dataView.getBigInt64( offset.value, true ) );
+
+ } else {
+
+ int = dataView.getUint32( offset.value + 4, true ) + Number( dataView.getUint32( offset.value, true ) << 32 );
+
+ }
offset.value += ULONG_SIZE;
return int;
- }
+ };
function parseFloat32( dataView, offset ) {
@@ -1992,18 +2002,21 @@
const EXRHeader = {};
- if ( dataView.getUint32( 0, true ) != 20000630 ) // magic
- throw 'THREE.EXRLoader: provided file doesn\'t appear to be in OpenEXR format.';
+ if ( dataView.getUint32( 0, true ) != 20000630 ) { // magic
+
+ throw new Error( 'THREE.EXRLoader: provided file doesn\'t appear to be in OpenEXR format.' );
+
+ }
- EXRHeader.version = dataView.getUint8( 4, true );
+ EXRHeader.version = dataView.getUint8( 4 );
- const spec = dataView.getUint8( 5, true ); // fullMask
+ const spec = dataView.getUint8( 5 ); // fullMask
EXRHeader.spec = {
- singleTile: !! ( spec & 1 ),
- longName: !! ( spec & 2 ),
- deepFormat: !! ( spec & 4 ),
- multiPart: !! ( spec & 8 ),
+ singleTile: !! ( spec & 2 ),
+ longName: !! ( spec & 4 ),
+ deepFormat: !! ( spec & 8 ),
+ multiPart: !! ( spec & 16 ),
};
// start of header
@@ -2043,7 +2056,7 @@
if ( spec != 0 ) {
console.error( 'EXRHeader:', EXRHeader );
- throw 'THREE.EXRLoader: provided file is currently unsupported.';
+ throw new Error( 'THREE.EXRLoader: provided file is currently unsupported.' );
}
@@ -2114,7 +2127,7 @@
break;
default:
- throw 'EXRLoader.parse: ' + EXRHeader.compression + ' is unsupported';
+ throw new Error( 'EXRLoader.parse: ' + EXRHeader.compression + ' is unsupported' );
}
@@ -2155,7 +2168,7 @@
} else {
- throw 'EXRLoader.parse: unsupported pixelType ' + EXRDecoder.type + ' for ' + EXRHeader.compression + '.';
+ throw new Error( 'EXRLoader.parse: unsupported pixelType ' + EXRDecoder.type + ' for ' + EXRHeader.compression + '.' );
}

examples/jsm/loaders/GLTFLoader.js

@@ -47,7 +47,6 @@
PropertyBinding,
Quaternion,
QuaternionKeyframeTrack,
- RGBFormat,
RepeatWrapping,
Skeleton,
SkinnedMesh,
@@ -1478,7 +1477,6 @@
'vec3 specularFactor = specular;',
'#ifdef USE_SPECULARMAP',
' vec4 texelSpecular = texture2D( specularMap, vUv );',
- ' texelSpecular = sRGBToLinear( texelSpecular );',
' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
' specularFactor *= texelSpecular.rgb;',
'#endif'
@@ -2253,7 +2251,7 @@
// Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
// expensive work of uploading a texture to the GPU off the main thread.
- if ( typeof createImageBitmap !== 'undefined' && /Firefox|Safari/.test( navigator.userAgent ) === false ) {
+ if ( typeof createImageBitmap !== 'undefined' && /Firefox|^((?!chrome|android).)*safari/i.test( navigator.userAgent ) === false ) {
this.textureLoader = new ImageBitmapLoader( this.options.manager );
@@ -3179,8 +3177,8 @@
} else {
- materialParams.format = RGBFormat;
materialParams.transparent = false;
+ materialParams.alphaWrite = false;
if ( alphaMode === ALPHA_MODES.MASK ) {

examples/jsm/loaders/HDRCubeTextureLoader.js

@@ -6,8 +6,7 @@
HalfFloatType,
LinearEncoding,
LinearFilter,
- Loader,
- RGBFormat
+ Loader
} from 'three';
import { RGBELoader } from '../loaders/RGBELoader.js';
@@ -46,7 +45,6 @@
case FloatType:
texture.encoding = LinearEncoding;
- texture.format = RGBFormat;
texture.minFilter = LinearFilter;
texture.magFilter = LinearFilter;
texture.generateMipmaps = false;
@@ -55,7 +53,6 @@
case HalfFloatType:
texture.encoding = LinearEncoding;
- texture.format = RGBFormat;
texture.minFilter = LinearFilter;
texture.magFilter = LinearFilter;
texture.generateMipmaps = false;

examples/jsm/loaders/LDrawLoader.js

@@ -13,7 +13,8 @@
ShaderMaterial,
UniformsLib,
UniformsUtils,
- Vector3
+ Vector3,
+ Ray
} from 'three';
// Special surface finish tag types.
@@ -35,6 +36,9 @@
const FILE_LOCATION_TRY_ABSOLUTE = 5;
const FILE_LOCATION_NOT_FOUND = 6;
+const MAIN_COLOUR_CODE = '16';
+const MAIN_EDGE_COLOUR_CODE = '24';
+
const _tempVec0 = new Vector3();
const _tempVec1 = new Vector3();
@@ -167,16 +171,56 @@
}
-function smoothNormals( faces, lineSegments ) {
+class ConditionalLineSegments extends LineSegments {
+
+ constructor( geometry, material ) {
+
+ super( geometry, material );
+ this.isConditionalLine = true;
+
+ }
+
+}
+
+function generateFaceNormals( faces ) {
+
+ for ( let i = 0, l = faces.length; i < l; i ++ ) {
+
+ const face = faces[ i ];
+ const vertices = face.vertices;
+ const v0 = vertices[ 0 ];
+ const v1 = vertices[ 1 ];
+ const v2 = vertices[ 2 ];
+
+ _tempVec0.subVectors( v1, v0 );
+ _tempVec1.subVectors( v2, v1 );
+ face.faceNormal = new Vector3()
+ .crossVectors( _tempVec0, _tempVec1 )
+ .normalize();
+
+ }
+
+}
+
+const _ray = new Ray();
+function smoothNormals( faces, lineSegments, checkSubSegments = false ) {
+
+ // NOTE: 1e2 is pretty coarse but was chosen to quantize the resulting value because
+ // it allows edges to be smoothed as expected (see minifig arms).
+ // --
+ // And the vector values are initialize multiplied by 1 + 1e-10 to account for floating
+ // point errors on vertices along quantization boundaries. Ie after matrix multiplication
+ // vertices that should be merged might be set to "1.7" and "1.6999..." meaning they won't
+ // get merged. This added epsilon attempts to push these error values to the same quantized
+ // value for the sake of hashing. See "AT-ST mini" dishes. See mrdoob/three#23169.
+ const hashMultiplier = ( 1 + 1e-10 ) * 1e2;
function hashVertex( v ) {
- // NOTE: 1e2 is pretty coarse but was chosen because it allows edges
- // to be smoothed as expected (see minifig arms). The errors between edges
- // could be due to matrix multiplication.
- const x = ~ ~ ( v.x * 1e2 );
- const y = ~ ~ ( v.y * 1e2 );
- const z = ~ ~ ( v.z * 1e2 );
+ const x = ~ ~ ( v.x * hashMultiplier );
+ const y = ~ ~ ( v.y * hashMultiplier );
+ const z = ~ ~ ( v.z * hashMultiplier );
+
return `${ x },${ y },${ z }`;
}
@@ -187,7 +231,27 @@
}
+ // converts the two vertices to a ray with a normalized direction and origin of 0, 0, 0 projected
+ // onto the original line.
+ function toNormalizedRay( v0, v1, targetRay ) {
+
+ targetRay.direction.subVectors( v1, v0 ).normalize();
+
+ const scalar = v0.dot( targetRay.direction );
+ targetRay.origin.copy( v0 ).addScaledVector( targetRay.direction, - scalar );
+
+ return targetRay;
+
+ }
+
+ function hashRay( ray ) {
+
+ return hashEdge( ray.origin, ray.direction );
+
+ }
+
const hardEdges = new Set();
+ const hardEdgeRays = new Map();
const halfEdgeList = {};
const normals = [];
@@ -201,6 +265,43 @@
hardEdges.add( hashEdge( v0, v1 ) );
hardEdges.add( hashEdge( v1, v0 ) );
+ // only generate the hard edge ray map if we're checking subsegments because it's more expensive to check
+ // and requires more memory.
+ if ( checkSubSegments ) {
+
+ // add both ray directions to the map
+ const ray = toNormalizedRay( v0, v1, new Ray() );
+ const rh1 = hashRay( ray );
+ if ( ! hardEdgeRays.has( rh1 ) ) {
+
+ toNormalizedRay( v1, v0, ray );
+ const rh2 = hashRay( ray );
+
+ const info = {
+ ray,
+ distances: [],
+ };
+
+ hardEdgeRays.set( rh1, info );
+ hardEdgeRays.set( rh2, info );
+
+ }
+
+ // store both segments ends in min, max order in the distances array to check if a face edge is a
+ // subsegment later.
+ const info = hardEdgeRays.get( rh1 );
+ let d0 = info.ray.direction.dot( v0 );
+ let d1 = info.ray.direction.dot( v1 );
+ if ( d0 > d1 ) {
+
+ [ d0, d1 ] = [ d1, d0 ];
+
+ }
+
+ info.distances.push( d0, d1 );
+
+ }
+
}
// track the half edges associated with each triangle
@@ -218,7 +319,53 @@
const hash = hashEdge( v0, v1 );
// don't add the triangle if the edge is supposed to be hard
- if ( hardEdges.has( hash ) ) continue;
+ if ( hardEdges.has( hash ) ) {
+
+ continue;
+
+ }
+
+ // if checking subsegments then check to see if this edge lies on a hard edge ray and whether its within any ray bounds
+ if ( checkSubSegments ) {
+
+ toNormalizedRay( v0, v1, _ray );
+
+ const rayHash = hashRay( _ray );
+ if ( hardEdgeRays.has( rayHash ) ) {
+
+ const info = hardEdgeRays.get( rayHash );
+ const { ray, distances } = info;
+ let d0 = ray.direction.dot( v0 );
+ let d1 = ray.direction.dot( v1 );
+
+ if ( d0 > d1 ) {
+
+ [ d0, d1 ] = [ d1, d0 ];
+
+ }
+
+ // return early if the face edge is found to be a subsegment of a line edge meaning the edge will have "hard" normals
+ let found = false;
+ for ( let i = 0, l = distances.length; i < l; i += 2 ) {
+
+ if ( d0 >= distances[ i ] && d1 <= distances[ i + 1 ] ) {
+
+ found = true;
+ break;
+
+ }
+
+ }
+
+ if ( found ) {
+
+ continue;
+
+ }
+
+ }
+
+ }
const info = {
index: index,
@@ -389,13 +536,7 @@
function isPartType( type ) {
- return type === 'Part';
-
-}
-
-function isModelType( type ) {
-
- return type === 'Model' || type === 'Unofficial_Model';
+ return type === 'Part' || type === 'Unofficial_Part';
}
@@ -462,6 +603,12 @@
}
+ getVector() {
+
+ return new Vector3( parseFloat( this.getToken() ), parseFloat( this.getToken() ), parseFloat( this.getToken() ) );
+
+ }
+
getRemainingString() {
return this.line.substring( this.currentCharIndex, this.lineLength );
@@ -488,31 +635,69 @@
}
-class LDrawFileCache {
+// Fetches and parses an intermediate representation of LDraw parts files.
+class LDrawParsedCache {
constructor( loader ) {
- this.cache = {};
this.loader = loader;
+ this._cache = {};
}
- setData( key, contents ) {
+ cloneResult( original ) {
- this.cache[ key.toLowerCase() ] = contents;
+ const result = {};
- }
+ // vertices are transformed and normals computed before being converted to geometry
+ // so these pieces must be cloned.
+ result.faces = original.faces.map( face => {
- async loadData( fileName ) {
+ return {
+ colorCode: face.colorCode,
+ material: face.material,
+ vertices: face.vertices.map( v => v.clone() ),
+ normals: face.normals.map( () => null ),
+ faceNormal: null
+ };
- const key = fileName.toLowerCase();
- if ( key in this.cache ) {
+ } );
- return this.cache[ key ];
+ result.conditionalSegments = original.conditionalSegments.map( face => {
+
+ return {
+ colorCode: face.colorCode,
+ material: face.material,
+ vertices: face.vertices.map( v => v.clone() ),
+ controlPoints: face.controlPoints.map( v => v.clone() )
+ };
+
+ } );
+
+ result.lineSegments = original.lineSegments.map( face => {
+
+ return {
+ colorCode: face.colorCode,
+ material: face.material,
+ vertices: face.vertices.map( v => v.clone() )
+ };
+
+ } );
+
+ // none if this is subsequently modified
+ result.type = original.type;
+ result.category = original.category;
+ result.keywords = original.keywords;
+ result.subobjects = original.subobjects;
+ result.totalFaces = original.totalFaces;
+ result.startingConstructionStep = original.startingConstructionStep;
+ result.materials = original.materials;
+ result.group = null;
+ return result;
}
- this.cache[ fileName ] = new Promise( async ( resolve, reject ) => {
+ async fetchData( fileName ) {
let triedLowerCase = false;
let locationState = FILE_LOCATION_AS_IS;
@@ -575,9 +760,7 @@
try {
const text = await fileLoader.loadAsync( subobjectURL );
- this.setData( fileName, text );
- resolve( text );
- return;
+ return text;
} catch {
@@ -587,1468 +770,1639 @@
}
- reject();
+ throw new Error( 'LDrawLoader: Subobject "' + fileName + '" could not be loaded.' );
- } );
+ }
- return this.cache[ fileName ];
+ parse( text, fileName = null ) {
- }
+ const loader = this.loader;
-}
+ // final results
+ const faces = [];
+ const lineSegments = [];
+ const conditionalSegments = [];
+ const subobjects = [];
+ const materials = {};
-function sortByMaterial( a, b ) {
+ const getLocalMaterial = colorCode => {
- if ( a.colourCode === b.colourCode ) {
+ return materials[ colorCode ] || null;
- return 0;
+ };
- }
+ let type = 'Model';
+ let category = null;
+ let keywords = null;
+ let totalFaces = 0;
- if ( a.colourCode < b.colourCode ) {
+ // split into lines
+ if ( text.indexOf( '\r\n' ) !== - 1 ) {
- return - 1;
+ // This is faster than String.split with regex that splits on both
+ text = text.replace( /\r\n/g, '\n' );
}
- return 1;
+ const lines = text.split( '\n' );
+ const numLines = lines.length;
-}
+ let parsingEmbeddedFiles = false;
+ let currentEmbeddedFileName = null;
+ let currentEmbeddedText = null;
-function createObject( elements, elementSize, isConditionalSegments = false, totalElements = null ) {
+ let bfcCertified = false;
+ let bfcCCW = true;
+ let bfcInverted = false;
+ let bfcCull = true;
- // Creates a LineSegments (elementSize = 2) or a Mesh (elementSize = 3 )
- // With per face / segment material, implemented with mesh groups and materials array
+ let startingConstructionStep = false;
- // Sort the faces or line segments by colour code to make later the mesh groups
- elements.sort( sortByMaterial );
+ // Parse all line commands
+ for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
- if ( totalElements === null ) {
+ const line = lines[ lineIndex ];
- totalElements = elements.length;
+ if ( line.length === 0 ) continue;
- }
+ if ( parsingEmbeddedFiles ) {
- const positions = new Float32Array( elementSize * totalElements * 3 );
- const normals = elementSize === 3 ? new Float32Array( elementSize * totalElements * 3 ) : null;
- const materials = [];
+ if ( line.startsWith( '0 FILE ' ) ) {
- const quadArray = new Array( 6 );
- const bufferGeometry = new BufferGeometry();
- let prevMaterial = null;
- let index0 = 0;
- let numGroupVerts = 0;
- let offset = 0;
+ // Save previous embedded file in the cache
+ this.setData( currentEmbeddedFileName, currentEmbeddedText );
- for ( let iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
+ // New embedded text file
+ currentEmbeddedFileName = line.substring( 7 );
+ currentEmbeddedText = '';
- const elem = elements[ iElem ];
- let vertices = elem.vertices;
- if ( vertices.length === 4 ) {
+ } else {
- quadArray[ 0 ] = vertices[ 0 ];
- quadArray[ 1 ] = vertices[ 1 ];
- quadArray[ 2 ] = vertices[ 2 ];
- quadArray[ 3 ] = vertices[ 0 ];
- quadArray[ 4 ] = vertices[ 2 ];
- quadArray[ 5 ] = vertices[ 3 ];
- vertices = quadArray;
+ currentEmbeddedText += line + '\n';
}
- for ( let j = 0, l = vertices.length; j < l; j ++ ) {
-
- const v = vertices[ j ];
- const index = offset + j * 3;
- positions[ index + 0 ] = v.x;
- positions[ index + 1 ] = v.y;
- positions[ index + 2 ] = v.z;
+ continue;
}
- if ( elementSize === 3 ) {
+ const lp = new LineParser( line, lineIndex + 1 );
+ lp.seekNonSpace();
- let elemNormals = elem.normals;
- if ( elemNormals.length === 4 ) {
+ if ( lp.isAtTheEnd() ) {
- quadArray[ 0 ] = elemNormals[ 0 ];
- quadArray[ 1 ] = elemNormals[ 1 ];
- quadArray[ 2 ] = elemNormals[ 2 ];
- quadArray[ 3 ] = elemNormals[ 0 ];
- quadArray[ 4 ] = elemNormals[ 2 ];
- quadArray[ 5 ] = elemNormals[ 3 ];
- elemNormals = quadArray;
+ // Empty line
+ continue;
}
- for ( let j = 0, l = elemNormals.length; j < l; j ++ ) {
-
- let n = elem.faceNormal;
- if ( elemNormals[ j ] ) {
+ // Parse the line type
+ const lineType = lp.getToken();
- n = elemNormals[ j ].norm;
+ let material;
+ let colorCode;
+ let segment;
+ let ccw;
+ let doubleSided;
+ let v0, v1, v2, v3, c0, c1;
- }
+ switch ( lineType ) {
- const index = offset + j * 3;
- normals[ index + 0 ] = n.x;
- normals[ index + 1 ] = n.y;
- normals[ index + 2 ] = n.z;
+ // Line type 0: Comment or META
+ case '0':
- }
+ // Parse meta directive
+ const meta = lp.getToken();
- }
+ if ( meta ) {
- if ( prevMaterial !== elem.material ) {
+ switch ( meta ) {
- if ( prevMaterial !== null ) {
+ case '!LDRAW_ORG':
- bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
+ type = lp.getToken();
+ break;
- }
+ case '!COLOUR':
- materials.push( elem.material );
+ material = loader.parseColorMetaDirective( lp );
+ if ( material ) {
- prevMaterial = elem.material;
- index0 = offset / 3;
- numGroupVerts = vertices.length;
+ materials[ material.userData.code ] = material;
} else {
- numGroupVerts += vertices.length;
+ console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
}
- offset += 3 * vertices.length;
-
- }
+ break;
- if ( numGroupVerts > 0 ) {
+ case '!CATEGORY':
- bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
+ category = lp.getToken();
+ break;
- }
+ case '!KEYWORDS':
- bufferGeometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
+ const newKeywords = lp.getRemainingString().split( ',' );
+ if ( newKeywords.length > 0 ) {
- if ( normals !== null ) {
+ if ( ! keywords ) {
- bufferGeometry.setAttribute( 'normal', new BufferAttribute( normals, 3 ) );
+ keywords = [];
}
- let object3d = null;
+ newKeywords.forEach( function ( keyword ) {
- if ( elementSize === 2 ) {
+ keywords.push( keyword.trim() );
- object3d = new LineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
+ } );
- } else if ( elementSize === 3 ) {
+ }
- object3d = new Mesh( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
+ break;
- }
+ case 'FILE':
- if ( isConditionalSegments ) {
+ if ( lineIndex > 0 ) {
- object3d.isConditionalLine = true;
+ // Start embedded text files parsing
+ parsingEmbeddedFiles = true;
+ currentEmbeddedFileName = lp.getRemainingString();
+ currentEmbeddedText = '';
- const controlArray0 = new Float32Array( elements.length * 3 * 2 );
- const controlArray1 = new Float32Array( elements.length * 3 * 2 );
- const directionArray = new Float32Array( elements.length * 3 * 2 );
- for ( let i = 0, l = elements.length; i < l; i ++ ) {
+ bfcCertified = false;
+ bfcCCW = true;
- const os = elements[ i ];
- const vertices = os.vertices;
- const controlPoints = os.controlPoints;
- const c0 = controlPoints[ 0 ];
- const c1 = controlPoints[ 1 ];
- const v0 = vertices[ 0 ];
- const v1 = vertices[ 1 ];
- const index = i * 3 * 2;
- controlArray0[ index + 0 ] = c0.x;
- controlArray0[ index + 1 ] = c0.y;
- controlArray0[ index + 2 ] = c0.z;
- controlArray0[ index + 3 ] = c0.x;
- controlArray0[ index + 4 ] = c0.y;
- controlArray0[ index + 5 ] = c0.z;
+ }
- controlArray1[ index + 0 ] = c1.x;
- controlArray1[ index + 1 ] = c1.y;
- controlArray1[ index + 2 ] = c1.z;
- controlArray1[ index + 3 ] = c1.x;
- controlArray1[ index + 4 ] = c1.y;
- controlArray1[ index + 5 ] = c1.z;
+ break;
- directionArray[ index + 0 ] = v1.x - v0.x;
- directionArray[ index + 1 ] = v1.y - v0.y;
- directionArray[ index + 2 ] = v1.z - v0.z;
- directionArray[ index + 3 ] = v1.x - v0.x;
- directionArray[ index + 4 ] = v1.y - v0.y;
- directionArray[ index + 5 ] = v1.z - v0.z;
+ case 'BFC':
- }
+ // Changes to the backface culling state
+ while ( ! lp.isAtTheEnd() ) {
- bufferGeometry.setAttribute( 'control0', new BufferAttribute( controlArray0, 3, false ) );
- bufferGeometry.setAttribute( 'control1', new BufferAttribute( controlArray1, 3, false ) );
- bufferGeometry.setAttribute( 'direction', new BufferAttribute( directionArray, 3, false ) );
+ const token = lp.getToken();
- }
+ switch ( token ) {
- return object3d;
+ case 'CERTIFY':
+ case 'NOCERTIFY':
-}
+ bfcCertified = token === 'CERTIFY';
+ bfcCCW = true;
-//
+ break;
-class LDrawLoader extends Loader {
+ case 'CW':
+ case 'CCW':
- constructor( manager ) {
+ bfcCCW = token === 'CCW';
- super( manager );
+ break;
- // Array of THREE.Material
- this.materials = [];
+ case 'INVERTNEXT':
- // Not using THREE.Cache here because it returns the previous HTML error response instead of calling onError()
- // This also allows to handle the embedded text files ("0 FILE" lines)
- this.cache = new LDrawFileCache( this );
+ bfcInverted = true;
- // This object is a map from file names to paths. It agilizes the paths search. If it is not set then files will be searched by trial and error.
- this.fileMap = null;
+ break;
- this.rootParseScope = this.newParseScopeLevel();
+ case 'CLIP':
+ case 'NOCLIP':
- // Add default main triangle and line edge materials (used in pieces that can be coloured with a main color)
- this.setMaterials( [
- this.parseColourMetaDirective( new LineParser( 'Main_Colour CODE 16 VALUE #FF8080 EDGE #333333' ) ),
- this.parseColourMetaDirective( new LineParser( 'Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333' ) )
- ] );
-
- // If this flag is set to true, each subobject will be a Object.
- // If not (the default), only one object which contains all the merged primitives will be created.
- this.separateObjects = false;
+ bfcCull = token === 'CLIP';
- // If this flag is set to true the vertex normals will be smoothed.
- this.smoothNormals = true;
+ break;
- // The path to load parts from the LDraw parts library from.
- this.partsLibraryPath = '';
+ default:
- }
+ console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
- setPartsLibraryPath( path ) {
+ break;
- this.partsLibraryPath = path;
- return this;
+ }
}
- async preloadMaterials( url ) {
+ break;
- const fileLoader = new FileLoader( this.manager );
- fileLoader.setPath( this.path );
- fileLoader.setRequestHeader( this.requestHeader );
- fileLoader.setWithCredentials( this.withCredentials );
+ case 'STEP':
- const text = await fileLoader.loadAsync( url );
- const colorLineRegex = /^0 !COLOUR/;
- const lines = text.split( /[\n\r]/g );
- const materials = [];
- for ( let i = 0, l = lines.length; i < l; i ++ ) {
+ startingConstructionStep = true;
- const line = lines[ i ];
- if ( colorLineRegex.test( line ) ) {
+ break;
- const directive = line.replace( colorLineRegex, '' );
- const material = this.parseColourMetaDirective( new LineParser( directive ) );
- materials.push( material );
+ default:
+ // Other meta directives are not implemented
+ break;
}
}
- this.setMaterials( materials );
+ break;
- }
+ // Line type 1: Sub-object file
+ case '1':
- load( url, onLoad, onProgress, onError ) {
+ colorCode = lp.getToken();
+ material = getLocalMaterial( colorCode );
- if ( ! this.fileMap ) {
+ const posX = parseFloat( lp.getToken() );
+ const posY = parseFloat( lp.getToken() );
+ const posZ = parseFloat( lp.getToken() );
+ const m0 = parseFloat( lp.getToken() );
+ const m1 = parseFloat( lp.getToken() );
+ const m2 = parseFloat( lp.getToken() );
+ const m3 = parseFloat( lp.getToken() );
+ const m4 = parseFloat( lp.getToken() );
+ const m5 = parseFloat( lp.getToken() );
+ const m6 = parseFloat( lp.getToken() );
+ const m7 = parseFloat( lp.getToken() );
+ const m8 = parseFloat( lp.getToken() );
- this.fileMap = {};
+ const matrix = new Matrix4().set(
+ m0, m1, m2, posX,
+ m3, m4, m5, posY,
+ m6, m7, m8, posZ,
+ 0, 0, 0, 1
+ );
- }
+ let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
- const fileLoader = new FileLoader( this.manager );
- fileLoader.setPath( this.path );
- fileLoader.setRequestHeader( this.requestHeader );
- fileLoader.setWithCredentials( this.withCredentials );
- fileLoader.load( url, text => {
+ if ( loader.fileMap[ fileName ] ) {
- this.processObject( text, null, url, this.rootParseScope )
- .then( function ( result ) {
+ // Found the subobject path in the preloaded file path map
+ fileName = loader.fileMap[ fileName ];
- onLoad( result.groupObject );
+ } else {
- } );
+ // Standardized subfolders
+ if ( fileName.startsWith( 's/' ) ) {
- }, onProgress, onError );
+ fileName = 'parts/' + fileName;
- }
+ } else if ( fileName.startsWith( '48/' ) ) {
- parse( text, path, onLoad ) {
+ fileName = 'p/' + fileName;
- // Async parse. This function calls onParse with the parsed THREE.Object3D as parameter
- this.processObject( text, null, path, this.rootParseScope )
- .then( function ( result ) {
+ }
- onLoad( result.groupObject );
+ }
+ subobjects.push( {
+ material: material,
+ colorCode: colorCode,
+ matrix: matrix,
+ fileName: fileName,
+ inverted: bfcInverted,
+ startingConstructionStep: startingConstructionStep
} );
- }
+ bfcInverted = false;
- setMaterials( materials ) {
+ break;
- // Clears parse scopes stack, adds new scope with material library
- this.rootParseScope = this.newParseScopeLevel( materials );
- this.rootParseScope.isFromParse = false;
+ // Line type 2: Line segment
+ case '2':
- this.materials = materials;
+ colorCode = lp.getToken();
+ material = getLocalMaterial( colorCode );
+ v0 = lp.getVector();
+ v1 = lp.getVector();
- return this;
+ segment = {
+ material: material,
+ colorCode: colorCode,
+ vertices: [ v0, v1 ],
+ };
- }
+ lineSegments.push( segment );
- setFileMap( fileMap ) {
+ break;
- this.fileMap = fileMap;
+ // Line type 5: Conditional Line segment
+ case '5':
- return this;
+ colorCode = lp.getToken();
+ material = getLocalMaterial( colorCode );
+ v0 = lp.getVector();
+ v1 = lp.getVector();
+ c0 = lp.getVector();
+ c1 = lp.getVector();
- }
+ segment = {
+ material: material,
+ colorCode: colorCode,
+ vertices: [ v0, v1 ],
+ controlPoints: [ c0, c1 ],
+ };
- newParseScopeLevel( materials = null, parentScope = null ) {
+ conditionalSegments.push( segment );
- // Adds a new scope level, assign materials to it and returns it
+ break;
- const matLib = {};
+ // Line type 3: Triangle
+ case '3':
- if ( materials ) {
+ colorCode = lp.getToken();
+ material = getLocalMaterial( colorCode );
+ ccw = bfcCCW;
+ doubleSided = ! bfcCertified || ! bfcCull;
- for ( let i = 0, n = materials.length; i < n; i ++ ) {
+ if ( ccw === true ) {
- const material = materials[ i ];
- matLib[ material.userData.code ] = material;
+ v0 = lp.getVector();
+ v1 = lp.getVector();
+ v2 = lp.getVector();
- }
+ } else {
- }
+ v2 = lp.getVector();
+ v1 = lp.getVector();
+ v0 = lp.getVector();
- const newParseScope = {
+ }
- parentScope: parentScope,
- lib: matLib,
- url: null,
-
- // Subobjects
- subobjects: null,
- numSubobjects: 0,
- subobjectIndex: 0,
- inverted: false,
- category: null,
- keywords: null,
-
- // Current subobject
- currentFileName: null,
- mainColourCode: parentScope ? parentScope.mainColourCode : '16',
- mainEdgeColourCode: parentScope ? parentScope.mainEdgeColourCode : '24',
- currentMatrix: new Matrix4(),
- matrix: new Matrix4(),
- type: 'Model',
- groupObject: null,
-
- // If false, it is a root material scope previous to parse
- isFromParse: true,
-
- faces: [],
- lineSegments: [],
- conditionalSegments: [],
- totalFaces: 0,
+ faces.push( {
+ material: material,
+ colorCode: colorCode,
+ faceNormal: null,
+ vertices: [ v0, v1, v2 ],
+ normals: [ null, null, null ],
+ } );
+ totalFaces ++;
- // If true, this object is the start of a construction step
- startingConstructionStep: false
- };
+ if ( doubleSided === true ) {
- return newParseScope;
+ faces.push( {
+ material: material,
+ colorCode: colorCode,
+ faceNormal: null,
+ vertices: [ v2, v1, v0 ],
+ normals: [ null, null, null ],
+ } );
+ totalFaces ++;
}
- addMaterial( material, parseScope ) {
+ break;
- // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
+ // Line type 4: Quadrilateral
+ case '4':
- const matLib = parseScope.lib;
+ colorCode = lp.getToken();
+ material = getLocalMaterial( colorCode );
+ ccw = bfcCCW;
+ doubleSided = ! bfcCertified || ! bfcCull;
- if ( ! matLib[ material.userData.code ] ) {
+ if ( ccw === true ) {
- this.materials.push( material );
+ v0 = lp.getVector();
+ v1 = lp.getVector();
+ v2 = lp.getVector();
+ v3 = lp.getVector();
+
+ } else {
+
+ v3 = lp.getVector();
+ v2 = lp.getVector();
+ v1 = lp.getVector();
+ v0 = lp.getVector();
}
- matLib[ material.userData.code ] = material;
+ // specifically place the triangle diagonal in the v0 and v1 slots so we can
+ // account for the doubling of vertices later when smoothing normals.
+ faces.push( {
+ material: material,
+ colorCode: colorCode,
+ faceNormal: null,
+ vertices: [ v0, v1, v2, v3 ],
+ normals: [ null, null, null, null ],
+ } );
+ totalFaces += 2;
- return this;
+ if ( doubleSided === true ) {
+
+ faces.push( {
+ material: material,
+ colorCode: colorCode,
+ faceNormal: null,
+ vertices: [ v3, v2, v1, v0 ],
+ normals: [ null, null, null, null ],
+ } );
+ totalFaces += 2;
}
- getMaterial( colourCode, parseScope = this.rootParseScope ) {
+ break;
- // Given a colour code search its material in the parse scopes stack
+ default:
+ throw new Error( 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.' );
- if ( colourCode.startsWith( '0x2' ) ) {
+ }
- // Special 'direct' material value (RGB colour)
+ }
- const colour = colourCode.substring( 3 );
+ if ( parsingEmbeddedFiles ) {
- return this.parseColourMetaDirective( new LineParser( 'Direct_Color_' + colour + ' CODE -1 VALUE #' + colour + ' EDGE #' + colour + '' ) );
+ this.setData( currentEmbeddedFileName, currentEmbeddedText );
}
- while ( parseScope ) {
+ return {
+ faces,
+ conditionalSegments,
+ lineSegments,
+ type,
+ category,
+ keywords,
+ subobjects,
+ totalFaces,
+ startingConstructionStep,
+ materials,
+ fileName,
+ group: null
+ };
- const material = parseScope.lib[ colourCode ];
+ }
- if ( material ) {
+ // returns an (optionally cloned) instance of the data
+ getData( fileName, clone = true ) {
- return material;
+ const key = fileName.toLowerCase();
+ const result = this._cache[ key ];
+ if ( result === null || result instanceof Promise ) {
+
+ return null;
+
+ }
+
+ if ( clone ) {
+
+ return this.cloneResult( result );
} else {
- parseScope = parseScope.parentScope;
+ return result;
}
}
- // Material was not found
- return null;
+ // kicks off a fetch and parse of the requested data if it hasn't already been loaded. Returns when
+ // the data is ready to use and can be retrieved synchronously with "getData".
+ async ensureDataLoaded( fileName ) {
+
+ const key = fileName.toLowerCase();
+ if ( ! ( key in this._cache ) ) {
+
+ // replace the promise with a copy of the parsed data for immediate processing
+ this._cache[ key ] = this.fetchData( fileName ).then( text => {
+
+ const info = this.parse( text, fileName );
+ this._cache[ key ] = info;
+ return info;
+
+ } );
}
- parseColourMetaDirective( lineParser ) {
+ await this._cache[ key ];
- // Parses a colour definition and returns a THREE.Material
+ }
- let code = null;
+ // sets the data in the cache from parsed data
+ setData( fileName, text ) {
- // Triangle and line colours
- let colour = 0xFF00FF;
- let edgeColour = 0xFF00FF;
+ const key = fileName.toLowerCase();
+ this._cache[ key ] = this.parse( text, fileName );
- // Transparency
- let alpha = 1;
- let isTransparent = false;
- // Self-illumination:
- let luminance = 0;
+ }
- let finishType = FINISH_TYPE_DEFAULT;
+}
- let edgeMaterial = null;
+// returns the material for an associated color code. If the color code is 16 for a face or 24 for
+// an edge then the passthroughColorCode is used.
+function getMaterialFromCode( colorCode, parentColorCode, materialHierarchy, forEdge ) {
- const name = lineParser.getToken();
- if ( ! name ) {
+ const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
+ if ( isPassthrough ) {
- throw 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.';
+ colorCode = parentColorCode;
}
- // Parse tag tokens and their parameters
- let token = null;
- while ( true ) {
+ return materialHierarchy[ colorCode ] || null;
- token = lineParser.getToken();
+}
- if ( ! token ) {
+// Class used to parse and build LDraw parts as three.js objects and cache them if they're a "Part" type.
+class LDrawPartsGeometryCache {
- break;
+ constructor( loader ) {
+
+ this.loader = loader;
+ this.parseCache = new LDrawParsedCache( loader );
+ this._cache = {};
}
- switch ( token.toUpperCase() ) {
+ // Convert the given file information into a mesh by processing subobjects.
+ async processIntoMesh( info ) {
- case 'CODE':
+ const loader = this.loader;
+ const parseCache = this.parseCache;
+ const faceMaterials = new Set();
- code = lineParser.getToken();
- break;
+ // Processes the part subobject information to load child parts and merge geometry onto part
+ // piece object.
+ const processInfoSubobjects = async ( info, subobject = null ) => {
- case 'VALUE':
+ const subobjects = info.subobjects;
+ const promises = [];
+
+ // Trigger load of all subobjects. If a subobject isn't a primitive then load it as a separate
+ // group which lets instruction steps apply correctly.
+ for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
+
+ const subobject = subobjects[ i ];
+ const promise = parseCache.ensureDataLoaded( subobject.fileName ).then( () => {
- colour = lineParser.getToken();
- if ( colour.startsWith( '0x' ) ) {
+ const subobjectInfo = parseCache.getData( subobject.fileName, false );
+ if ( ! isPrimitiveType( subobjectInfo.type ) ) {
- colour = '#' + colour.substring( 2 );
+ return this.loadModel( subobject.fileName ).catch( error => {
- } else if ( ! colour.startsWith( '#' ) ) {
+ console.warn( error );
+ return null;
- throw 'LDrawLoader: Invalid colour while parsing material' + lineParser.getLineNumberString() + '.';
+ } );
}
- break;
+ return processInfoSubobjects( parseCache.getData( subobject.fileName ), subobject );
- case 'EDGE':
+ } );
- edgeColour = lineParser.getToken();
- if ( edgeColour.startsWith( '0x' ) ) {
+ promises.push( promise );
- edgeColour = '#' + edgeColour.substring( 2 );
+ }
- } else if ( ! edgeColour.startsWith( '#' ) ) {
+ const group = new Group();
+ group.userData.category = info.category;
+ group.userData.keywords = info.keywords;
+ info.group = group;
- // Try to see if edge colour is a colour code
- edgeMaterial = this.getMaterial( edgeColour );
- if ( ! edgeMaterial ) {
+ const subobjectInfos = await Promise.all( promises );
+ for ( let i = 0, l = subobjectInfos.length; i < l; i ++ ) {
- throw 'LDrawLoader: Invalid edge colour while parsing material' + lineParser.getLineNumberString() + '.';
+ const subobject = info.subobjects[ i ];
+ const subobjectInfo = subobjectInfos[ i ];
- }
+ if ( subobjectInfo === null ) {
- // Get the edge material for this triangle material
- edgeMaterial = edgeMaterial.userData.edgeMaterial;
+ // the subobject failed to load
+ continue;
}
- break;
+ // if the subobject was loaded as a separate group then apply the parent scopes materials
+ if ( subobjectInfo.isGroup ) {
- case 'ALPHA':
+ const subobjectGroup = subobjectInfo;
+ subobject.matrix.decompose( subobjectGroup.position, subobjectGroup.quaternion, subobjectGroup.scale );
+ subobjectGroup.userData.startingConstructionStep = subobject.startingConstructionStep;
+ subobjectGroup.name = subobject.fileName;
- alpha = parseInt( lineParser.getToken() );
+ loader.applyMaterialsToMesh( subobjectGroup, subobject.colorCode, info.materials );
- if ( isNaN( alpha ) ) {
+ group.add( subobjectGroup );
+ continue;
+
+ }
- throw 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.';
+ // add the subobject group if it has children in case it has both children and primitives
+ if ( subobjectInfo.group.children.length ) {
+
+ group.add( subobjectInfo.group );
}
- alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
+ // transform the primitives into the local space of the parent piece and append them to
+ // to the parent primitives list.
+ const parentLineSegments = info.lineSegments;
+ const parentConditionalSegments = info.conditionalSegments;
+ const parentFaces = info.faces;
- if ( alpha < 1 ) {
+ const lineSegments = subobjectInfo.lineSegments;
+ const conditionalSegments = subobjectInfo.conditionalSegments;
- isTransparent = true;
+ const faces = subobjectInfo.faces;
+ const matrix = subobject.matrix;
+ const inverted = subobject.inverted;
+ const matrixScaleInverted = matrix.determinant() < 0;
+ const colorCode = subobject.colorCode;
- }
+ const lineColorCode = colorCode === MAIN_COLOUR_CODE ? MAIN_EDGE_COLOUR_CODE : colorCode;
+ for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
- break;
+ const ls = lineSegments[ i ];
+ const vertices = ls.vertices;
+ vertices[ 0 ].applyMatrix4( matrix );
+ vertices[ 1 ].applyMatrix4( matrix );
+ ls.colorCode = ls.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : ls.colorCode;
+ ls.material = ls.material || getMaterialFromCode( ls.colorCode, ls.colorCode, info.materials, true );
- case 'LUMINANCE':
+ parentLineSegments.push( ls );
- luminance = parseInt( lineParser.getToken() );
+ }
- if ( isNaN( luminance ) ) {
+ for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
- throw 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.';
+ const os = conditionalSegments[ i ];
+ const vertices = os.vertices;
+ const controlPoints = os.controlPoints;
+ vertices[ 0 ].applyMatrix4( matrix );
+ vertices[ 1 ].applyMatrix4( matrix );
+ controlPoints[ 0 ].applyMatrix4( matrix );
+ controlPoints[ 1 ].applyMatrix4( matrix );
+ os.colorCode = os.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : os.colorCode;
+ os.material = os.material || getMaterialFromCode( os.colorCode, os.colorCode, info.materials, true );
+
+ parentConditionalSegments.push( os );
}
- luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
+ for ( let i = 0, l = faces.length; i < l; i ++ ) {
- break;
+ const tri = faces[ i ];
+ const vertices = tri.vertices;
+ for ( let i = 0, l = vertices.length; i < l; i ++ ) {
- case 'CHROME':
- finishType = FINISH_TYPE_CHROME;
- break;
+ vertices[ i ].applyMatrix4( matrix );
- case 'PEARLESCENT':
- finishType = FINISH_TYPE_PEARLESCENT;
- break;
+ }
- case 'RUBBER':
- finishType = FINISH_TYPE_RUBBER;
- break;
+ tri.colorCode = tri.colorCode === MAIN_COLOUR_CODE ? colorCode : tri.colorCode;
+ tri.material = tri.material || getMaterialFromCode( tri.colorCode, colorCode, info.materials, false );
+ faceMaterials.add( tri.colorCode );
- case 'MATTE_METALLIC':
- finishType = FINISH_TYPE_MATTE_METALLIC;
- break;
+ // If the scale of the object is negated then the triangle winding order
+ // needs to be flipped.
+ if ( matrixScaleInverted !== inverted ) {
- case 'METAL':
- finishType = FINISH_TYPE_METAL;
- break;
+ vertices.reverse();
- case 'MATERIAL':
- // Not implemented
- lineParser.setToEnd();
- break;
+ }
- default:
- throw 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.';
- break;
+ parentFaces.push( tri );
}
+ info.totalFaces += subobjectInfo.totalFaces;
+
}
- let material = null;
+ // Apply the parent subobjects pass through material code to this object. This is done several times due
+ // to material scoping.
+ if ( subobject ) {
- switch ( finishType ) {
+ loader.applyMaterialsToMesh( group, subobject.colorCode, info.materials );
- case FINISH_TYPE_DEFAULT:
+ }
- material = new MeshStandardMaterial( { color: colour, roughness: 0.3, metalness: 0 } );
- break;
+ return info;
- case FINISH_TYPE_PEARLESCENT:
+ };
- // Try to imitate pearlescency by making the surface glossy
- material = new MeshStandardMaterial( { color: colour, roughness: 0.3, metalness: 0.25 } );
- break;
+ // Track material use to see if we need to use the normal smooth slow path for hard edges.
+ for ( let i = 0, l = info.faces; i < l; i ++ ) {
- case FINISH_TYPE_CHROME:
+ faceMaterials.add( info.faces[ i ].colorCode );
- // Mirror finish surface
- material = new MeshStandardMaterial( { color: colour, roughness: 0, metalness: 1 } );
- break;
+ }
- case FINISH_TYPE_RUBBER:
+ await processInfoSubobjects( info );
- // Rubber finish
- material = new MeshStandardMaterial( { color: colour, roughness: 0.9, metalness: 0 } );
- break;
+ if ( loader.smoothNormals ) {
- case FINISH_TYPE_MATTE_METALLIC:
+ const checkSubSegments = faceMaterials.size > 1;
+ generateFaceNormals( info.faces );
+ smoothNormals( info.faces, info.lineSegments, checkSubSegments );
- // Brushed metal finish
- material = new MeshStandardMaterial( { color: colour, roughness: 0.8, metalness: 0.4 } );
- break;
+ }
- case FINISH_TYPE_METAL:
+ // Add the primitive objects and metadata.
+ const group = info.group;
+ if ( info.faces.length > 0 ) {
- // Average metal finish
- material = new MeshStandardMaterial( { color: colour, roughness: 0.2, metalness: 0.85 } );
- break;
+ group.add( createObject( info.faces, 3, false, info.totalFaces ) );
- default:
- // Should not happen
- break;
+ }
+
+ if ( info.lineSegments.length > 0 ) {
+
+ group.add( createObject( info.lineSegments, 2 ) );
}
- material.transparent = isTransparent;
- material.premultipliedAlpha = true;
- material.opacity = alpha;
- material.depthWrite = ! isTransparent;
+ if ( info.conditionalSegments.length > 0 ) {
- material.polygonOffset = true;
- material.polygonOffsetFactor = 1;
+ group.add( createObject( info.conditionalSegments, 2, true ) );
- if ( luminance !== 0 ) {
+ }
- material.emissive.set( material.color ).multiplyScalar( luminance );
+ return group;
}
- if ( ! edgeMaterial ) {
+ hasCachedModel( fileName ) {
- // This is the material used for edges
- edgeMaterial = new LineBasicMaterial( {
- color: edgeColour,
- transparent: isTransparent,
- opacity: alpha,
- depthWrite: ! isTransparent
- } );
- edgeMaterial.userData.code = code;
- edgeMaterial.name = name + ' - Edge';
+ return fileName !== null && fileName.toLowerCase() in this._cache;
- // This is the material used for conditional edges
- edgeMaterial.userData.conditionalEdgeMaterial = new LDrawConditionalLineMaterial( {
+ }
- fog: true,
- transparent: isTransparent,
- depthWrite: ! isTransparent,
- color: edgeColour,
- opacity: alpha,
+ async getCachedModel( fileName ) {
- } );
+ if ( fileName !== null && this.hasCachedModel( fileName ) ) {
- }
+ const key = fileName.toLowerCase();
+ const group = await this._cache[ key ];
+ return group.clone();
- material.userData.code = code;
- material.name = name;
+ } else {
- material.userData.edgeMaterial = edgeMaterial;
+ return null;
- return material;
+ }
}
- //
+ // Loads and parses the model with the given file name. Returns a cached copy if available.
+ async loadModel( fileName ) {
- objectParse( text, parseScope ) {
+ const parseCache = this.parseCache;
+ const key = fileName.toLowerCase();
+ if ( this.hasCachedModel( fileName ) ) {
- // Retrieve data from the parent parse scope
- const currentParseScope = parseScope;
- const parentParseScope = currentParseScope.parentScope;
+ // Return cached model if available.
+ return this.getCachedModel( fileName );
- // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
- const mainColourCode = currentParseScope.mainColourCode;
- const mainEdgeColourCode = currentParseScope.mainEdgeColourCode;
+ } else {
+ // Otherwise parse a new model.
+ // Ensure the file data is loaded and pre parsed.
+ await parseCache.ensureDataLoaded( fileName );
- // Parse result variables
- let faces;
- let lineSegments;
- let conditionalSegments;
+ const info = parseCache.getData( fileName );
+ const promise = this.processIntoMesh( info );
- const subobjects = [];
+ // Now that the file has loaded it's possible that another part parse has been waiting in parallel
+ // so check the cache again to see if it's been added since the last async operation so we don't
+ // do unnecessary work.
+ if ( this.hasCachedModel( fileName ) ) {
- let category = null;
- let keywords = null;
+ return this.getCachedModel( fileName );
- if ( text.indexOf( '\r\n' ) !== - 1 ) {
+ }
- // This is faster than String.split with regex that splits on both
- text = text.replace( /\r\n/g, '\n' );
+ // Cache object if it's a part so it can be reused later.
+ if ( isPartType( info.type ) ) {
+
+ this._cache[ key ] = promise;
}
- const lines = text.split( '\n' );
- const numLines = lines.length;
+ // return a copy
+ const group = await promise;
+ return group.clone();
- let parsingEmbeddedFiles = false;
- let currentEmbeddedFileName = null;
- let currentEmbeddedText = null;
+ }
- let bfcCertified = false;
- let bfcCCW = true;
- let bfcInverted = false;
- let bfcCull = true;
- let type = '';
+ }
- let startingConstructionStep = false;
+ // parses the given model text into a renderable object. Returns cached copy if available.
+ async parseModel( text ) {
- const scope = this;
- function parseColourCode( lineParser, forEdge ) {
+ const parseCache = this.parseCache;
+ const info = parseCache.parse( text );
+ if ( isPartType( info.type ) && this.hasCachedModel( info.fileName ) ) {
- // Parses next colour code and returns a THREE.Material
+ return this.getCachedModel( info.fileName );
- let colourCode = lineParser.getToken();
+ }
- if ( ! forEdge && colourCode === '16' ) {
+ return this.processIntoMesh( info );
- colourCode = mainColourCode;
+ }
+
+}
+
+function sortByMaterial( a, b ) {
+
+ if ( a.colorCode === b.colorCode ) {
+
+ return 0;
}
- if ( forEdge && colourCode === '24' ) {
+ if ( a.colorCode < b.colorCode ) {
- colourCode = mainEdgeColourCode;
+ return - 1;
}
- const material = scope.getMaterial( colourCode, currentParseScope );
+ return 1;
- if ( ! material ) {
+}
- throw 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.';
+function createObject( elements, elementSize, isConditionalSegments = false, totalElements = null ) {
- }
+ // Creates a LineSegments (elementSize = 2) or a Mesh (elementSize = 3 )
+ // With per face / segment material, implemented with mesh groups and materials array
- return material;
+ // Sort the faces or line segments by color code to make later the mesh groups
+ elements.sort( sortByMaterial );
+
+ if ( totalElements === null ) {
+
+ totalElements = elements.length;
}
- function parseVector( lp ) {
+ const positions = new Float32Array( elementSize * totalElements * 3 );
+ const normals = elementSize === 3 ? new Float32Array( elementSize * totalElements * 3 ) : null;
+ const materials = [];
- const v = new Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
+ const quadArray = new Array( 6 );
+ const bufferGeometry = new BufferGeometry();
+ let prevMaterial = null;
+ let index0 = 0;
+ let numGroupVerts = 0;
+ let offset = 0;
- if ( ! scope.separateObjects ) {
+ for ( let iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
- v.applyMatrix4( currentParseScope.currentMatrix );
+ const elem = elements[ iElem ];
+ let vertices = elem.vertices;
+ if ( vertices.length === 4 ) {
+
+ quadArray[ 0 ] = vertices[ 0 ];
+ quadArray[ 1 ] = vertices[ 1 ];
+ quadArray[ 2 ] = vertices[ 2 ];
+ quadArray[ 3 ] = vertices[ 0 ];
+ quadArray[ 4 ] = vertices[ 2 ];
+ quadArray[ 5 ] = vertices[ 3 ];
+ vertices = quadArray;
}
- return v;
+ for ( let j = 0, l = vertices.length; j < l; j ++ ) {
+
+ const v = vertices[ j ];
+ const index = offset + j * 3;
+ positions[ index + 0 ] = v.x;
+ positions[ index + 1 ] = v.y;
+ positions[ index + 2 ] = v.z;
}
- // Parse all line commands
- for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
+ // create the normals array if this is a set of faces
+ if ( elementSize === 3 ) {
- const line = lines[ lineIndex ];
+ if ( ! elem.faceNormal ) {
- if ( line.length === 0 ) continue;
+ const v0 = vertices[ 0 ];
+ const v1 = vertices[ 1 ];
+ const v2 = vertices[ 2 ];
+ _tempVec0.subVectors( v1, v0 );
+ _tempVec1.subVectors( v2, v1 );
+ elem.faceNormal = new Vector3()
+ .crossVectors( _tempVec0, _tempVec1 )
+ .normalize();
- if ( parsingEmbeddedFiles ) {
+ }
- if ( line.startsWith( '0 FILE ' ) ) {
+ let elemNormals = elem.normals;
+ if ( elemNormals.length === 4 ) {
- // Save previous embedded file in the cache
- this.cache.setData( currentEmbeddedFileName.toLowerCase(), currentEmbeddedText );
+ quadArray[ 0 ] = elemNormals[ 0 ];
+ quadArray[ 1 ] = elemNormals[ 1 ];
+ quadArray[ 2 ] = elemNormals[ 2 ];
+ quadArray[ 3 ] = elemNormals[ 0 ];
+ quadArray[ 4 ] = elemNormals[ 2 ];
+ quadArray[ 5 ] = elemNormals[ 3 ];
+ elemNormals = quadArray;
- // New embedded text file
- currentEmbeddedFileName = line.substring( 7 );
- currentEmbeddedText = '';
+ }
- } else {
+ for ( let j = 0, l = elemNormals.length; j < l; j ++ ) {
- currentEmbeddedText += line + '\n';
+ // use face normal if a vertex normal is not provided
+ let n = elem.faceNormal;
+ if ( elemNormals[ j ] ) {
+
+ n = elemNormals[ j ].norm;
}
- continue;
+ const index = offset + j * 3;
+ normals[ index + 0 ] = n.x;
+ normals[ index + 1 ] = n.y;
+ normals[ index + 2 ] = n.z;
}
- const lp = new LineParser( line, lineIndex + 1 );
+ }
- lp.seekNonSpace();
+ if ( prevMaterial !== elem.colorCode ) {
- if ( lp.isAtTheEnd() ) {
+ if ( prevMaterial !== null ) {
- // Empty line
- continue;
+ bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
}
- // Parse the line type
- const lineType = lp.getToken();
+ const material = elem.material;
+ if ( material !== null ) {
- let material;
- let segment;
- let inverted;
- let ccw;
- let doubleSided;
- let v0, v1, v2, v3, c0, c1, faceNormal;
+ if ( elementSize === 3 ) {
- switch ( lineType ) {
+ materials.push( material );
- // Line type 0: Comment or META
- case '0':
+ } else if ( elementSize === 2 ) {
- // Parse meta directive
- const meta = lp.getToken();
+ if ( material !== null ) {
- if ( meta ) {
+ if ( isConditionalSegments ) {
- switch ( meta ) {
+ materials.push( material.userData.edgeMaterial.userData.conditionalEdgeMaterial );
- case '!LDRAW_ORG':
+ } else {
- type = lp.getToken();
+ materials.push( material.userData.edgeMaterial );
- currentParseScope.type = type;
+ }
- // If the scale of the object is negated then the triangle winding order
- // needs to be flipped.
- if (
- currentParseScope.matrix.determinant() < 0 && (
- scope.separateObjects && isPrimitiveType( type ) ||
- ! scope.separateObjects
- ) ) {
+ } else {
- currentParseScope.inverted = ! currentParseScope.inverted;
+ materials.push( null );
}
- faces = currentParseScope.faces;
- lineSegments = currentParseScope.lineSegments;
- conditionalSegments = currentParseScope.conditionalSegments;
+ }
- break;
+ } else {
- case '!COLOUR':
+ // If a material has not been made available yet then keep the color code string in the material array
+ // to save the spot for the material once a parent scopes materials are being applied to the object.
+ materials.push( elem.colorCode );
- material = this.parseColourMetaDirective( lp );
- if ( material ) {
+ }
- this.addMaterial( material, parseScope );
+ prevMaterial = elem.colorCode;
+ index0 = offset / 3;
+ numGroupVerts = vertices.length;
} else {
- console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
+ numGroupVerts += vertices.length;
}
- break;
+ offset += 3 * vertices.length;
- case '!CATEGORY':
+ }
- category = lp.getToken();
- break;
+ if ( numGroupVerts > 0 ) {
- case '!KEYWORDS':
+ bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
- const newKeywords = lp.getRemainingString().split( ',' );
- if ( newKeywords.length > 0 ) {
+ }
- if ( ! keywords ) {
+ bufferGeometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
- keywords = [];
+ if ( normals !== null ) {
+
+ bufferGeometry.setAttribute( 'normal', new BufferAttribute( normals, 3 ) );
}
- newKeywords.forEach( function ( keyword ) {
+ let object3d = null;
- keywords.push( keyword.trim() );
+ if ( elementSize === 2 ) {
- } );
+ if ( isConditionalSegments ) {
- }
+ object3d = new ConditionalLineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
- break;
+ } else {
- case 'FILE':
+ object3d = new LineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
- if ( lineIndex > 0 ) {
+ }
- // Start embedded text files parsing
- parsingEmbeddedFiles = true;
- currentEmbeddedFileName = lp.getRemainingString();
- currentEmbeddedText = '';
+ } else if ( elementSize === 3 ) {
- bfcCertified = false;
- bfcCCW = true;
+ object3d = new Mesh( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
}
- break;
+ if ( isConditionalSegments ) {
- case 'BFC':
+ object3d.isConditionalLine = true;
- // Changes to the backface culling state
- while ( ! lp.isAtTheEnd() ) {
+ const controlArray0 = new Float32Array( elements.length * 3 * 2 );
+ const controlArray1 = new Float32Array( elements.length * 3 * 2 );
+ const directionArray = new Float32Array( elements.length * 3 * 2 );
+ for ( let i = 0, l = elements.length; i < l; i ++ ) {
- const token = lp.getToken();
+ const os = elements[ i ];
+ const vertices = os.vertices;
+ const controlPoints = os.controlPoints;
+ const c0 = controlPoints[ 0 ];
+ const c1 = controlPoints[ 1 ];
+ const v0 = vertices[ 0 ];
+ const v1 = vertices[ 1 ];
+ const index = i * 3 * 2;
+ controlArray0[ index + 0 ] = c0.x;
+ controlArray0[ index + 1 ] = c0.y;
+ controlArray0[ index + 2 ] = c0.z;
+ controlArray0[ index + 3 ] = c0.x;
+ controlArray0[ index + 4 ] = c0.y;
+ controlArray0[ index + 5 ] = c0.z;
- switch ( token ) {
+ controlArray1[ index + 0 ] = c1.x;
+ controlArray1[ index + 1 ] = c1.y;
+ controlArray1[ index + 2 ] = c1.z;
+ controlArray1[ index + 3 ] = c1.x;
+ controlArray1[ index + 4 ] = c1.y;
+ controlArray1[ index + 5 ] = c1.z;
- case 'CERTIFY':
- case 'NOCERTIFY':
+ directionArray[ index + 0 ] = v1.x - v0.x;
+ directionArray[ index + 1 ] = v1.y - v0.y;
+ directionArray[ index + 2 ] = v1.z - v0.z;
+ directionArray[ index + 3 ] = v1.x - v0.x;
+ directionArray[ index + 4 ] = v1.y - v0.y;
+ directionArray[ index + 5 ] = v1.z - v0.z;
- bfcCertified = token === 'CERTIFY';
- bfcCCW = true;
+ }
- break;
+ bufferGeometry.setAttribute( 'control0', new BufferAttribute( controlArray0, 3, false ) );
+ bufferGeometry.setAttribute( 'control1', new BufferAttribute( controlArray1, 3, false ) );
+ bufferGeometry.setAttribute( 'direction', new BufferAttribute( directionArray, 3, false ) );
- case 'CW':
- case 'CCW':
+ }
- bfcCCW = token === 'CCW';
+ return object3d;
- break;
+}
- case 'INVERTNEXT':
+//
- bfcInverted = true;
+class LDrawLoader extends Loader {
- break;
+ constructor( manager ) {
- case 'CLIP':
- case 'NOCLIP':
+ super( manager );
- bfcCull = token === 'CLIP';
+ // Array of THREE.Material
+ this.materials = [];
+ this.materialLibrary = {};
- break;
+ // This also allows to handle the embedded text files ("0 FILE" lines)
+ this.partsCache = new LDrawPartsGeometryCache( this );
- default:
+ // This object is a map from file names to paths. It agilizes the paths search. If it is not set then files will be searched by trial and error.
+ this.fileMap = {};
- console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
+ // Initializes the materials library with default materials
+ this.setMaterials( [] );
- break;
+ // If this flag is set to true the vertex normals will be smoothed.
+ this.smoothNormals = true;
+
+ // The path to load parts from the LDraw parts library from.
+ this.partsLibraryPath = '';
}
+ setPartsLibraryPath( path ) {
+
+ this.partsLibraryPath = path;
+ return this;
+
}
- break;
+ async preloadMaterials( url ) {
- case 'STEP':
+ const fileLoader = new FileLoader( this.manager );
+ fileLoader.setPath( this.path );
+ fileLoader.setRequestHeader( this.requestHeader );
+ fileLoader.setWithCredentials( this.withCredentials );
- startingConstructionStep = true;
+ const text = await fileLoader.loadAsync( url );
+ const colorLineRegex = /^0 !COLOUR/;
+ const lines = text.split( /[\n\r]/g );
+ const materials = [];
+ for ( let i = 0, l = lines.length; i < l; i ++ ) {
- break;
+ const line = lines[ i ];
+ if ( colorLineRegex.test( line ) ) {
- default:
- // Other meta directives are not implemented
- break;
+ const directive = line.replace( colorLineRegex, '' );
+ const material = this.parseColorMetaDirective( new LineParser( directive ) );
+ materials.push( material );
}
}
- break;
-
- // Line type 1: Sub-object file
- case '1':
+ this.setMaterials( materials );
- material = parseColourCode( lp );
+ }
- const posX = parseFloat( lp.getToken() );
- const posY = parseFloat( lp.getToken() );
- const posZ = parseFloat( lp.getToken() );
- const m0 = parseFloat( lp.getToken() );
- const m1 = parseFloat( lp.getToken() );
- const m2 = parseFloat( lp.getToken() );
- const m3 = parseFloat( lp.getToken() );
- const m4 = parseFloat( lp.getToken() );
- const m5 = parseFloat( lp.getToken() );
- const m6 = parseFloat( lp.getToken() );
- const m7 = parseFloat( lp.getToken() );
- const m8 = parseFloat( lp.getToken() );
+ load( url, onLoad, onProgress, onError ) {
- const matrix = new Matrix4().set(
- m0, m1, m2, posX,
- m3, m4, m5, posY,
- m6, m7, m8, posZ,
- 0, 0, 0, 1
- );
+ const fileLoader = new FileLoader( this.manager );
+ fileLoader.setPath( this.path );
+ fileLoader.setRequestHeader( this.requestHeader );
+ fileLoader.setWithCredentials( this.withCredentials );
+ fileLoader.load( url, text => {
- let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
+ this.partsCache
+ .parseModel( text, this.materialLibrary )
+ .then( group => {
+
+ this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
+ this.computeConstructionSteps( group );
+ onLoad( group );
- if ( scope.fileMap[ fileName ] ) {
+ } )
+ .catch( onError );
- // Found the subobject path in the preloaded file path map
- fileName = scope.fileMap[ fileName ];
+ }, onProgress, onError );
- } else {
+ }
- // Standardized subfolders
- if ( fileName.startsWith( 's/' ) ) {
+ parse( text, onLoad ) {
- fileName = 'parts/' + fileName;
+ this.partsCache
+ .parseModel( text, this.materialLibrary )
+ .then( group => {
- } else if ( fileName.startsWith( '48/' ) ) {
+ this.computeConstructionSteps( group );
+ onLoad( group );
- fileName = 'p/' + fileName;
+ } );
}
- }
+ setMaterials( materials ) {
- subobjects.push( {
- material: material,
- matrix: matrix,
- fileName: fileName,
- inverted: bfcInverted !== currentParseScope.inverted,
- startingConstructionStep: startingConstructionStep
- } );
+ this.materialLibrary = {};
+ this.materials = [];
+ for ( let i = 0, l = materials.length; i < l; i ++ ) {
- bfcInverted = false;
+ this.addMaterial( materials[ i ] );
- break;
+ }
- // Line type 2: Line segment
- case '2':
+ // Add default main triangle and line edge materials (used in pieces that can be colored with a main color)
+ this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Main_Colour CODE 16 VALUE #FF8080 EDGE #333333' ) ) );
+ this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333' ) ) );
- material = parseColourCode( lp, true );
- v0 = parseVector( lp );
- v1 = parseVector( lp );
+ return this;
- segment = {
- material: material.userData.edgeMaterial,
- colourCode: material.userData.code,
- v0: v0,
- v1: v1,
+ }
- vertices: [ v0, v1 ],
- };
+ setFileMap( fileMap ) {
- lineSegments.push( segment );
+ this.fileMap = fileMap;
- break;
+ return this;
- // Line type 5: Conditional Line segment
- case '5':
+ }
- material = parseColourCode( lp, true );
- v0 = parseVector( lp );
- v1 = parseVector( lp );
- c0 = parseVector( lp );
- c1 = parseVector( lp );
+ addMaterial( material ) {
- segment = {
- material: material.userData.edgeMaterial.userData.conditionalEdgeMaterial,
- colourCode: material.userData.code,
- vertices: [ v0, v1 ],
- controlPoints: [ c0, c1 ],
- };
+ // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
- conditionalSegments.push( segment );
+ const matLib = this.materialLibrary;
+ if ( ! matLib[ material.userData.code ] ) {
- break;
+ this.materials.push( material );
+ matLib[ material.userData.code ] = material;
- // Line type 3: Triangle
- case '3':
+ }
- material = parseColourCode( lp );
+ return this;
- inverted = currentParseScope.inverted;
- ccw = bfcCCW !== inverted;
- doubleSided = ! bfcCertified || ! bfcCull;
+ }
- if ( ccw === true ) {
+ getMaterial( colorCode ) {
- v0 = parseVector( lp );
- v1 = parseVector( lp );
- v2 = parseVector( lp );
+ if ( colorCode.startsWith( '0x2' ) ) {
- } else {
+ // Special 'direct' material value (RGB color)
+ const color = colorCode.substring( 3 );
- v2 = parseVector( lp );
- v1 = parseVector( lp );
- v0 = parseVector( lp );
+ return this.parseColorMetaDirective( new LineParser( 'Direct_Color_' + color + ' CODE -1 VALUE #' + color + ' EDGE #' + color + '' ) );
}
- _tempVec0.subVectors( v1, v0 );
- _tempVec1.subVectors( v2, v1 );
- faceNormal = new Vector3()
- .crossVectors( _tempVec0, _tempVec1 )
- .normalize();
+ return this.materialLibrary[ colorCode ] || null;
- faces.push( {
- material: material,
- colourCode: material.userData.code,
- faceNormal: faceNormal,
- vertices: [ v0, v1, v2 ],
- normals: [ null, null, null ],
- } );
- currentParseScope.totalFaces ++;
+ }
- if ( doubleSided === true ) {
+ // Applies the appropriate materials to a prebuilt hierarchy of geometry. Assumes that color codes are present
+ // in the material array if they need to be filled in.
+ applyMaterialsToMesh( group, parentColorCode, materialHierarchy, finalMaterialPass = false ) {
- faces.push( {
- material: material,
- colourCode: material.userData.code,
- faceNormal: faceNormal,
- vertices: [ v2, v1, v0 ],
- normals: [ null, null, null ],
- } );
- currentParseScope.totalFaces ++;
+ // find any missing materials as indicated by a color code string and replace it with a material from the current material lib
+ const loader = this;
+ const parentIsPassthrough = parentColorCode === MAIN_COLOUR_CODE;
+ group.traverse( c => {
- }
+ if ( c.isMesh || c.isLineSegments ) {
- break;
+ if ( Array.isArray( c.material ) ) {
- // Line type 4: Quadrilateral
- case '4':
+ for ( let i = 0, l = c.material.length; i < l; i ++ ) {
- material = parseColourCode( lp );
+ if ( ! c.material[ i ].isMaterial ) {
- inverted = currentParseScope.inverted;
- ccw = bfcCCW !== inverted;
- doubleSided = ! bfcCertified || ! bfcCull;
+ c.material[ i ] = getMaterial( c, c.material[ i ] );
- if ( ccw === true ) {
+ }
- v0 = parseVector( lp );
- v1 = parseVector( lp );
- v2 = parseVector( lp );
- v3 = parseVector( lp );
+ }
- } else {
+ } else if ( ! c.material.isMaterial ) {
- v3 = parseVector( lp );
- v2 = parseVector( lp );
- v1 = parseVector( lp );
- v0 = parseVector( lp );
+ c.material = getMaterial( c, c.material );
}
- _tempVec0.subVectors( v1, v0 );
- _tempVec1.subVectors( v2, v1 );
- faceNormal = new Vector3()
- .crossVectors( _tempVec0, _tempVec1 )
- .normalize();
+ }
- // specifically place the triangle diagonal in the v0 and v1 slots so we can
- // account for the doubling of vertices later when smoothing normals.
- faces.push( {
- material: material,
- colourCode: material.userData.code,
- faceNormal: faceNormal,
- vertices: [ v0, v1, v2, v3 ],
- normals: [ null, null, null, null ],
} );
- currentParseScope.totalFaces += 2;
- if ( doubleSided === true ) {
- faces.push( {
- material: material,
- colourCode: material.userData.code,
- faceNormal: faceNormal,
- vertices: [ v3, v2, v1, v0 ],
- normals: [ null, null, null, null ],
- } );
- currentParseScope.totalFaces += 2;
+ // Returns the appropriate material for the object (line or face) given color code. If the code is "pass through"
+ // (24 for lines, 16 for edges) then the pass through color code is used. If that is also pass through then it's
+ // simply returned for the subsequent material application.
+ function getMaterial( c, colorCode ) {
+
+ // if our parent is a passthrough color code and we don't have the current material color available then
+ // return early.
+ if ( parentIsPassthrough && ! ( colorCode in materialHierarchy ) && ! finalMaterialPass ) {
+
+ return colorCode;
}
- break;
+ const forEdge = c.isLineSegments || c.isConditionalLine;
+ const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
+ if ( isPassthrough ) {
- default:
- throw 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.';
- break;
+ colorCode = parentColorCode;
}
- }
+ let material = null;
+ if ( colorCode in materialHierarchy ) {
- if ( parsingEmbeddedFiles ) {
+ material = materialHierarchy[ colorCode ];
+
+ } else if ( finalMaterialPass ) {
- this.cache.setData( currentEmbeddedFileName.toLowerCase(), currentEmbeddedText );
+ // see if we can get the final material from from the "getMaterial" function which will attempt to
+ // parse the "direct" colors
+ material = loader.getMaterial( colorCode );
+ if ( material === null ) {
+
+ // otherwise throw an error if this is final opportunity to set the material
+ throw new Error( `LDrawLoader: Material properties for code ${ colorCode } not available.` );
}
- currentParseScope.category = category;
- currentParseScope.keywords = keywords;
- currentParseScope.subobjects = subobjects;
- currentParseScope.numSubobjects = subobjects.length;
- currentParseScope.subobjectIndex = 0;
- const isRoot = ! parentParseScope.isFromParse;
- if ( isRoot || scope.separateObjects && ! isPrimitiveType( type ) ) {
+ } else {
- currentParseScope.groupObject = new Group();
- currentParseScope.groupObject.userData.startingConstructionStep = currentParseScope.startingConstructionStep;
+ return colorCode;
}
- }
+ if ( c.isLineSegments ) {
- computeConstructionSteps( model ) {
+ material = material.userData.edgeMaterial;
- // Sets userdata.constructionStep number in Group objects and userData.numConstructionSteps number in the root Group object.
+ if ( c.isConditionalLine ) {
- let stepNumber = 0;
+ material = material.userData.conditionalEdgeMaterial;
- model.traverse( c => {
+ }
- if ( c.isGroup ) {
+ }
- if ( c.userData.startingConstructionStep ) {
+ return material;
- stepNumber ++;
+ }
}
- c.userData.constructionStep = stepNumber;
+ getMainMaterial() {
+
+ return this.getMaterial( MAIN_COLOUR_CODE );
}
- } );
+ getMainEdgeMaterial() {
- model.userData.numConstructionSteps = stepNumber + 1;
+ const mainMat = this.getMainMaterial();
+ return mainMat && mainMat.userData ? mainMat.userData.edgeMaterial : null;
}
- finalizeObject( subobjectParseScope ) {
+ parseColorMetaDirective( lineParser ) {
- // fail gracefully if an object could not be loaded
- if ( subobjectParseScope === null ) {
+ // Parses a color definition and returns a THREE.Material
- return;
+ let code = null;
- }
+ // Triangle and line colors
+ let color = 0xFF00FF;
+ let edgeColor = 0xFF00FF;
+
+ // Transparency
+ let alpha = 1;
+ let isTransparent = false;
+ // Self-illumination:
+ let luminance = 0;
- const parentParseScope = subobjectParseScope.parentScope;
+ let finishType = FINISH_TYPE_DEFAULT;
- // Smooth the normals if this is a part or if this is a case where the subpart
- // is added directly into the parent model (meaning it will never get smoothed by
- // being added to a part)
- const doSmooth =
- isPartType( subobjectParseScope.type ) ||
- (
- ! isPartType( subobjectParseScope.type ) &&
- ! isModelType( subobjectParseScope.type ) &&
- isModelType( subobjectParseScope.parentScope.type )
- );
+ let edgeMaterial = null;
- if ( this.smoothNormals && doSmooth ) {
+ const name = lineParser.getToken();
+ if ( ! name ) {
- smoothNormals( subobjectParseScope.faces, subobjectParseScope.lineSegments );
+ throw new Error( 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.' );
}
- const isRoot = ! parentParseScope.isFromParse;
- if ( this.separateObjects && ! isPrimitiveType( subobjectParseScope.type ) || isRoot ) {
+ // Parse tag tokens and their parameters
+ let token = null;
+ while ( true ) {
- const objGroup = subobjectParseScope.groupObject;
+ token = lineParser.getToken();
- if ( subobjectParseScope.faces.length > 0 ) {
+ if ( ! token ) {
- objGroup.add( createObject( subobjectParseScope.faces, 3, false, subobjectParseScope.totalFaces ) );
+ break;
}
- if ( subobjectParseScope.lineSegments.length > 0 ) {
-
- objGroup.add( createObject( subobjectParseScope.lineSegments, 2 ) );
+ switch ( token.toUpperCase() ) {
- }
+ case 'CODE':
- if ( subobjectParseScope.conditionalSegments.length > 0 ) {
+ code = lineParser.getToken();
+ break;
- objGroup.add( createObject( subobjectParseScope.conditionalSegments, 2, true ) );
+ case 'VALUE':
- }
+ color = lineParser.getToken();
+ if ( color.startsWith( '0x' ) ) {
- if ( parentParseScope.groupObject ) {
+ color = '#' + color.substring( 2 );
- objGroup.name = subobjectParseScope.fileName;
- objGroup.userData.category = subobjectParseScope.category;
- objGroup.userData.keywords = subobjectParseScope.keywords;
- subobjectParseScope.matrix.decompose( objGroup.position, objGroup.quaternion, objGroup.scale );
+ } else if ( ! color.startsWith( '#' ) ) {
- parentParseScope.groupObject.add( objGroup );
+ throw new Error( 'LDrawLoader: Invalid color while parsing material' + lineParser.getLineNumberString() + '.' );
}
- } else {
+ break;
- const separateObjects = this.separateObjects;
- const parentLineSegments = parentParseScope.lineSegments;
- const parentConditionalSegments = parentParseScope.conditionalSegments;
- const parentFaces = parentParseScope.faces;
-
- const lineSegments = subobjectParseScope.lineSegments;
- const conditionalSegments = subobjectParseScope.conditionalSegments;
- const faces = subobjectParseScope.faces;
+ case 'EDGE':
- for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
+ edgeColor = lineParser.getToken();
+ if ( edgeColor.startsWith( '0x' ) ) {
- const ls = lineSegments[ i ];
+ edgeColor = '#' + edgeColor.substring( 2 );
- if ( separateObjects ) {
+ } else if ( ! edgeColor.startsWith( '#' ) ) {
- const vertices = ls.vertices;
- vertices[ 0 ].applyMatrix4( subobjectParseScope.matrix );
- vertices[ 1 ].applyMatrix4( subobjectParseScope.matrix );
+ // Try to see if edge color is a color code
+ edgeMaterial = this.getMaterial( edgeColor );
+ if ( ! edgeMaterial ) {
+
+ throw new Error( 'LDrawLoader: Invalid edge color while parsing material' + lineParser.getLineNumberString() + '.' );
}
- parentLineSegments.push( ls );
+ // Get the edge material for this triangle material
+ edgeMaterial = edgeMaterial.userData.edgeMaterial;
}
- for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
+ break;
- const os = conditionalSegments[ i ];
+ case 'ALPHA':
- if ( separateObjects ) {
+ alpha = parseInt( lineParser.getToken() );
- const vertices = os.vertices;
- const controlPoints = os.controlPoints;
- vertices[ 0 ].applyMatrix4( subobjectParseScope.matrix );
- vertices[ 1 ].applyMatrix4( subobjectParseScope.matrix );
- controlPoints[ 0 ].applyMatrix4( subobjectParseScope.matrix );
- controlPoints[ 1 ].applyMatrix4( subobjectParseScope.matrix );
+ if ( isNaN( alpha ) ) {
+
+ throw new Error( 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.' );
}
- parentConditionalSegments.push( os );
+ alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
+
+ if ( alpha < 1 ) {
+
+ isTransparent = true;
}
- for ( let i = 0, l = faces.length; i < l; i ++ ) {
+ break;
- const tri = faces[ i ];
+ case 'LUMINANCE':
- if ( separateObjects ) {
+ luminance = parseInt( lineParser.getToken() );
- const vertices = tri.vertices;
- for ( let i = 0, l = vertices.length; i < l; i ++ ) {
+ if ( isNaN( luminance ) ) {
- vertices[ i ] = vertices[ i ].clone().applyMatrix4( subobjectParseScope.matrix );
+ throw new Error( 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.' );
}
- _tempVec0.subVectors( vertices[ 1 ], vertices[ 0 ] );
- _tempVec1.subVectors( vertices[ 2 ], vertices[ 1 ] );
- tri.faceNormal.crossVectors( _tempVec0, _tempVec1 ).normalize();
+ luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
- }
+ break;
- parentFaces.push( tri );
+ case 'CHROME':
+ finishType = FINISH_TYPE_CHROME;
+ break;
- }
+ case 'PEARLESCENT':
+ finishType = FINISH_TYPE_PEARLESCENT;
+ break;
- parentParseScope.totalFaces += subobjectParseScope.totalFaces;
+ case 'RUBBER':
+ finishType = FINISH_TYPE_RUBBER;
+ break;
+
+ case 'MATTE_METALLIC':
+ finishType = FINISH_TYPE_MATTE_METALLIC;
+ break;
+
+ case 'METAL':
+ finishType = FINISH_TYPE_METAL;
+ break;
+
+ case 'MATERIAL':
+ // Not implemented
+ lineParser.setToEnd();
+ break;
+
+ default:
+ throw new Error( 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.' );
}
}
- async processObject( text, subobject, url, parentScope ) {
+ let material = null;
+
+ switch ( finishType ) {
+
+ case FINISH_TYPE_DEFAULT:
- const scope = this;
+ material = new MeshStandardMaterial( { color: color, roughness: 0.3, metalness: 0 } );
+ break;
- const parseScope = this.newParseScopeLevel( null, parentScope );
- parseScope.url = url;
+ case FINISH_TYPE_PEARLESCENT:
- const parentParseScope = parseScope.parentScope;
+ // Try to imitate pearlescency by making the surface glossy
+ material = new MeshStandardMaterial( { color: color, roughness: 0.3, metalness: 0.25 } );
+ break;
- // Set current matrix
- if ( subobject ) {
+ case FINISH_TYPE_CHROME:
- parseScope.currentMatrix.multiplyMatrices( parentParseScope.currentMatrix, subobject.matrix );
- parseScope.matrix.copy( subobject.matrix );
- parseScope.inverted = subobject.inverted;
- parseScope.startingConstructionStep = subobject.startingConstructionStep;
- parseScope.mainColourCode = subobject.material.userData.code;
- parseScope.mainEdgeColourCode = subobject.material.userData.edgeMaterial.userData.code;
- parseScope.fileName = subobject.fileName;
+ // Mirror finish surface
+ material = new MeshStandardMaterial( { color: color, roughness: 0, metalness: 1 } );
+ break;
+
+ case FINISH_TYPE_RUBBER:
+
+ // Rubber finish
+ material = new MeshStandardMaterial( { color: color, roughness: 0.9, metalness: 0 } );
+ break;
+
+ case FINISH_TYPE_MATTE_METALLIC:
+
+ // Brushed metal finish
+ material = new MeshStandardMaterial( { color: color, roughness: 0.8, metalness: 0.4 } );
+ break;
+
+ case FINISH_TYPE_METAL:
+
+ // Average metal finish
+ material = new MeshStandardMaterial( { color: color, roughness: 0.2, metalness: 0.85 } );
+ break;
+
+ default:
+ // Should not happen
+ break;
}
- // Parse the object
- this.objectParse( text, parseScope );
+ material.transparent = isTransparent;
+ material.premultipliedAlpha = true;
+ material.opacity = alpha;
+ material.depthWrite = ! isTransparent;
+ material.color.convertSRGBToLinear();
+
+ material.polygonOffset = true;
+ material.polygonOffsetFactor = 1;
- const subobjects = parseScope.subobjects;
- const promises = [];
- for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
+ if ( luminance !== 0 ) {
- promises.push( loadSubobject( parseScope.subobjects[ i ] ) );
+ material.emissive.set( material.color ).multiplyScalar( luminance );
}
- // Kick off of the downloads in parallel but process all the subobjects
- // in order so all the assembly instructions are correct
- const subobjectScopes = await Promise.all( promises );
- for ( let i = 0, l = subobjectScopes.length; i < l; i ++ ) {
+ if ( ! edgeMaterial ) {
+
+ // This is the material used for edges
+ edgeMaterial = new LineBasicMaterial( {
+ color: edgeColor,
+ transparent: isTransparent,
+ opacity: alpha,
+ depthWrite: ! isTransparent
+ } );
+ edgeMaterial.userData.code = code;
+ edgeMaterial.name = name + ' - Edge';
+ edgeMaterial.color.convertSRGBToLinear();
- this.finalizeObject( subobjectScopes[ i ] );
+ // This is the material used for conditional edges
+ edgeMaterial.userData.conditionalEdgeMaterial = new LDrawConditionalLineMaterial( {
+
+ fog: true,
+ transparent: isTransparent,
+ depthWrite: ! isTransparent,
+ color: edgeColor,
+ opacity: alpha,
+
+ } );
+ edgeMaterial.userData.conditionalEdgeMaterial.color.convertSRGBToLinear();
}
- // If it is root object then finalize this object and compute construction steps
- if ( ! parentParseScope.isFromParse ) {
+ material.userData.code = code;
+ material.name = name;
- this.finalizeObject( parseScope );
- this.computeConstructionSteps( parseScope.groupObject );
+ material.userData.edgeMaterial = edgeMaterial;
+
+ this.addMaterial( material );
+
+ return material;
}
- return parseScope;
+ computeConstructionSteps( model ) {
- function loadSubobject( subobject ) {
+ // Sets userdata.constructionStep number in Group objects and userData.numConstructionSteps number in the root Group object.
- return scope.cache.loadData( subobject.fileName ).then( function ( text ) {
+ let stepNumber = 0;
- return scope.processObject( text, subobject, url, parseScope );
+ model.traverse( c => {
- } ).catch( function () {
+ if ( c.isGroup ) {
- console.warn( 'LDrawLoader: Subobject "' + subobject.fileName + '" could not be found.' );
- return null;
+ if ( c.userData.startingConstructionStep ) {
- } );
+ stepNumber ++;
+
+ }
+
+ c.userData.constructionStep = stepNumber;
}
+ } );
+
+ model.userData.numConstructionSteps = stepNumber + 1;
+
}
}

examples/jsm/loaders/LUT3dlLoader.js

@@ -1,11 +1,11 @@
// http://download.autodesk.com/us/systemdocs/help/2011/lustre/index.html?url=./files/WSc4e151a45a3b785a24c3d9a411df9298473-7ffd.htm,topicNumber=d0e9492
-
+// https://community.foundry.com/discuss/topic/103636/format-spec-for-3dl?mode=Post&postID=895258
import {
Loader,
FileLoader,
DataTexture,
DataTexture3D,
- RGBFormat,
+ RGBAFormat,
UnsignedByteType,
ClampToEdgeWrapping,
LinearFilter,
@@ -69,7 +69,7 @@
}
- const dataArray = new Array( size * size * size * 3 );
+ const dataArray = new Array( size * size * size * 4 );
let index = 0;
let maxOutputValue = 0.0;
for ( let i = 1, l = lines.length; i < l; i ++ ) {
@@ -88,21 +88,26 @@
// b grows first, then g, then r
const pixelIndex = bLayer * size * size + gLayer * size + rLayer;
- dataArray[ 3 * pixelIndex + 0 ] = r;
- dataArray[ 3 * pixelIndex + 1 ] = g;
- dataArray[ 3 * pixelIndex + 2 ] = b;
+ dataArray[ 4 * pixelIndex + 0 ] = r;
+ dataArray[ 4 * pixelIndex + 1 ] = g;
+ dataArray[ 4 * pixelIndex + 2 ] = b;
+ dataArray[ 4 * pixelIndex + 3 ] = 1.0;
index += 1;
}
- // Find the apparent bit depth of the stored RGB values and scale the
+ // Find the apparent bit depth of the stored RGB values and map the
// values to [ 0, 255 ].
const bits = Math.ceil( Math.log2( maxOutputValue ) );
const maxBitValue = Math.pow( 2.0, bits );
- for ( let i = 0, l = dataArray.length; i < l; i ++ ) {
+ for ( let i = 0, l = dataArray.length; i < l; i += 4 ) {
- const val = dataArray[ i ];
- dataArray[ i ] = 255 * val / maxBitValue;
+ const r = dataArray[ i + 0 ];
+ const g = dataArray[ i + 1 ];
+ const b = dataArray[ i + 2 ];
+ dataArray[ i + 0 ] = 255 * r / maxBitValue; // r
+ dataArray[ i + 1 ] = 255 * g / maxBitValue; // g
+ dataArray[ i + 2 ] = 255 * b / maxBitValue; // b
}
@@ -111,7 +116,7 @@
texture.image.data = data;
texture.image.width = size;
texture.image.height = size * size;
- texture.format = RGBFormat;
+ texture.format = RGBAFormat;
texture.type = UnsignedByteType;
texture.magFilter = LinearFilter;
texture.minFilter = LinearFilter;
@@ -125,7 +130,7 @@
texture3D.image.width = size;
texture3D.image.height = size;
texture3D.image.depth = size;
- texture3D.format = RGBFormat;
+ texture3D.format = RGBAFormat;
texture3D.type = UnsignedByteType;
texture3D.magFilter = LinearFilter;
texture3D.minFilter = LinearFilter;

examples/jsm/loaders/LUTCubeLoader.js

@@ -6,7 +6,6 @@
Vector3,
DataTexture,
DataTexture3D,
- RGBFormat,
UnsignedByteType,
ClampToEdgeWrapping,
LinearFilter,
@@ -77,7 +76,7 @@
// more precision than can be captured with Uint8Array.
const sizeToken = split[ 1 ];
size = parseFloat( sizeToken );
- data = new Uint8Array( size * size * size * 3 );
+ data = new Uint8Array( size * size * size * 4 );
break;
case 'DOMAIN_MIN':
domainMin.x = parseFloat( split[ 1 ] );
@@ -107,7 +106,8 @@
data[ currIndex + 0 ] = r * 255;
data[ currIndex + 1 ] = g * 255;
data[ currIndex + 2 ] = b * 255;
- currIndex += 3;
+ data[ currIndex + 3 ] = 255;
+ currIndex += 4;
}
@@ -117,7 +117,6 @@
texture.image.data = data;
texture.image.width = size;
texture.image.height = size * size;
- texture.format = RGBFormat;
texture.type = UnsignedByteType;
texture.magFilter = LinearFilter;
texture.minFilter = LinearFilter;
@@ -131,7 +130,6 @@
texture3D.image.width = size;
texture3D.image.height = size;
texture3D.image.depth = size;
- texture3D.format = RGBFormat;
texture3D.type = UnsignedByteType;
texture3D.magFilter = LinearFilter;
texture3D.minFilter = LinearFilter;

examples/jsm/loaders/MD2Loader.js

@@ -243,7 +243,7 @@
for ( let j = 0; j < 16; j ++ ) {
- const character = data.getUint8( offset + j, true );
+ const character = data.getUint8( offset + j );
if ( character === 0 ) break;
string[ j ] = character;
@@ -260,10 +260,10 @@
for ( let j = 0; j < header.num_vertices; j ++ ) {
- let x = data.getUint8( offset ++, true );
- let y = data.getUint8( offset ++, true );
- let z = data.getUint8( offset ++, true );
- const n = _normalData[ data.getUint8( offset ++, true ) ];
+ let x = data.getUint8( offset ++ );
+ let y = data.getUint8( offset ++ );
+ let z = data.getUint8( offset ++ );
+ const n = _normalData[ data.getUint8( offset ++ ) ];
x = x * scale.x + translation.x;
y = y * scale.y + translation.y;

examples/jsm/loaders/MTLLoader.js

@@ -8,7 +8,8 @@
MeshPhongMaterial,
RepeatWrapping,
TextureLoader,
- Vector2
+ Vector2,
+ sRGBEncoding
} from 'three';
/**
@@ -358,6 +359,12 @@
map.wrapS = scope.wrap;
map.wrapT = scope.wrap;
+ if ( mapType === 'map' || mapType === 'emissiveMap' ) {
+
+ map.encoding = sRGBEncoding;
+
+ }
+
params[ mapType ] = map;
}
@@ -377,21 +384,21 @@
// Diffuse color (color under white light) using RGB values
- params.color = new Color().fromArray( value );
+ params.color = new Color().fromArray( value ).convertSRGBToLinear();
break;
case 'ks':
// Specular color (color when light is reflected from shiny surface) using RGB values
- params.specular = new Color().fromArray( value );
+ params.specular = new Color().fromArray( value ).convertSRGBToLinear();
break;
case 'ke':
// Emissive using RGB values
- params.emissive = new Color().fromArray( value );
+ params.emissive = new Color().fromArray( value ).convertSRGBToLinear();
break;

examples/jsm/loaders/PCDLoader.js

@@ -303,9 +303,9 @@
if ( offset.rgb !== undefined ) {
- color.push( dataview.getUint8( ( PCDheader.points * offset.rgb ) + PCDheader.size[ 3 ] * i + 0 ) / 255.0 );
- color.push( dataview.getUint8( ( PCDheader.points * offset.rgb ) + PCDheader.size[ 3 ] * i + 1 ) / 255.0 );
color.push( dataview.getUint8( ( PCDheader.points * offset.rgb ) + PCDheader.size[ 3 ] * i + 2 ) / 255.0 );
+ color.push( dataview.getUint8( ( PCDheader.points * offset.rgb ) + PCDheader.size[ 3 ] * i + 1 ) / 255.0 );
+ color.push( dataview.getUint8( ( PCDheader.points * offset.rgb ) + PCDheader.size[ 3 ] * i + 0 ) / 255.0 );
}

examples/jsm/loaders/RGBELoader.js

@@ -4,8 +4,7 @@
FloatType,
HalfFloatType,
LinearEncoding,
- LinearFilter,
- RGBFormat,
+ LinearFilter
} from 'three';
// https://github.com/mrdoob/three.js/issues/5552
@@ -342,6 +341,7 @@
destArray[ destOffset + 0 ] = sourceArray[ sourceOffset + 0 ] * scale;
destArray[ destOffset + 1 ] = sourceArray[ sourceOffset + 1 ] * scale;
destArray[ destOffset + 2 ] = sourceArray[ sourceOffset + 2 ] * scale;
+ destArray[ destOffset + 3 ] = 1;
};
@@ -354,6 +354,7 @@
destArray[ destOffset + 0 ] = DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 0 ] * scale, 65504 ) );
destArray[ destOffset + 1 ] = DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 1 ] * scale, 65504 ) );
destArray[ destOffset + 2 ] = DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 2 ] * scale, 65504 ) );
+ destArray[ destOffset + 3 ] = DataUtils.toHalfFloat( 1 );
};
@@ -377,32 +378,30 @@
case FloatType:
numElements = image_rgba_data.length / 4;
- const floatArray = new Float32Array( numElements * 3 );
+ const floatArray = new Float32Array( numElements * 4 );
for ( let j = 0; j < numElements; j ++ ) {
- RGBEByteToRGBFloat( image_rgba_data, j * 4, floatArray, j * 3 );
+ RGBEByteToRGBFloat( image_rgba_data, j * 4, floatArray, j * 4 );
}
data = floatArray;
- format = RGBFormat;
type = FloatType;
break;
case HalfFloatType:
numElements = image_rgba_data.length / 4;
- const halfArray = new Uint16Array( numElements * 3 );
+ const halfArray = new Uint16Array( numElements * 4 );
for ( let j = 0; j < numElements; j ++ ) {
- RGBEByteToRGBHalf( image_rgba_data, j * 4, halfArray, j * 3 );
+ RGBEByteToRGBHalf( image_rgba_data, j * 4, halfArray, j * 4 );
}
data = halfArray;
- format = RGBFormat;
type = HalfFloatType;
break;

examples/jsm/loaders/RGBMLoader.js

@@ -328,7 +328,7 @@
var fd, foff = 0; // frames
var mgck = [ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a ];
- for ( var i = 0; i < 8; i ++ ) if ( data[ i ] != mgck[ i ] ) throw 'The input is not a PNG file!';
+ for ( var i = 0; i < 8; i ++ ) if ( data[ i ] != mgck[ i ] ) throw new Error( 'The input is not a PNG file!' );
while ( offset < data.length ) {

examples/jsm/loaders/STLLoader.js

@@ -151,7 +151,7 @@
for ( let i = 0, il = query.length; i < il; i ++ ) {
- if ( query[ i ] !== reader.getUint8( offset + i, false ) ) return false;
+ if ( query[ i ] !== reader.getUint8( offset + i ) ) return false;
}

examples/jsm/loaders/SVGLoader.js

@@ -129,7 +129,9 @@
case 'use':
style = parseStyle( node, style );
- const usedNodeId = node.href.baseVal.substring( 1 );
+
+ const href = node.getAttributeNS( 'http://www.w3.org/1999/xlink', 'href' ) || '';
+ const usedNodeId = href.substring( 1 );
const usedNode = node.viewportElement.getElementById( usedNodeId );
if ( usedNode ) {
@@ -659,9 +661,14 @@
for ( let j = 0; j < selectorList.length; j ++ ) {
+ // Remove empty rules
+ const definitions = Object.fromEntries(
+ Object.entries( stylesheet.style ).filter( ( [ , v ] ) => v !== '' )
+ );
+
stylesheets[ selectorList[ j ] ] = Object.assign(
stylesheets[ selectorList[ j ] ] || {},
- stylesheet.style
+ definitions
);
}

examples/jsm/loaders/VRMLLoader.js

@@ -24,8 +24,6 @@
Points,
PointsMaterial,
Quaternion,
- RGBAFormat,
- RGBFormat,
RepeatWrapping,
Scene,
ShapeUtils,
@@ -1265,6 +1263,7 @@
color.r = value;
color.g = value;
color.b = value;
+ color.a = 1;
break;
case TEXTURE_TYPE.INTENSITY_ALPHA:
@@ -1281,6 +1280,7 @@
color.r = parseInt( '0x' + hex.substring( 2, 4 ) );
color.g = parseInt( '0x' + hex.substring( 4, 6 ) );
color.b = parseInt( '0x' + hex.substring( 6, 8 ) );
+ color.a = 1;
break;
case TEXTURE_TYPE.RGBA:
@@ -1348,11 +1348,9 @@
const height = fieldValues[ 1 ];
const num_components = fieldValues[ 2 ];
- const useAlpha = ( num_components === 2 || num_components === 4 );
const textureType = getTextureType( num_components );
- const size = ( ( useAlpha === true ) ? 4 : 3 ) * ( width * height );
- const data = new Uint8Array( size );
+ const data = new Uint8Array( 4 * width * height );
const color = { r: 0, g: 0, b: 0, a: 0 };
@@ -1360,8 +1358,6 @@
parseHexColor( fieldValues[ j ], textureType, color );
- if ( useAlpha === true ) {
-
const stride = k * 4;
data[ stride + 0 ] = color.r;
@@ -1369,19 +1365,9 @@
data[ stride + 2 ] = color.b;
data[ stride + 3 ] = color.a;
- } else {
-
- const stride = k * 3;
-
- data[ stride + 0 ] = color.r;
- data[ stride + 1 ] = color.g;
- data[ stride + 2 ] = color.b;
-
- }
-
}
- texture = new DataTexture( data, width, height, ( useAlpha === true ) ? RGBAFormat : RGBFormat );
+ texture = new DataTexture( data, width, height );
texture.needsUpdate = true;
texture.__type = textureType; // needed for material modifications
break;

examples/jsm/math/ConvexHull.js

@@ -46,17 +46,9 @@
setFromPoints( points ) {
- if ( Array.isArray( points ) !== true ) {
+ // The algorithm needs at least four points.
- console.error( 'THREE.ConvexHull: Points parameter is not an array.' );
-
- }
-
- if ( points.length < 4 ) {
-
- console.error( 'THREE.ConvexHull: The algorithm needs at least four points.' );
-
- }
+ if ( points.length >= 4 ) {
this.makeEmpty();
@@ -68,6 +60,8 @@
this.compute();
+ }
+
return this;
}

examples/jsm/misc/Volume.js

@@ -99,7 +99,7 @@
case 'unsigned long long int' :
case 'uint64' :
case 'uint64_t' :
- throw 'Error in Volume constructor : this type is not supported in JavaScript';
+ throw new Error( 'Error in Volume constructor : this type is not supported in JavaScript' );
break;
case 'Float32' :
case 'float32' :
@@ -118,7 +118,7 @@
if ( this.data.length !== this.xLength * this.yLength * this.zLength ) {
- throw 'Error in Volume constructor, lengths are not matching arrayBuffer size';
+ throw new Error( 'Error in Volume constructor, lengths are not matching arrayBuffer size' );
}

examples/jsm/modifiers/CurveModifier.js

@@ -1,11 +1,11 @@
// Original src: https://github.com/zz85/threejs-path-flow
-const BITS = 3;
+const CHANNELS = 4;
const TEXTURE_WIDTH = 1024;
const TEXTURE_HEIGHT = 4;
import {
DataTexture,
- RGBFormat,
+ RGBAFormat,
FloatType,
RepeatWrapping,
Mesh,
@@ -22,12 +22,12 @@
*/
export function initSplineTexture( numberOfCurves = 1 ) {
- const dataArray = new Float32Array( TEXTURE_WIDTH * TEXTURE_HEIGHT * numberOfCurves * BITS );
+ const dataArray = new Float32Array( TEXTURE_WIDTH * TEXTURE_HEIGHT * numberOfCurves * CHANNELS );
const dataTexture = new DataTexture(
dataArray,
TEXTURE_WIDTH,
TEXTURE_HEIGHT * numberOfCurves,
- RGBFormat,
+ RGBAFormat,
FloatType
);
@@ -80,10 +80,11 @@
const image = texture.image;
const { data } = image;
- const i = BITS * TEXTURE_WIDTH * o; // Row Offset
- data[ index * BITS + i + 0 ] = x;
- data[ index * BITS + i + 1 ] = y;
- data[ index * BITS + i + 2 ] = z;
+ const i = CHANNELS * TEXTURE_WIDTH * o; // Row Offset
+ data[ index * CHANNELS + i + 0 ] = x;
+ data[ index * CHANNELS + i + 1 ] = y;
+ data[ index * CHANNELS + i + 2 ] = z;
+ data[ index * CHANNELS + i + 3 ] = 1;
}

examples/jsm/modifiers/EdgeSplitModifier.js

@@ -181,12 +181,6 @@
if ( geometry.index == null ) {
- if ( BufferGeometryUtils === undefined ) {
-
- throw 'THREE.EdgeSplitModifier relies on BufferGeometryUtils';
-
- }
-
geometry = BufferGeometryUtils.mergeVertices( geometry );
}

examples/jsm/modifiers/SimplifyModifier.js

@@ -17,16 +17,6 @@
class SimplifyModifier {
- constructor() {
-
- if ( BufferGeometryUtils === undefined ) {
-
- throw 'THREE.SimplifyModifier relies on BufferGeometryUtils';
-
- }
-
- }
-
modify( geometry, count ) {
if ( geometry.isGeometry === true ) {

examples/jsm/node-editor/accessors/NormalEditor.js

@@ -1,21 +1,21 @@
-import { ObjectNode, SelectInput, LabelElement } from '../../libs/flow.module.js';
+import { SelectInput, Element } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { NormalNode } from '../../renderers/nodes/Nodes.js';
-export class NormalEditor extends ObjectNode {
+export class NormalEditor extends BaseNode {
constructor() {
const node = new NormalNode();
- super( 'Normal', 3, node, 250 );
-
- this.title.setStyle( 'red' );
+ super( 'Normal', 3, node, 200 );
const optionsField = new SelectInput( [
{ name: 'Local', value: NormalNode.LOCAL },
{ name: 'World', value: NormalNode.WORLD },
- { name: 'View', value: NormalNode.VIEW }
- ] ).onChange( () => {
+ { name: 'View', value: NormalNode.VIEW },
+ { name: 'Geometry', value: NormalNode.GEOMETRY }
+ ], NormalNode.LOCAL ).onChange( () => {
node.scope = optionsField.getValue();
@@ -23,7 +23,7 @@
} );
- this.add( new LabelElement( 'Scope' ).add( optionsField ) );
+ this.add( new Element().add( optionsField ) );
}

examples/jsm/node-editor/accessors/PositionEditor.js

@@ -1,21 +1,21 @@
-import { ObjectNode, SelectInput, LabelElement } from '../../libs/flow.module.js';
+import { SelectInput, Element } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { PositionNode } from '../../renderers/nodes/Nodes.js';
-export class PositionEditor extends ObjectNode {
+export class PositionEditor extends BaseNode {
constructor() {
const node = new PositionNode();
- super( 'Position', 3, node, 250 );
-
- this.title.setStyle( 'red' );
+ super( 'Position', 3, node, 200 );
const optionsField = new SelectInput( [
{ name: 'Local', value: PositionNode.LOCAL },
{ name: 'World', value: PositionNode.WORLD },
- { name: 'View', value: PositionNode.VIEW }
- ] ).onChange( () => {
+ { name: 'View', value: PositionNode.VIEW },
+ { name: 'View Direction', value: PositionNode.VIEW_DIRECTION }
+ ], PositionNode.LOCAL ).onChange( () => {
node.scope = optionsField.getValue();
@@ -23,7 +23,7 @@
} );
- this.add( new LabelElement( 'Scope' ).add( optionsField ) );
+ this.add( new Element().add( optionsField ) );
}

examples/jsm/node-editor/accessors/UVEditor.js

@@ -1,19 +1,18 @@
-import { ObjectNode, SelectInput, LabelElement } from '../../libs/flow.module.js';
+import { SelectInput, LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { UVNode } from '../../renderers/nodes/Nodes.js';
-export class UVEditor extends ObjectNode {
+export class UVEditor extends BaseNode {
constructor() {
const node = new UVNode();
- super( 'UV', 2, node, 250 );
+ super( 'UV', 2, node, 200 );
- this.title.setStyle( 'red' );
+ const optionsField = new SelectInput( [ '1', '2' ], 0 ).onChange( () => {
- const optionsField = new SelectInput( [ '1', '2' ] ).onChange( () => {
-
- node.value = Number( optionsField.getValue() );
+ node.index = Number( optionsField.getValue() );
this.invalidate();

examples/jsm/node-editor/core/BaseNode.js

@@ -0,0 +1,83 @@
+import { ObjectNode } from '../../libs/flow.module.js';
+
+export class BaseNode extends ObjectNode {
+
+ constructor( name, inputLength, value = null, width = 300 ) {
+
+ const getObjectCallback = ( /*output = null*/ ) => {
+
+ return this.value;
+
+ };
+
+ super( name, inputLength, getObjectCallback, width );
+
+ this.setOutputColor( this.getColorValueFromValue( value ) );
+
+ this.editor = null;
+
+ this.value = value;
+
+ this.onValidElement = ( inputElement, outputElement ) => {
+
+ const outputObject = outputElement.getObject();
+
+ if ( ! outputObject || ! outputObject.isNode ) {
+
+ return false;
+
+ }
+
+ };
+
+ }
+
+ serialize( data ) {
+
+ super.serialize( data );
+
+ delete data.width;
+
+ }
+
+ deserialize( data ) {
+
+ delete data.width;
+
+ super.deserialize( data );
+
+ }
+
+ setEditor( value ) {
+
+ this.editor = value;
+
+ return this;
+
+ }
+
+ getColorValueFromValue( value ) {
+
+ if ( ! value ) return;
+
+ if ( value.isMaterial === true ) {
+
+ return 'forestgreen';
+
+ } else if ( value.isObject3D === true ) {
+
+ return 'orange';
+
+ }
+
+ }
+
+ add( element ) {
+
+ element.onValid( ( source, target ) => this.onValidElement( source, target ) );
+
+ return super.add( element );
+
+ }
+
+}

examples/jsm/node-editor/display/BlendEditor.js

@@ -1,16 +1,17 @@
-import { ObjectNode, LabelElement } from '../../libs/flow.module.js';
+import { LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { MathNode, FloatNode } from '../../renderers/nodes/Nodes.js';
const NULL_VALUE = new FloatNode();
const ONE_VALUE = new FloatNode( 1 );
-export class BlendEditor extends ObjectNode {
+export class BlendEditor extends BaseNode {
constructor() {
const node = new MathNode( MathNode.MIX, NULL_VALUE, NULL_VALUE, ONE_VALUE );
- super( 'Blend', 3, node );
+ super( 'Blend', 3, node, 200 );
const aElement = new LabelElement( 'Base' ).setInput( 3 );
const bElement = new LabelElement( 'Blend' ).setInput( 3 );
@@ -18,19 +19,19 @@
aElement.onConnect( () => {
- node.aNode = aElement.linkedExtra || NULL_VALUE;
+ node.aNode = aElement.getLinkedObject() || NULL_VALUE;
} );
bElement.onConnect( () => {
- node.bNode = bElement.linkedExtra || NULL_VALUE;
+ node.bNode = bElement.getLinkedObject() || NULL_VALUE;
} );
cElement.onConnect( () => {
- node.cNode = cElement.linkedExtra || ONE_VALUE;
+ node.cNode = cElement.getLinkedObject() || ONE_VALUE;
} );

examples/jsm/node-editor/examples/animate-uv.json

@@ -1 +1 @@
-{"objects":{"325":{"x":1718,"y":136,"width":"300px","elements":[326,328,329,330,331],"id":325,"type":"StandardMaterialEditor"},"326":{"style":"blue","title":"Standard Material","id":326,"type":"TitleElement"},"328":{"inputLength":3,"links":[394],"label":"Color","id":328,"type":"LabelElement"},"329":{"inputLength":1,"label":"Opacity","id":329,"type":"LabelElement"},"330":{"inputLength":1,"label":"Metalness","id":330,"type":"LabelElement"},"331":{"inputLength":1,"label":"Roughness","id":331,"type":"LabelElement"},"337":{"x":155,"y":230,"width":"250px","elements":[338,344,345,342],"id":337,"type":"TimerEditor"},"338":{"outputLength":1,"title":"Timer","icon":"ti ti-clock","id":338,"type":"TitleElement"},"340":{"value":16.881,"id":340,"type":"NumberInput"},"341":{"value":0.04,"id":341,"type":"NumberInput"},"342":{"inputs":[343],"id":342,"type":"Element"},"343":{"value":"Reset","id":343,"type":"ButtonInput"},"344":{"inputs":[340],"label":"Value","id":344,"type":"LabelElement"},"345":{"inputs":[341],"label":"Scale","id":345,"type":"LabelElement"},"353":{"x":202,"y":79,"width":"250px","elements":[354,357],"id":353,"type":"UVEditor"},"354":{"outputLength":2,"style":"red","title":"UV","id":354,"type":"TitleElement"},"356":{"options":["1","2"],"value":"0","id":356,"type":"SelectInput"},"357":{"inputs":[356],"label":"Channel","id":357,"type":"LabelElement"},"361":{"x":612,"y":102,"width":"250px","elements":[362,367,365,366],"id":361,"type":"OperatorEditor"},"362":{"outputLength":1,"title":"Operator","id":362,"type":"TitleElement"},"364":{"options":[{"name":"+ Addition","value":"+"},{"name":"- Subtraction","value":"-"},{"name":"* Multiplication","value":"*"},{"name":"/ Division","value":"/"}],"value":"+","id":364,"type":"SelectInput"},"365":{"inputLength":3,"links":[354],"label":"A","id":365,"type":"LabelElement"},"366":{"inputLength":3,"links":[338],"label":"B","id":366,"type":"LabelElement"},"367":{"inputs":[364],"label":"Operator","id":367,"type":"LabelElement"},"373":{"x":1047,"y":158,"width":"250px","elements":[374,379,377,378],"id":373,"type":"OperatorEditor"},"374":{"outputLength":1,"title":"Operator","id":374,"type":"TitleElement"},"376":{"options":[{"name":"+ Addition","value":"+"},{"name":"- Subtraction","value":"-"},{"name":"* Multiplication","value":"*"},{"name":"/ Division","value":"/"}],"value":"*","id":376,"type":"SelectInput"},"377":{"inputLength":3,"links":[362],"label":"A","id":377,"type":"LabelElement"},"378":{"inputLength":3,"links":[386],"label":"B","id":378,"type":"LabelElement"},"379":{"inputs":[376],"label":"Operator","id":379,"type":"LabelElement"},"385":{"x":601,"y":345,"width":"250px","elements":[386,389],"id":385,"type":"FloatEditor"},"386":{"outputLength":1,"title":"Float","icon":"ti ti-box-multiple-1","id":386,"type":"TitleElement"},"388":{"value":24.12,"id":388,"type":"NumberInput"},"389":{"inputs":[388],"label":"Value","id":389,"type":"LabelElement"},"393":{"x":1402,"y":14,"width":"200px","elements":[394,396],"id":393,"type":"CheckerEditor"},"394":{"outputLength":1,"title":"Checker","id":394,"type":"TitleElement"},"396":{"inputLength":2,"links":[374],"label":"UV","id":396,"type":"LabelElement"}},"nodes":[325,337,353,361,373,385,393],"id":0,"type":"Canvas"}
\ No newline at end of file
+{"objects":{"733":{"x":1718,"y":136,"width":300,"elements":[734,736,737,738,739],"id":733,"type":"StandardMaterialEditor"},"734":{"outputLength":1,"style":"blue","title":"Standard Material","id":734,"type":"TitleElement"},"736":{"inputLength":3,"inputs":[740],"links":[809],"label":"Color","id":736,"type":"LabelElement"},"737":{"inputLength":1,"inputs":[741],"label":"Opacity","icon":"ti ti-layers-subtract","id":737,"type":"LabelElement"},"738":{"inputLength":1,"inputs":[743],"label":"Metalness","id":738,"type":"LabelElement"},"739":{"inputLength":1,"inputs":[745],"label":"Roughness","id":739,"type":"LabelElement"},"740":{"value":16777215,"id":740,"type":"ColorInput"},"741":{"min":0,"max":1,"value":1,"id":741,"type":"SliderInput"},"743":{"min":0,"max":1,"value":0,"id":743,"type":"SliderInput"},"745":{"min":0,"max":1,"value":1,"id":745,"type":"SliderInput"},"752":{"x":155,"y":230,"width":250,"elements":[753,759,760,757],"id":752,"type":"TimerEditor"},"753":{"outputLength":1,"title":"Timer","icon":"ti ti-clock","id":753,"type":"TitleElement"},"755":{"value":0.218,"id":755,"type":"NumberInput"},"756":{"value":0.04,"id":756,"type":"NumberInput"},"757":{"inputs":[758],"id":757,"type":"Element"},"758":{"value":"Reset","id":758,"type":"ButtonInput"},"759":{"inputs":[755],"id":759,"type":"Element"},"760":{"inputs":[756],"label":"Scale","id":760,"type":"LabelElement"},"768":{"x":202,"y":79,"width":250,"elements":[769,772],"id":768,"type":"UVEditor"},"769":{"outputLength":2,"style":"red","title":"UV","id":769,"type":"TitleElement"},"771":{"options":["1","2"],"value":"0","id":771,"type":"SelectInput"},"772":{"inputs":[771],"label":"Channel","id":772,"type":"LabelElement"},"776":{"x":612,"y":102,"width":250,"elements":[777,782,780,781],"id":776,"type":"OperatorEditor"},"777":{"outputLength":1,"title":"Operator","id":777,"type":"TitleElement"},"779":{"options":[{"name":"+ Addition","value":"+"},{"name":"- Subtraction","value":"-"},{"name":"* Multiplication","value":"*"},{"name":"/ Division","value":"/"}],"value":"+","id":779,"type":"SelectInput"},"780":{"inputLength":3,"links":[769],"label":"A","id":780,"type":"LabelElement"},"781":{"inputLength":3,"links":[753],"label":"B","id":781,"type":"LabelElement"},"782":{"inputs":[779],"id":782,"type":"Element"},"788":{"x":1047,"y":158,"width":250,"elements":[789,794,792,793],"id":788,"type":"OperatorEditor"},"789":{"outputLength":1,"title":"Operator","id":789,"type":"TitleElement"},"791":{"options":[{"name":"+ Addition","value":"+"},{"name":"- Subtraction","value":"-"},{"name":"* Multiplication","value":"*"},{"name":"/ Division","value":"/"}],"value":"*","id":791,"type":"SelectInput"},"792":{"inputLength":3,"links":[777],"label":"A","id":792,"type":"LabelElement"},"793":{"inputLength":3,"links":[801],"label":"B","id":793,"type":"LabelElement"},"794":{"inputs":[791],"id":794,"type":"Element"},"800":{"x":601,"y":345,"width":250,"elements":[801,804],"id":800,"type":"FloatEditor"},"801":{"outputLength":1,"title":"Float","icon":"ti ti-box-multiple-1","id":801,"type":"TitleElement"},"803":{"value":24.12,"id":803,"type":"NumberInput"},"804":{"inputs":[803],"id":804,"type":"Element"},"808":{"x":1402,"y":14,"width":200,"elements":[809,811],"id":808,"type":"CheckerEditor"},"809":{"outputLength":1,"title":"Checker","id":809,"type":"TitleElement"},"811":{"inputLength":2,"links":[789],"label":"UV","id":811,"type":"LabelElement"},"837":{"x":2160,"y":128,"width":300,"elements":[838,841,851,852,853,854],"id":837,"type":"MeshEditor"},"838":{"outputLength":1,"title":"Mesh","id":838,"type":"TitleElement"},"840":{"value":"Stanford_Bunny","id":840,"type":"StringInput"},"841":{"inputs":[840],"label":"Name","id":841,"type":"LabelElement"},"842":{"value":0,"id":842,"type":"NumberInput"},"843":{"value":0,"id":843,"type":"NumberInput"},"844":{"value":10,"id":844,"type":"NumberInput"},"845":{"value":0,"id":845,"type":"NumberInput"},"846":{"value":0,"id":846,"type":"NumberInput"},"847":{"value":0,"id":847,"type":"NumberInput"},"848":{"value":100,"id":848,"type":"NumberInput"},"849":{"value":100,"id":849,"type":"NumberInput"},"850":{"value":100,"id":850,"type":"NumberInput"},"851":{"inputs":[842,843,844],"label":"Position","id":851,"type":"LabelElement"},"852":{"inputs":[845,846,847],"label":"Rotation","id":852,"type":"LabelElement"},"853":{"inputs":[848,849,850],"label":"Scale","id":853,"type":"LabelElement"},"854":{"inputLength":1,"links":[734],"label":"Material","id":854,"type":"LabelElement"}},"nodes":[733,752,768,776,788,800,808,837],"id":2,"type":"Canvas"}
\ No newline at end of file

examples/jsm/node-editor/examples/fake-top-light.json

@@ -1 +1 @@
-{"objects":{"575":{"x":885,"y":119,"width":"300px","elements":[576,578,579,580,581],"id":575,"type":"StandardMaterialEditor"},"576":{"style":"blue","title":"Standard Material","id":576,"type":"TitleElement"},"578":{"inputLength":3,"links":[595],"label":"Color","id":578,"type":"LabelElement"},"579":{"inputLength":1,"label":"Opacity","id":579,"type":"LabelElement"},"580":{"inputLength":1,"label":"Metalness","id":580,"type":"LabelElement"},"581":{"inputLength":1,"label":"Roughness","id":581,"type":"LabelElement"},"587":{"x":73,"y":296,"width":"","elements":[588,593],"id":587,"type":"Vector3Editor"},"588":{"outputLength":3,"title":"Vector 3","icon":"ti ti-box-multiple-3","id":588,"type":"TitleElement"},"590":{"value":0,"id":590,"type":"NumberInput"},"591":{"value":1,"id":591,"type":"NumberInput"},"592":{"value":0,"id":592,"type":"NumberInput"},"593":{"inputs":[590,591,592],"label":"Values","id":593,"type":"LabelElement"},"594":{"x":541,"y":199,"width":"200px","elements":[595,597,598],"id":594,"type":"DotEditor"},"595":{"outputLength":1,"title":"Dot Product","id":595,"type":"TitleElement"},"597":{"inputLength":3,"links":[600],"label":"A","id":597,"type":"LabelElement"},"598":{"inputLength":3,"links":[588],"label":"B","id":598,"type":"LabelElement"},"599":{"x":106,"y":158,"width":"250px","elements":[600,603],"id":599,"type":"NormalEditor"},"600":{"outputLength":3,"style":"red","title":"Normal","id":600,"type":"TitleElement"},"602":{"options":[{"name":"Local","value":"local"},{"name":"World","value":"world"},{"name":"View","value":"view"}],"value":"world","id":602,"type":"SelectInput"},"603":{"inputs":[602],"label":"Scope","id":603,"type":"LabelElement"}},"nodes":[575,587,594,599],"id":0,"type":"Canvas"}
\ No newline at end of file
+{"objects":{"389":{"x":885,"y":119,"width":300,"elements":[390,392,393,394,395],"id":389,"type":"StandardMaterialEditor"},"390":{"outputLength":1,"style":"blue","title":"Standard Material","id":390,"type":"TitleElement"},"392":{"inputLength":3,"inputs":[396],"links":[421],"label":"Color","id":392,"type":"LabelElement"},"393":{"inputLength":1,"inputs":[397],"label":"Opacity","icon":"ti ti-layers-subtract","id":393,"type":"LabelElement"},"394":{"inputLength":1,"inputs":[399],"label":"Metalness","id":394,"type":"LabelElement"},"395":{"inputLength":1,"inputs":[401],"label":"Roughness","id":395,"type":"LabelElement"},"396":{"value":16777215,"id":396,"type":"ColorInput"},"397":{"min":0,"max":1,"value":1,"id":397,"type":"SliderInput"},"399":{"min":0,"max":1,"value":0,"id":399,"type":"SliderInput"},"401":{"min":0,"max":1,"value":1,"id":401,"type":"SliderInput"},"408":{"x":73,"y":296,"width":325,"elements":[409,414],"id":408,"type":"Vector3Editor"},"409":{"outputLength":3,"title":"Vector 3","icon":"ti ti-box-multiple-3","id":409,"type":"TitleElement"},"411":{"value":0,"id":411,"type":"NumberInput"},"412":{"value":1,"id":412,"type":"NumberInput"},"413":{"value":0,"id":413,"type":"NumberInput"},"414":{"inputs":[411,412,413],"label":"Values","id":414,"type":"LabelElement"},"420":{"x":541,"y":199,"width":200,"elements":[421,423,424],"id":420,"type":"DotEditor"},"421":{"outputLength":1,"title":"Dot Product","id":421,"type":"TitleElement"},"423":{"inputLength":3,"links":[429],"label":"A","id":423,"type":"LabelElement"},"424":{"inputLength":3,"links":[409],"label":"B","id":424,"type":"LabelElement"},"428":{"x":106,"y":158,"width":250,"elements":[429,432],"id":428,"type":"NormalEditor"},"429":{"outputLength":3,"style":"red","title":"Normal","id":429,"type":"TitleElement"},"431":{"options":[{"name":"Local","value":"local"},{"name":"World","value":"world"},{"name":"View","value":"view"}],"value":"world","id":431,"type":"SelectInput"},"432":{"inputs":[431],"id":432,"type":"Element"},"473":{"x":1314,"y":113,"width":300,"elements":[474,477,487,488,489,490],"id":473,"type":"MeshEditor"},"474":{"outputLength":1,"title":"Mesh","id":474,"type":"TitleElement"},"476":{"value":"Stanford_Bunny","id":476,"type":"StringInput"},"477":{"inputs":[476],"label":"Name","id":477,"type":"LabelElement"},"478":{"value":0,"id":478,"type":"NumberInput"},"479":{"value":0,"id":479,"type":"NumberInput"},"480":{"value":10,"id":480,"type":"NumberInput"},"481":{"value":0,"id":481,"type":"NumberInput"},"482":{"value":0,"id":482,"type":"NumberInput"},"483":{"value":0,"id":483,"type":"NumberInput"},"484":{"value":100,"id":484,"type":"NumberInput"},"485":{"value":100,"id":485,"type":"NumberInput"},"486":{"value":100,"id":486,"type":"NumberInput"},"487":{"inputs":[478,479,480],"label":"Position","id":487,"type":"LabelElement"},"488":{"inputs":[481,482,483],"label":"Rotation","id":488,"type":"LabelElement"},"489":{"inputs":[484,485,486],"label":"Scale","id":489,"type":"LabelElement"},"490":{"inputLength":1,"links":[390],"label":"Material","id":490,"type":"LabelElement"}},"nodes":[389,408,420,428,473],"id":2,"type":"Canvas"}
\ No newline at end of file

examples/jsm/node-editor/examples/oscillator-color.json

@@ -1 +1 @@
-{"objects":{"131":{"x":1602,"y":-3,"width":"300px","elements":[132,134,135,136,137],"id":131,"type":"StandardMaterialEditor"},"132":{"style":"blue","title":"Standard Material","id":132,"type":"TitleElement"},"134":{"inputLength":3,"links":[170],"label":"Color","id":134,"type":"LabelElement"},"135":{"inputLength":1,"label":"Opacity","id":135,"type":"LabelElement"},"136":{"inputLength":1,"label":"Metalness","id":136,"type":"LabelElement"},"137":{"inputLength":1,"label":"Roughness","id":137,"type":"LabelElement"},"143":{"x":123,"y":207,"width":"250px","elements":[144,150,151,148],"id":143,"type":"TimerEditor"},"144":{"outputLength":1,"title":"Timer","icon":"ti ti-clock","id":144,"type":"TitleElement"},"146":{"value":7.286,"id":146,"type":"NumberInput"},"147":{"value":0.37,"id":147,"type":"NumberInput"},"148":{"inputs":[149],"id":148,"type":"Element"},"149":{"value":"Reset","id":149,"type":"ButtonInput"},"150":{"inputs":[146],"label":"Value","id":150,"type":"LabelElement"},"151":{"inputs":[147],"label":"Scale","id":151,"type":"LabelElement"},"159":{"x":485,"y":94,"width":"250px","elements":[160,164,163],"id":159,"type":"OscillatorEditor"},"160":{"outputLength":1,"title":"Oscillator","id":160,"type":"TitleElement"},"162":{"options":[{"name":"Sine","value":"sine"},{"name":"Square","value":"square"},{"name":"Triangle","value":"triangle"},{"name":"Sawtooth","value":"sawtooth"}],"value":"sine","id":162,"type":"SelectInput"},"163":{"inputLength":1,"links":[144],"label":"Time","id":163,"type":"LabelElement"},"164":{"inputs":[162],"label":"Method","id":164,"type":"LabelElement"},"169":{"x":1208,"y":66,"width":"","elements":[170,172,173,174],"id":169,"type":"BlendEditor"},"170":{"outputLength":3,"title":"Blend","id":170,"type":"TitleElement"},"172":{"inputLength":3,"links":[180],"label":"Base","id":172,"type":"LabelElement"},"173":{"inputLength":3,"links":[200],"label":"Blend","id":173,"type":"LabelElement"},"174":{"inputLength":1,"links":[160],"label":"Opacity","id":174,"type":"LabelElement"},"179":{"x":797,"y":-55,"width":"","elements":[180,187,188,189],"id":179,"type":"ColorEditor"},"180":{"outputLength":1,"title":"Color","icon":"ti ti-palette","id":180,"type":"TitleElement"},"182":{"value":16580865,"id":182,"type":"ColorInput"},"183":{"value":"#FD0101","id":183,"type":"StringInput"},"184":{"min":0,"max":1,"step":0.01,"value":0.996,"id":184,"type":"NumberInput"},"185":{"min":0,"max":1,"step":0.01,"value":0.004,"id":185,"type":"NumberInput"},"186":{"min":0,"max":1,"step":0.01,"value":0.004,"id":186,"type":"NumberInput"},"187":{"inputs":[182],"label":"Value","id":187,"type":"LabelElement"},"188":{"inputs":[183],"label":"Hex","id":188,"type":"LabelElement"},"189":{"inputs":[184,185,186],"label":"RGB","id":189,"type":"LabelElement"},"199":{"x":810,"y":220,"width":"","elements":[200,207,208,209],"id":199,"type":"ColorEditor"},"200":{"outputLength":1,"title":"Color","icon":"ti ti-palette","id":200,"type":"TitleElement"},"202":{"value":19455,"id":202,"type":"ColorInput"},"203":{"value":"#4BFF00","id":203,"type":"StringInput"},"204":{"min":0,"max":1,"step":0.01,"value":0,"id":204,"type":"NumberInput"},"205":{"min":0,"max":1,"step":0.01,"value":0.298,"id":205,"type":"NumberInput"},"206":{"min":0,"max":1,"step":0.01,"value":1,"id":206,"type":"NumberInput"},"207":{"inputs":[202],"label":"Value","id":207,"type":"LabelElement"},"208":{"inputs":[203],"label":"Hex","id":208,"type":"LabelElement"},"209":{"inputs":[204,205,206],"label":"RGB","id":209,"type":"LabelElement"}},"nodes":[131,143,159,169,179,199],"id":0,"type":"Canvas"}
\ No newline at end of file
+{"objects":{"247":{"x":1602,"y":-3,"width":300,"elements":[248,250,251,252,253],"id":247,"type":"StandardMaterialEditor"},"248":{"outputLength":1,"style":"blue","title":"Standard Material","id":248,"type":"TitleElement"},"250":{"inputLength":3,"inputs":[254],"links":[293],"label":"Color","id":250,"type":"LabelElement"},"251":{"inputLength":1,"inputs":[255],"label":"Opacity","icon":"ti ti-layers-subtract","id":251,"type":"LabelElement"},"252":{"inputLength":1,"inputs":[257],"label":"Metalness","id":252,"type":"LabelElement"},"253":{"inputLength":1,"inputs":[259],"label":"Roughness","id":253,"type":"LabelElement"},"254":{"value":16777215,"id":254,"type":"ColorInput"},"255":{"min":0,"max":1,"value":1,"id":255,"type":"SliderInput"},"257":{"min":0,"max":1,"value":0,"id":257,"type":"SliderInput"},"259":{"min":0,"max":1,"value":1,"id":259,"type":"SliderInput"},"266":{"x":123,"y":207,"width":250,"elements":[267,273,274,271],"id":266,"type":"TimerEditor"},"267":{"outputLength":1,"title":"Timer","icon":"ti ti-clock","id":267,"type":"TitleElement"},"269":{"value":1.985,"id":269,"type":"NumberInput"},"270":{"value":0.37,"id":270,"type":"NumberInput"},"271":{"inputs":[272],"id":271,"type":"Element"},"272":{"value":"Reset","id":272,"type":"ButtonInput"},"273":{"inputs":[269],"id":273,"type":"Element"},"274":{"inputs":[270],"label":"Scale","id":274,"type":"LabelElement"},"282":{"x":485,"y":94,"width":250,"elements":[283,287,286],"id":282,"type":"OscillatorEditor"},"283":{"outputLength":1,"title":"Oscillator","id":283,"type":"TitleElement"},"285":{"options":[{"name":"Sine","value":"sine"},{"name":"Square","value":"square"},{"name":"Triangle","value":"triangle"},{"name":"Sawtooth","value":"sawtooth"}],"value":"sine","id":285,"type":"SelectInput"},"286":{"inputLength":1,"links":[267],"label":"Time","id":286,"type":"LabelElement"},"287":{"inputs":[285],"id":287,"type":"Element"},"292":{"x":1208,"y":66,"width":200,"elements":[293,295,296,297],"id":292,"type":"BlendEditor"},"293":{"outputLength":3,"title":"Blend","id":293,"type":"TitleElement"},"295":{"inputLength":3,"links":[303],"label":"Base","id":295,"type":"LabelElement"},"296":{"inputLength":3,"links":[323],"label":"Blend","id":296,"type":"LabelElement"},"297":{"inputLength":1,"links":[283],"label":"Opacity","id":297,"type":"LabelElement"},"302":{"x":797,"y":-55,"width":300,"elements":[303,310,311,312],"id":302,"type":"ColorEditor"},"303":{"outputLength":1,"title":"Color","icon":"ti ti-palette","id":303,"type":"TitleElement"},"305":{"value":16580865,"id":305,"type":"ColorInput"},"306":{"value":"#FD0101","id":306,"type":"StringInput"},"307":{"min":0,"max":1,"step":0.01,"value":0.996,"id":307,"type":"NumberInput"},"308":{"min":0,"max":1,"step":0.01,"value":0.004,"id":308,"type":"NumberInput"},"309":{"min":0,"max":1,"step":0.01,"value":0.004,"id":309,"type":"NumberInput"},"310":{"inputs":[305],"id":310,"type":"Element"},"311":{"inputs":[306],"label":"Hex","id":311,"type":"LabelElement"},"312":{"inputs":[307,308,309],"label":"RGB","id":312,"type":"LabelElement"},"322":{"x":810,"y":220,"width":300,"elements":[323,330,331,332],"id":322,"type":"ColorEditor"},"323":{"outputLength":1,"title":"Color","icon":"ti ti-palette","id":323,"type":"TitleElement"},"325":{"value":19455,"id":325,"type":"ColorInput"},"326":{"value":"#004BFF","id":326,"type":"StringInput"},"327":{"min":0,"max":1,"step":0.01,"value":0,"id":327,"type":"NumberInput"},"328":{"min":0,"max":1,"step":0.01,"value":0.298,"id":328,"type":"NumberInput"},"329":{"min":0,"max":1,"step":0.01,"value":1,"id":329,"type":"NumberInput"},"330":{"inputs":[325],"id":330,"type":"Element"},"331":{"inputs":[326],"label":"Hex","id":331,"type":"LabelElement"},"332":{"inputs":[327,328,329],"label":"RGB","id":332,"type":"LabelElement"},"371":{"x":2064,"y":-17,"width":300,"elements":[372,375,385,386,387,388],"id":371,"type":"MeshEditor"},"372":{"outputLength":1,"title":"Mesh","id":372,"type":"TitleElement"},"374":{"value":"Stanford_Bunny","id":374,"type":"StringInput"},"375":{"inputs":[374],"label":"Name","id":375,"type":"LabelElement"},"376":{"value":0,"id":376,"type":"NumberInput"},"377":{"value":0,"id":377,"type":"NumberInput"},"378":{"value":10,"id":378,"type":"NumberInput"},"379":{"value":0,"id":379,"type":"NumberInput"},"380":{"value":0,"id":380,"type":"NumberInput"},"381":{"value":0,"id":381,"type":"NumberInput"},"382":{"value":100,"id":382,"type":"NumberInput"},"383":{"value":100,"id":383,"type":"NumberInput"},"384":{"value":100,"id":384,"type":"NumberInput"},"385":{"inputs":[376,377,378],"label":"Position","id":385,"type":"LabelElement"},"386":{"inputs":[379,380,381],"label":"Rotation","id":386,"type":"LabelElement"},"387":{"inputs":[382,383,384],"label":"Scale","id":387,"type":"LabelElement"},"388":{"inputLength":1,"links":[248],"label":"Material","id":388,"type":"LabelElement"}},"nodes":[247,266,282,292,302,322,371],"id":2,"type":"Canvas"}
\ No newline at end of file

examples/jsm/node-editor/examples/rim.json

@@ -1 +1 @@
-{"objects":{"52":{"x":1873,"y":248,"width":"300px","elements":[53,55,56,57,58],"id":52,"type":"StandardMaterialEditor"},"53":{"style":"blue","title":"Standard Material","id":53,"type":"TitleElement"},"55":{"inputLength":3,"links":[103],"label":"Color","id":55,"type":"LabelElement"},"56":{"inputLength":1,"label":"Opacity","id":56,"type":"LabelElement"},"57":{"inputLength":1,"label":"Metalness","id":57,"type":"LabelElement"},"58":{"inputLength":1,"links":[177],"label":"Roughness","id":58,"type":"LabelElement"},"64":{"x":506,"y":328,"width":"200px","elements":[65,67,68],"id":64,"type":"DotEditor"},"65":{"outputLength":1,"title":"Dot Product","id":65,"type":"TitleElement"},"67":{"inputLength":3,"links":[85],"label":"A","id":67,"type":"LabelElement"},"68":{"inputLength":3,"links":[73],"label":"B","id":68,"type":"LabelElement"},"72":{"x":33,"y":453,"width":"300px","elements":[73,78],"id":72,"type":"Vector3Editor"},"73":{"outputLength":3,"title":"Vector 3","icon":"ti ti-box-multiple-3","id":73,"type":"TitleElement"},"75":{"value":0,"id":75,"type":"NumberInput"},"76":{"value":0,"id":76,"type":"NumberInput"},"77":{"value":1.0,"id":77,"type":"NumberInput"},"78":{"inputs":[75,76,77],"label":"Values","id":78,"type":"LabelElement"},"84":{"x":75,"y":278,"width":"250px","elements":[85,88],"id":84,"type":"NormalEditor"},"85":{"outputLength":3,"style":"red","title":"Normal","id":85,"type":"TitleElement"},"87":{"options":[{"name":"Local","value":"local"},{"name":"World","value":"world"},{"name":"View","value":"view"}],"value":"view","id":87,"type":"SelectInput"},"88":{"inputs":[87],"label":"Scope","id":88,"type":"LabelElement"},"92":{"x":846,"y":353,"width":"300px","elements":[93,97,96],"id":92,"type":"InvertEditor"},"93":{"outputLength":1,"title":"Invert / Negate","id":93,"type":"TitleElement"},"95":{"options":[{"name":"Invert ( 1 - Source )","value":"invert"},{"name":"Negate ( - Source )","value":"negate"}],"value":"invert","id":95,"type":"SelectInput"},"96":{"inputLength":1,"links":[65],"label":"Source","id":96,"type":"LabelElement"},"97":{"inputs":[95],"label":"Method","id":97,"type":"LabelElement"},"102":{"x":1459,"y":146,"width":"300px","elements":[103,105,106,107],"id":102,"type":"BlendEditor"},"103":{"outputLength":3,"title":"Blend","id":103,"type":"TitleElement"},"105":{"inputLength":3,"links":[113],"label":"Base","id":105,"type":"LabelElement"},"106":{"inputLength":3,"links":[133],"label":"Blend","id":106,"type":"LabelElement"},"107":{"inputLength":1,"links":[161],"label":"Opacity","id":107,"type":"LabelElement"},"112":{"x":846,"y":17,"width":"300px","elements":[113,120,121,122],"id":112,"type":"ColorEditor"},"113":{"outputLength":1,"title":"Color","icon":"ti ti-palette","id":113,"type":"TitleElement"},"115":{"value":5058,"id":115,"type":"ColorInput"},"116":{"value":"#13C200","id":116,"type":"StringInput"},"117":{"min":0,"max":1,"step":0.01,"value":0,"id":117,"type":"NumberInput"},"118":{"min":0,"max":1,"step":0.01,"value":0.075,"id":118,"type":"NumberInput"},"119":{"min":0,"max":1,"step":0.01,"value":0.761,"id":119,"type":"NumberInput"},"120":{"inputs":[115],"label":"Value","id":120,"type":"LabelElement"},"121":{"inputs":[116],"label":"Hex","id":121,"type":"LabelElement"},"122":{"inputs":[117,118,119],"label":"RGB","id":122,"type":"LabelElement"},"132":{"x":844,"y":189,"width":"300px","elements":[133,140,141,142],"id":132,"type":"ColorEditor"},"133":{"outputLength":1,"title":"Color","icon":"ti ti-palette","id":133,"type":"TitleElement"},"135":{"value":16711680,"id":135,"type":"ColorInput"},"136":{"value":"#FF0000","id":136,"type":"StringInput"},"137":{"min":0,"max":1,"step":0.01,"value":1,"id":137,"type":"NumberInput"},"138":{"min":0,"max":1,"step":0.01,"value":0,"id":138,"type":"NumberInput"},"139":{"min":0,"max":1,"step":0.01,"value":0,"id":139,"type":"NumberInput"},"140":{"inputs":[135],"label":"Value","id":140,"type":"LabelElement"},"141":{"inputs":[136],"label":"Hex","id":141,"type":"LabelElement"},"142":{"inputs":[137,138,139],"label":"RGB","id":142,"type":"LabelElement"},"160":{"x":1241,"y":361,"width":"200px","elements":[161,163,164],"id":160,"type":"PowerEditor"},"161":{"outputLength":1,"title":"Power","id":161,"type":"TitleElement"},"163":{"inputLength":1,"links":[93],"label":"A","id":163,"type":"LabelElement"},"164":{"inputLength":1,"links":[169],"label":"B","id":164,"type":"LabelElement"},"168":{"x":852,"y":503,"width":"250px","elements":[169,172],"id":168,"type":"FloatEditor"},"169":{"outputLength":1,"title":"Float","icon":"ti ti-box-multiple-1","id":169,"type":"TitleElement"},"171":{"value":1.32,"id":171,"type":"NumberInput"},"172":{"inputs":[171],"label":"Value","id":172,"type":"LabelElement"},"176":{"x":1482,"y":449,"width":"300px","elements":[177,187,183,184,185],"id":176,"type":"SliderEditor"},"177":{"outputLength":1,"title":"Slider","icon":"ti ti-adjustments-horizontal","id":177,"type":"TitleElement"},"179":{"min":0,"max":1,"value":1,"id":179,"type":"SliderInput"},"181":{"value":0,"id":181,"type":"NumberInput"},"182":{"value":1,"id":182,"type":"NumberInput"},"183":{"inputs":[181],"label":"Min.","id":183,"type":"LabelElement"},"184":{"inputs":[182],"label":"Max.","id":184,"type":"LabelElement"},"185":{"inputs":[186],"id":185,"type":"Element"},"186":{"value":"More","id":186,"type":"ButtonInput"},"187":{"inputs":[179],"label":"Value","id":187,"type":"LabelElement"}},"nodes":[52,64,72,84,92,102,112,132,160,168,176],"id":0,"type":"Canvas"}
\ No newline at end of file
+{"objects":{"61":{"x":1873,"y":248,"width":300,"elements":[62,64,65,66,67],"id":61,"type":"StandardMaterialEditor"},"62":{"outputLength":1,"style":"blue","title":"Standard Material","id":62,"type":"TitleElement"},"64":{"inputLength":3,"inputs":[68],"links":[119],"label":"Color","id":64,"type":"LabelElement"},"65":{"inputLength":1,"inputs":[69],"label":"Opacity","icon":"ti ti-layers-subtract","id":65,"type":"LabelElement"},"66":{"inputLength":1,"inputs":[71],"label":"Metalness","id":66,"type":"LabelElement"},"67":{"inputLength":1,"inputs":[73],"links":[185],"label":"Roughness","id":67,"type":"LabelElement"},"68":{"value":16777215,"id":68,"type":"ColorInput"},"69":{"min":0,"max":1,"value":1,"id":69,"type":"SliderInput"},"71":{"min":0,"max":1,"value":0,"id":71,"type":"SliderInput"},"73":{"min":0,"max":1,"value":1,"id":73,"type":"SliderInput"},"80":{"x":506,"y":328,"width":200,"elements":[81,83,84],"id":80,"type":"DotEditor"},"81":{"outputLength":1,"title":"Dot Product","id":81,"type":"TitleElement"},"83":{"inputLength":3,"links":[101],"label":"A","id":83,"type":"LabelElement"},"84":{"inputLength":3,"links":[89],"label":"B","id":84,"type":"LabelElement"},"88":{"x":33,"y":453,"width":300,"elements":[89,94],"id":88,"type":"Vector3Editor"},"89":{"outputLength":3,"title":"Vector 3","icon":"ti ti-box-multiple-3","id":89,"type":"TitleElement"},"91":{"value":0,"id":91,"type":"NumberInput"},"92":{"value":0,"id":92,"type":"NumberInput"},"93":{"value":1,"id":93,"type":"NumberInput"},"94":{"inputs":[91,92,93],"label":"Values","id":94,"type":"LabelElement"},"100":{"x":75,"y":278,"width":250,"elements":[101,104],"id":100,"type":"NormalEditor"},"101":{"outputLength":3,"style":"red","title":"Normal","id":101,"type":"TitleElement"},"103":{"options":[{"name":"Local","value":"local"},{"name":"World","value":"world"},{"name":"View","value":"view"}],"value":"view","id":103,"type":"SelectInput"},"104":{"inputs":[103],"id":104,"type":"Element"},"108":{"x":846,"y":353,"width":300,"elements":[109,113,112],"id":108,"type":"InvertEditor"},"109":{"outputLength":1,"title":"Invert / Negate","id":109,"type":"TitleElement"},"111":{"options":[{"name":"Invert ( 1 - Source )","value":"invert"},{"name":"Negate ( - Source )","value":"negate"}],"value":"invert","id":111,"type":"SelectInput"},"112":{"inputLength":1,"links":[81],"label":"Source","id":112,"type":"LabelElement"},"113":{"inputs":[111],"label":"Method","id":113,"type":"LabelElement"},"118":{"x":1459,"y":146,"width":300,"elements":[119,121,122,123],"id":118,"type":"BlendEditor"},"119":{"outputLength":3,"title":"Blend","id":119,"type":"TitleElement"},"121":{"inputLength":3,"links":[129],"label":"Base","id":121,"type":"LabelElement"},"122":{"inputLength":3,"links":[149],"label":"Blend","id":122,"type":"LabelElement"},"123":{"inputLength":1,"links":[169],"label":"Opacity","id":123,"type":"LabelElement"},"128":{"x":846,"y":17,"width":300,"elements":[129,136,137,138],"id":128,"type":"ColorEditor"},"129":{"outputLength":1,"title":"Color","icon":"ti ti-palette","id":129,"type":"TitleElement"},"131":{"value":5058,"id":131,"type":"ColorInput"},"132":{"value":"#0013C2","id":132,"type":"StringInput"},"133":{"min":0,"max":1,"step":0.01,"value":0,"id":133,"type":"NumberInput"},"134":{"min":0,"max":1,"step":0.01,"value":0.075,"id":134,"type":"NumberInput"},"135":{"min":0,"max":1,"step":0.01,"value":0.761,"id":135,"type":"NumberInput"},"136":{"inputs":[131],"id":136,"type":"Element"},"137":{"inputs":[132],"label":"Hex","id":137,"type":"LabelElement"},"138":{"inputs":[133,134,135],"label":"RGB","id":138,"type":"LabelElement"},"148":{"x":844,"y":189,"width":300,"elements":[149,156,157,158],"id":148,"type":"ColorEditor"},"149":{"outputLength":1,"title":"Color","icon":"ti ti-palette","id":149,"type":"TitleElement"},"151":{"value":16711680,"id":151,"type":"ColorInput"},"152":{"value":"#FF0000","id":152,"type":"StringInput"},"153":{"min":0,"max":1,"step":0.01,"value":1,"id":153,"type":"NumberInput"},"154":{"min":0,"max":1,"step":0.01,"value":0,"id":154,"type":"NumberInput"},"155":{"min":0,"max":1,"step":0.01,"value":0,"id":155,"type":"NumberInput"},"156":{"inputs":[151],"id":156,"type":"Element"},"157":{"inputs":[152],"label":"Hex","id":157,"type":"LabelElement"},"158":{"inputs":[153,154,155],"label":"RGB","id":158,"type":"LabelElement"},"168":{"x":1241,"y":361,"width":200,"elements":[169,171,172],"id":168,"type":"PowerEditor"},"169":{"outputLength":1,"title":"Power","id":169,"type":"TitleElement"},"171":{"inputLength":1,"links":[109],"label":"A","id":171,"type":"LabelElement"},"172":{"inputLength":1,"links":[177],"label":"B","id":172,"type":"LabelElement"},"176":{"x":852,"y":503,"width":250,"elements":[177,180],"id":176,"type":"FloatEditor"},"177":{"outputLength":1,"title":"Float","icon":"ti ti-box-multiple-1","id":177,"type":"TitleElement"},"179":{"value":1.32,"id":179,"type":"NumberInput"},"180":{"inputs":[179],"id":180,"type":"Element"},"184":{"x":1482,"y":449,"width":300,"elements":[185,195,191,192,193],"id":184,"type":"SliderEditor"},"185":{"outputLength":1,"title":"Slider","icon":"ti ti-adjustments-horizontal","id":185,"type":"TitleElement"},"187":{"min":0,"max":1,"value":1,"id":187,"type":"SliderInput"},"189":{"value":0,"id":189,"type":"NumberInput"},"190":{"value":1,"id":190,"type":"NumberInput"},"191":{"inputs":[189],"label":"Min.","id":191,"type":"LabelElement"},"192":{"inputs":[190],"label":"Max.","id":192,"type":"LabelElement"},"193":{"inputs":[194],"id":193,"type":"Element"},"194":{"value":"More","id":194,"type":"ButtonInput"},"195":{"inputs":[187],"id":195,"type":"Element"},"229":{"x":2313,"y":230,"width":300,"elements":[230,233,243,244,245,246],"id":229,"type":"MeshEditor"},"230":{"outputLength":1,"title":"Mesh","id":230,"type":"TitleElement"},"232":{"value":"Stanford_Bunny","id":232,"type":"StringInput"},"233":{"inputs":[232],"label":"Name","id":233,"type":"LabelElement"},"234":{"value":0,"id":234,"type":"NumberInput"},"235":{"value":0,"id":235,"type":"NumberInput"},"236":{"value":10,"id":236,"type":"NumberInput"},"237":{"value":0,"id":237,"type":"NumberInput"},"238":{"value":0,"id":238,"type":"NumberInput"},"239":{"value":0,"id":239,"type":"NumberInput"},"240":{"value":100,"id":240,"type":"NumberInput"},"241":{"value":100,"id":241,"type":"NumberInput"},"242":{"value":100,"id":242,"type":"NumberInput"},"243":{"inputs":[234,235,236],"label":"Position","id":243,"type":"LabelElement"},"244":{"inputs":[237,238,239],"label":"Rotation","id":244,"type":"LabelElement"},"245":{"inputs":[240,241,242],"label":"Scale","id":245,"type":"LabelElement"},"246":{"inputLength":1,"links":[62],"label":"Material","id":246,"type":"LabelElement"}},"nodes":[61,80,88,100,108,118,128,148,168,176,184,229],"id":2,"type":"Canvas"}
\ No newline at end of file

examples/jsm/node-editor/inputs/ColorEditor.js

@@ -1,20 +1,20 @@
-import { ObjectNode, ColorInput, StringInput, NumberInput, LabelElement } from '../../libs/flow.module.js';
+import { ColorInput, StringInput, NumberInput, LabelElement, Element } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { ColorNode } from '../../renderers/nodes/Nodes.js';
-export class ColorEditor extends ObjectNode {
+export class ColorEditor extends BaseNode {
constructor() {
const node = new ColorNode();
- super( 'Color', 1, node );
-
- this.title.setIcon( 'ti ti-palette' );
+ super( 'Color', 3, node );
const updateFields = ( editing ) => {
const value = node.value;
const hexValue = value.getHex();
+ const hexString = hexValue.toString( 16 ).toUpperCase().padStart( 6, '0' );
if ( editing !== 'color' ) {
@@ -24,7 +24,7 @@
if ( editing !== 'hex' ) {
- hexField.setValue( '#' + hexValue.toString( 16 ).toUpperCase().padEnd( 6, '0' ), false );
+ hexField.setValue( '#' + hexString, false );
}
@@ -36,6 +36,10 @@
}
+ fieldR.setTagColor( `#${hexString.substr( 0, 2 )}0000` );
+ fieldG.setTagColor( `#00${hexString.substr( 2, 2 )}00` );
+ fieldB.setTagColor( `#0000${hexString.substr( 4, 2 )}` );
+
};
const field = new ColorInput( 0xFFFFFF ).onChange( () => {
@@ -76,11 +80,11 @@
};
- const fieldR = new NumberInput( 1, 0, 1 ).onChange( onChangeRGB );
- const fieldG = new NumberInput( 1, 0, 1 ).onChange( onChangeRGB );
- const fieldB = new NumberInput( 1, 0, 1 ).onChange( onChangeRGB );
+ const fieldR = new NumberInput( 1, 0, 1 ).setTagColor( 'red' ).onChange( onChangeRGB );
+ const fieldG = new NumberInput( 1, 0, 1 ).setTagColor( 'green' ).onChange( onChangeRGB );
+ const fieldB = new NumberInput( 1, 0, 1 ).setTagColor( 'blue' ).onChange( onChangeRGB );
- this.add( new LabelElement( 'Value' ).add( field ).setSerializable( false ) )
+ this.add( new Element().add( field ).setSerializable( false ) )
.add( new LabelElement( 'Hex' ).add( hexField ).setSerializable( false ) )
.add( new LabelElement( 'RGB' ).add( fieldR ).add( fieldG ).add( fieldB ) );

examples/jsm/node-editor/inputs/FloatEditor.js

@@ -1,23 +1,22 @@
-import { ObjectNode, NumberInput, LabelElement } from '../../libs/flow.module.js';
+import { NumberInput, Element } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { FloatNode } from '../../renderers/nodes/Nodes.js';
-export class FloatEditor extends ObjectNode {
+export class FloatEditor extends BaseNode {
constructor() {
const node = new FloatNode();
- super( 'Float', 1, node, 250 );
+ super( 'Float', 1, node, 150 );
- this.title.setIcon( 'ti ti-box-multiple-1' );
-
- const field = new NumberInput().onChange( () => {
+ const field = new NumberInput().setTagColor( 'red' ).onChange( () => {
node.value = field.getValue();
} );
- this.add( new LabelElement( 'Value' ).add( field ) );
+ this.add( new Element().add( field ) );
}

examples/jsm/node-editor/inputs/SliderEditor.js

@@ -1,7 +1,8 @@
-import { ObjectNode, ButtonInput, SliderInput, NumberInput, LabelElement, Element } from '../../libs/flow.module.js';
+import { ButtonInput, SliderInput, NumberInput, LabelElement, Element } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { FloatNode } from '../../renderers/nodes/Nodes.js';
-export class SliderEditor extends ObjectNode {
+export class SliderEditor extends BaseNode {
constructor() {
@@ -9,8 +10,6 @@
super( 'Slider', 1, node );
- this.title.setIcon( 'ti ti-adjustments-horizontal' );
-
this.collapse = true;
const field = new SliderInput( 0, 0, 1 ).onChange( () => {
@@ -50,7 +49,7 @@
} ) ).setSerializable( false );
- this.add( new LabelElement( 'Value' ).add( field ) )
+ this.add( new Element().add( field ) )
.add( minElement )
.add( maxElement )
.add( moreElement );

examples/jsm/node-editor/inputs/Vector2Editor.js

@@ -1,7 +1,8 @@
-import { ObjectNode, NumberInput, LabelElement } from '../../libs/flow.module.js';
+import { NumberInput, LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { Vector2Node } from '../../renderers/nodes/Nodes.js';
-export class Vector2Editor extends ObjectNode {
+export class Vector2Editor extends BaseNode {
constructor() {
@@ -9,8 +10,6 @@
super( 'Vector 2', 2, node );
- this.title.setIcon( 'ti ti-box-multiple-2' );
-
const onUpdate = () => {
node.value.x = fieldX.getValue();
@@ -18,10 +17,10 @@
};
- const fieldX = new NumberInput().onChange( onUpdate );
- const fieldY = new NumberInput().onChange( onUpdate );
+ const fieldX = new NumberInput().setTagColor( 'red' ).onChange( onUpdate );
+ const fieldY = new NumberInput().setTagColor( 'green' ).onChange( onUpdate );
- this.add( new LabelElement( 'Values' ).add( fieldX ).add( fieldY ) );
+ this.add( new LabelElement( 'XY' ).add( fieldX ).add( fieldY ) );
}

examples/jsm/node-editor/inputs/Vector3Editor.js

@@ -1,15 +1,14 @@
-import { ObjectNode, NumberInput, LabelElement } from '../../libs/flow.module.js';
+import { NumberInput, LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { Vector3Node } from '../../renderers/nodes/Nodes.js';
-export class Vector3Editor extends ObjectNode {
+export class Vector3Editor extends BaseNode {
constructor() {
const node = new Vector3Node();
- super( 'Vector 3', 3, node );
-
- this.title.setIcon( 'ti ti-box-multiple-3' );
+ super( 'Vector 3', 3, node, 325 );
const onUpdate = () => {
@@ -19,11 +18,11 @@
};
- const fieldX = new NumberInput().onChange( onUpdate );
- const fieldY = new NumberInput().onChange( onUpdate );
- const fieldZ = new NumberInput().onChange( onUpdate );
+ const fieldX = new NumberInput().setTagColor( 'red' ).onChange( onUpdate );
+ const fieldY = new NumberInput().setTagColor( 'green' ).onChange( onUpdate );
+ const fieldZ = new NumberInput().setTagColor( 'blue' ).onChange( onUpdate );
- this.add( new LabelElement( 'Values' ).add( fieldX ).add( fieldY ).add( fieldZ ) );
+ this.add( new LabelElement( 'XYZ' ).add( fieldX ).add( fieldY ).add( fieldZ ) );
}

examples/jsm/node-editor/inputs/Vector4Editor.js

@@ -1,15 +1,14 @@
-import { ObjectNode, NumberInput, LabelElement } from '../../libs/flow.module.js';
+import { NumberInput, LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { Vector4Node } from '../../renderers/nodes/Nodes.js';
-export class Vector4Editor extends ObjectNode {
+export class Vector4Editor extends BaseNode {
constructor() {
const node = new Vector4Node();
- super( 'Vector 4', 4, node );
-
- this.title.setIcon( 'ti ti-box-multiple-4' );
+ super( 'Vector 4', 4, node, 350 );
const onUpdate = () => {
@@ -20,12 +19,12 @@
};
- const fieldX = new NumberInput().onChange( onUpdate );
- const fieldY = new NumberInput().onChange( onUpdate );
- const fieldZ = new NumberInput().onChange( onUpdate );
- const fieldW = new NumberInput().onChange( onUpdate );
+ const fieldX = new NumberInput().setTagColor( 'red' ).onChange( onUpdate );
+ const fieldY = new NumberInput().setTagColor( 'green' ).onChange( onUpdate );
+ const fieldZ = new NumberInput().setTagColor( 'blue' ).onChange( onUpdate );
+ const fieldW = new NumberInput().setTagColor( 'white' ).onChange( onUpdate );
- this.add( new LabelElement( 'Values' )
+ this.add( new LabelElement( 'XYZW' )
.add( fieldX )
.add( fieldY )
.add( fieldZ )

examples/jsm/node-editor/materials/BasicMaterialEditor.js

@@ -0,0 +1,87 @@
+import { ColorInput, SliderInput, LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
+import { MeshBasicNodeMaterial } from '../../renderers/nodes/Nodes.js';
+import * as THREE from 'three';
+
+export class BasicMaterialEditor extends BaseNode {
+
+ constructor() {
+
+ const material = new MeshBasicNodeMaterial();
+
+ super( 'Basic Material', 1, material );
+
+ this.setWidth( 300 );
+
+ const color = new LabelElement( 'color' ).setInput( 3 );
+ const opacity = new LabelElement( 'opacity' ).setInput( 1 );
+ const position = new LabelElement( 'position' ).setInput( 3 );
+
+ color.add( new ColorInput( material.color.getHex() ).onChange( ( input ) => {
+
+ material.color.setHex( input.getValue() );
+
+ } ) );
+
+ opacity.add( new SliderInput( material.opacity, 0, 1 ).onChange( ( input ) => {
+
+ material.opacity = input.getValue();
+
+ this.updateTransparent();
+
+ } ) );
+
+ color.onConnect( () => this.update(), true );
+ opacity.onConnect( () => this.update(), true );
+ position.onConnect( () => this.update(), true );
+
+ this.add( color )
+ .add( opacity )
+ .add( position );
+
+ this.color = color;
+ this.opacity = opacity;
+ this.position = position;
+
+ this.material = material;
+
+ this.update();
+
+ }
+
+ update() {
+
+ const { material, color, opacity, position } = this;
+
+ color.setEnabledInputs( ! color.getLinkedObject() );
+ opacity.setEnabledInputs( ! opacity.getLinkedObject() );
+
+ material.colorNode = color.getLinkedObject();
+ material.opacityNode = opacity.getLinkedObject() || null;
+
+ material.positionNode = position.getLinkedObject() || null;
+
+ material.dispose();
+
+ this.updateTransparent();
+
+ // TODO: Fix on NodeMaterial System
+ material.customProgramCacheKey = () => {
+
+ return THREE.MathUtils.generateUUID();
+
+ };
+
+ }
+
+ updateTransparent() {
+
+ const { material, opacity } = this;
+
+ material.transparent = opacity.getLinkedObject() || material.opacity < 1 ? true : false;
+
+ opacity.setIcon( material.transparent ? 'ti ti-layers-intersect' : 'ti ti-layers-subtract' );
+
+ }
+
+}

examples/jsm/node-editor/materials/PointsMaterialEditor.js

@@ -0,0 +1,97 @@
+import { ColorInput, SliderInput, LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
+import { PointsNodeMaterial } from '../../renderers/nodes/Nodes.js';
+import * as THREE from 'three';
+
+export class PointsMaterialEditor extends BaseNode {
+
+ constructor() {
+
+ const material = new PointsNodeMaterial( {
+ depthWrite: false,
+ transparent: true,
+ sizeAttenuation: true,
+ blending: THREE.AdditiveBlending
+ } );
+
+ super( 'Points Material', 1, material );
+
+ this.setWidth( 300 );
+
+ const color = new LabelElement( 'color' ).setInput( 3 );
+ const opacity = new LabelElement( 'opacity' ).setInput( 1 );
+ const size = new LabelElement( 'size' ).setInput( 1 );
+ const position = new LabelElement( 'position' ).setInput( 3 );
+
+ color.add( new ColorInput( material.color.getHex() ).onChange( ( input ) => {
+
+ material.color.setHex( input.getValue() );
+
+ } ) );
+
+ opacity.add( new SliderInput( material.opacity, 0, 1 ).onChange( ( input ) => {
+
+ material.opacity = input.getValue();
+
+ this.updateTransparent();
+
+ } ) );
+
+ color.onConnect( () => this.update(), true );
+ opacity.onConnect( () => this.update(), true );
+ size.onConnect(() => this.update(), true );
+ position.onConnect(() => this.update(), true );
+
+ this.add( color )
+ .add( opacity )
+ .add( size )
+ .add( position );
+
+ this.color = color;
+ this.opacity = opacity;
+ this.size = size;
+ this.position = position;
+
+ this.material = material;
+
+ this.update();
+
+ }
+
+ update() {
+
+ const { material, color, opacity, size, position } = this;
+
+ color.setEnabledInputs( ! color.getLinkedObject() );
+ opacity.setEnabledInputs( ! opacity.getLinkedObject() );
+
+ material.colorNode = color.getLinkedObject();
+ material.opacityNode = opacity.getLinkedObject() || null;
+
+ material.sizeNode = size.getLinkedObject() || null;
+ material.positionNode = position.getLinkedObject() || null;
+
+ material.dispose();
+
+ this.updateTransparent();
+
+ // TODO: Fix on NodeMaterial System
+ material.customProgramCacheKey = () => {
+
+ return THREE.MathUtils.generateUUID();
+
+ };
+
+ }
+
+ updateTransparent() {
+
+ const { material, opacity } = this;
+
+ material.transparent = opacity.getLinkedObject() || material.opacity < 1 ? true : false;
+
+ opacity.setIcon( material.transparent ? 'ti ti-layers-intersect' : 'ti ti-layers-subtract' );
+
+ }
+
+}

examples/jsm/node-editor/materials/StandardMaterialEditor.js

@@ -1,16 +1,15 @@
-import { ObjectNode, ColorInput, SliderInput, LabelElement } from '../../libs/flow.module.js';
+import { ColorInput, SliderInput, LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { MeshStandardNodeMaterial } from '../../renderers/nodes/Nodes.js';
import * as THREE from 'three';
-export class StandardMaterialEditor extends ObjectNode {
+export class StandardMaterialEditor extends BaseNode {
constructor() {
const material = new MeshStandardNodeMaterial();
- super( 'Standard Material', 0, material );
-
- this.title.setStyle( 'blue' );
+ super( 'Standard Material', 1, material );
this.setWidth( 300 );
@@ -18,6 +17,7 @@
const opacity = new LabelElement( 'opacity' ).setInput( 1 );
const metalness = new LabelElement( 'metalness' ).setInput( 1 );
const roughness = new LabelElement( 'roughness' ).setInput( 1 );
+ const position = new LabelElement( 'position' ).setInput( 3 );
color.add( new ColorInput( material.color.getHex() ).onChange( ( input ) => {
@@ -49,16 +49,19 @@
opacity.onConnect( () => this.update(), true );
metalness.onConnect( () => this.update(), true );
roughness.onConnect( () => this.update(), true );
+ position.onConnect(() => this.update(), true );
this.add( color )
.add( opacity )
.add( metalness )
- .add( roughness );
+ .add( roughness )
+ .add( position );
this.color = color;
this.opacity = opacity;
this.metalness = metalness;
this.roughness = roughness;
+ this.position = position;
this.material = material;
@@ -68,19 +71,19 @@
update() {
- const { material, color, opacity, roughness, metalness } = this;
-
- color.setEnabledInputs( ! color.linkedExtra );
- opacity.setEnabledInputs( ! opacity.linkedExtra );
- roughness.setEnabledInputs( ! roughness.linkedExtra );
- metalness.setEnabledInputs( ! metalness.linkedExtra );
-
- material.colorNode = color.linkedExtra;
+ const { material, color, opacity, roughness, metalness, position } = this;
- material.opacityNode = opacity.linkedExtra || null;
+ color.setEnabledInputs( ! color.getLinkedObject() );
+ opacity.setEnabledInputs( ! opacity.getLinkedObject() );
+ roughness.setEnabledInputs( ! roughness.getLinkedObject() );
+ metalness.setEnabledInputs( ! metalness.getLinkedObject() );
+
+ material.colorNode = color.getLinkedObject();
+ material.opacityNode = opacity.getLinkedObject() || null;
+ material.metalnessNode = metalness.getLinkedObject();
+ material.roughnessNode = roughness.getLinkedObject();
- material.metalnessNode = metalness.linkedExtra;
- material.roughnessNode = roughness.linkedExtra;
+ material.positionNode = position.getLinkedObject() || null;
material.dispose();
@@ -99,7 +102,7 @@
const { material, opacity } = this;
- material.transparent = opacity.linkedExtra || material.opacity < 1 ? true : false;
+ material.transparent = opacity.getLinkedObject() || material.opacity < 1 ? true : false;
opacity.setIcon( material.transparent ? 'ti ti-layers-intersect' : 'ti ti-layers-subtract' );

examples/jsm/node-editor/math/AngleEditor.js

@@ -0,0 +1,39 @@
+import { SelectInput, Element, LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
+import { MathNode, Vector3Node } from '../../renderers/nodes/Nodes.js';
+
+const DEFAULT_VALUE = new Vector3Node();
+
+export class AngleEditor extends BaseNode {
+
+ constructor() {
+
+ const node = new MathNode( MathNode.SIN, DEFAULT_VALUE );
+
+ super( 'Angle', 1, node, 175 );
+
+ const optionsField = new SelectInput( [
+ { name: 'Degrees to Radians', value: MathNode.RAD },
+ { name: 'Radians to Degrees', value: MathNode.DEG }
+ ], MathNode.RAD ).onChange( () => {
+
+ node.method = optionsField.getValue();
+
+ this.invalidate();
+
+ } );
+
+ const input = new LabelElement( 'A' ).setInput( 1 );
+
+ input.onConnect( () => {
+
+ node.aNode = input.getLinkedObject() || DEFAULT_VALUE;
+
+ } );
+
+ this.add( new Element().add( optionsField ) )
+ .add( input );
+
+ }
+
+}

examples/jsm/node-editor/math/DotEditor.js

@@ -1,30 +1,29 @@
-import { ObjectNode, LabelElement } from '../../libs/flow.module.js';
+import { LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { MathNode, FloatNode } from '../../renderers/nodes/Nodes.js';
const NULL_VALUE = new FloatNode();
-export class DotEditor extends ObjectNode {
+export class DotEditor extends BaseNode {
constructor() {
const node = new MathNode( MathNode.DOT, NULL_VALUE, NULL_VALUE );
- super( 'Dot Product', 1, node );
-
- this.setWidth( 200 );
+ super( 'Dot Product', 1, node, 175 );
const aElement = new LabelElement( 'A' ).setInput( 3 );
const bElement = new LabelElement( 'B' ).setInput( 3 );
aElement.onConnect( () => {
- node.aNode = aElement.linkedExtra || NULL_VALUE;
+ node.aNode = aElement.getLinkedObject() || NULL_VALUE;
} );
bElement.onConnect( () => {
- node.bNode = bElement.linkedExtra || NULL_VALUE;
+ node.bNode = bElement.getLinkedObject() || NULL_VALUE;
} );

examples/jsm/node-editor/math/InvertEditor.js

@@ -1,9 +1,10 @@
-import { ObjectNode, SelectInput, LabelElement } from '../../libs/flow.module.js';
+import { SelectInput, LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { MathNode, FloatNode } from '../../renderers/nodes/Nodes.js';
const DEFAULT_VALUE = new FloatNode();
-export class InvertEditor extends ObjectNode {
+export class InvertEditor extends BaseNode {
constructor() {
@@ -26,7 +27,7 @@
input.onConnect( () => {
- node.aNode = input.linkedExtra || DEFAULT_VALUE;
+ node.aNode = input.getLinkedObject() || DEFAULT_VALUE;
} );

examples/jsm/node-editor/math/LimiterEditor.js

@@ -1,20 +1,21 @@
-import { ObjectNode, SelectInput, LabelElement } from '../../libs/flow.module.js';
+import { SelectInput, LabelElement, Element } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { MathNode, FloatNode } from '../../renderers/nodes/Nodes.js';
const NULL_VALUE = new FloatNode();
-export class LimiterEditor extends ObjectNode {
+export class LimiterEditor extends BaseNode {
constructor() {
- const node = new MathNode( MathNode.MAX, NULL_VALUE, NULL_VALUE );
+ const node = new MathNode( MathNode.MIN, NULL_VALUE, NULL_VALUE );
- super( 'Limiter', 1, node, 250 );
+ super( 'Limiter', 1, node, 175 );
const methodInput = new SelectInput( [
- { name: 'Max', value: MathNode.MAX },
- { name: 'Min', value: MathNode.MIN }
- ] );
+ { name: 'Min', value: MathNode.MIN },
+ { name: 'Max', value: MathNode.MAX }
+ ], MathNode.MIN );
methodInput.onChange( ( data ) => {
@@ -29,17 +30,17 @@
aElement.onConnect( () => {
- node.aNode = aElement.linkedExtra || NULL_VALUE;
+ node.aNode = aElement.getLinkedObject() || NULL_VALUE;
} );
bElement.onConnect( () => {
- node.bNode = bElement.linkedExtra || NULL_VALUE;
+ node.bNode = bElement.getLinkedObject() || NULL_VALUE;
} );
- this.add( new LabelElement( 'Method' ).add( methodInput ) )
+ this.add( new Element().add( methodInput ) )
.add( aElement )
.add( bElement );

examples/jsm/node-editor/math/NormalizeEditor.js

@@ -1,21 +1,22 @@
-import { ObjectNode, LabelElement } from '../../libs/flow.module.js';
+import { LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { MathNode, Vector3Node } from '../../renderers/nodes/Nodes.js';
const DEFAULT_VALUE = new Vector3Node();
-export class NormalizeEditor extends ObjectNode {
+export class NormalizeEditor extends BaseNode {
constructor() {
const node = new MathNode( MathNode.NORMALIZE, DEFAULT_VALUE );
- super( 'Normalize', 3, node, 200 );
+ super( 'Normalize', 3, node, 175 );
- const input = new LabelElement( 'Source' ).setInput( 3 );
+ const input = new LabelElement( 'A' ).setInput( 3 );
input.onConnect( () => {
- node.aNode = input.linkedExtra || DEFAULT_VALUE;
+ node.aNode = input.getLinkedObject() || DEFAULT_VALUE;
} );

examples/jsm/node-editor/math/OperatorEditor.js

@@ -1,22 +1,23 @@
-import { ObjectNode, SelectInput, LabelElement } from '../../libs/flow.module.js';
+import { SelectInput, LabelElement, Element } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { OperatorNode, FloatNode } from '../../renderers/nodes/Nodes.js';
const NULL_VALUE = new FloatNode();
-export class OperatorEditor extends ObjectNode {
+export class OperatorEditor extends BaseNode {
constructor() {
const node = new OperatorNode( '+', NULL_VALUE, NULL_VALUE );
- super( 'Operator', 1, node, 250 );
+ super( 'Operator', 1, node, 150 );
const opInput = new SelectInput( [
- { name: '+ Addition', value: '+' },
- { name: '- Subtraction', value: '-' },
- { name: '* Multiplication', value: '*' },
- { name: '/ Division', value: '/' }
- ] );
+ { name: 'Addition ( + )', value: '+' },
+ { name: 'Subtraction ( - )', value: '-' },
+ { name: 'Multiplication ( * )', value: '*' },
+ { name: 'Division ( / )', value: '/' }
+ ], '+' );
opInput.onChange( ( data ) => {
@@ -31,17 +32,17 @@
aElement.onConnect( () => {
- node.aNode = aElement.linkedExtra || NULL_VALUE;
+ node.aNode = aElement.getLinkedObject() || NULL_VALUE;
} );
bElement.onConnect( () => {
- node.bNode = bElement.linkedExtra || NULL_VALUE;
+ node.bNode = bElement.getLinkedObject() || NULL_VALUE;
} );
- this.add( new LabelElement( 'Operator' ).add( opInput ) )
+ this.add( new Element().add( opInput ) )
.add( aElement )
.add( bElement );

examples/jsm/node-editor/math/PowerEditor.js

@@ -1,28 +1,29 @@
-import { ObjectNode, LabelElement } from '../../libs/flow.module.js';
+import { LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { MathNode, FloatNode } from '../../renderers/nodes/Nodes.js';
const NULL_VALUE = new FloatNode();
-export class PowerEditor extends ObjectNode {
+export class PowerEditor extends BaseNode {
constructor() {
const node = new MathNode( MathNode.POW, NULL_VALUE, NULL_VALUE );
- super( 'Power', 1, node, 200 );
+ super( 'Power', 1, node, 175 );
const aElement = new LabelElement( 'A' ).setInput( 1 );
const bElement = new LabelElement( 'B' ).setInput( 1 );
aElement.onConnect( () => {
- node.aNode = aElement.linkedExtra || NULL_VALUE;
+ node.aNode = aElement.getLinkedObject() || NULL_VALUE;
} );
bElement.onConnect( () => {
- node.bNode = bElement.linkedExtra || NULL_VALUE;
+ node.bNode = bElement.getLinkedObject() || NULL_VALUE;
} );

examples/jsm/node-editor/math/TrigonometryEditor.js

@@ -1,21 +1,26 @@
-import { ObjectNode, SelectInput, Element, LabelElement } from '../../libs/flow.module.js';
+import { SelectInput, Element, LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { MathNode, Vector3Node } from '../../renderers/nodes/Nodes.js';
const DEFAULT_VALUE = new Vector3Node();
-export class TrigonometryEditor extends ObjectNode {
+export class TrigonometryEditor extends BaseNode {
constructor() {
const node = new MathNode( MathNode.SIN, DEFAULT_VALUE );
- super( 'Trigonometry', 1, node, 200 );
+ super( 'Trigonometry', 1, node, 175 );
const optionsField = new SelectInput( [
{ name: 'Sin', value: MathNode.SIN },
{ name: 'Cos', value: MathNode.COS },
- { name: 'Tan', value: MathNode.TAN }
- ] ).onChange( () => {
+ { name: 'Tan', value: MathNode.TAN },
+
+ { name: 'asin', value: MathNode.ASIN },
+ { name: 'acos', value: MathNode.ACOS },
+ { name: 'atan', value: MathNode.ATAN }
+ ], MathNode.SIN ).onChange( () => {
node.method = optionsField.getValue();
@@ -23,11 +28,11 @@
} );
- const input = new LabelElement( 'Source' ).setInput( 1 );
+ const input = new LabelElement( 'A' ).setInput( 1 );
input.onConnect( () => {
- node.aNode = input.linkedExtra || DEFAULT_VALUE;
+ node.aNode = input.getLinkedObject() || DEFAULT_VALUE;
} );

examples/jsm/node-editor/NodeEditor.js

@@ -1,11 +1,14 @@
-import { Canvas, CircleMenu, ButtonInput, ContextMenu, Loader } from '../libs/flow.module.js';
+import { Styles, Canvas, CircleMenu, ButtonInput, ContextMenu, Tips, Search, Loader } from '../libs/flow.module.js';
+import { BasicMaterialEditor } from './materials/BasicMaterialEditor.js';
import { StandardMaterialEditor } from './materials/StandardMaterialEditor.js';
+import { PointsMaterialEditor } from './materials/PointsMaterialEditor.js';
import { OperatorEditor } from './math/OperatorEditor.js';
import { NormalizeEditor } from './math/NormalizeEditor.js';
import { InvertEditor } from './math/InvertEditor.js';
import { LimiterEditor } from './math/LimiterEditor.js';
import { DotEditor } from './math/DotEditor.js';
import { PowerEditor } from './math/PowerEditor.js';
+import { AngleEditor } from './math/AngleEditor.js';
import { TrigonometryEditor } from './math/TrigonometryEditor.js';
import { FloatEditor } from './inputs/FloatEditor.js';
import { Vector2Editor } from './inputs/Vector2Editor.js';
@@ -19,18 +22,218 @@
import { NormalEditor } from './accessors/NormalEditor.js';
import { TimerEditor } from './utils/TimerEditor.js';
import { OscillatorEditor } from './utils/OscillatorEditor.js';
+import { SplitEditor } from './utils/SplitEditor.js';
+import { JoinEditor } from './utils/JoinEditor.js';
import { CheckerEditor } from './procedural/CheckerEditor.js';
-
+import { PointsEditor } from './scene/PointsEditor.js';
+import { MeshEditor } from './scene/MeshEditor.js';
import { EventDispatcher } from 'three';
+Styles.icons.unlink = 'ti ti-unlink';
+
+export const NodeList = [
+ {
+ name: 'Inputs',
+ icon: 'forms',
+ children: [
+ {
+ name: 'Slider',
+ icon: 'adjustments-horizontal',
+ nodeClass: SliderEditor
+ },
+ {
+ name: 'Float',
+ icon: 'box-multiple-1',
+ nodeClass: FloatEditor
+ },
+ {
+ name: 'Vector 2',
+ icon: 'box-multiple-2',
+ nodeClass: Vector2Editor
+ },
+ {
+ name: 'Vector 3',
+ icon: 'box-multiple-3',
+ nodeClass: Vector3Editor
+ },
+ {
+ name: 'Vector 4',
+ icon: 'box-multiple-4',
+ nodeClass: Vector4Editor
+ },
+ {
+ name: 'Color',
+ icon: 'palette',
+ nodeClass: ColorEditor
+ }
+ ]
+ },
+ {
+ name: 'Accessors',
+ icon: 'vector-triangle',
+ children: [
+ {
+ name: 'UV',
+ icon: 'details',
+ nodeClass: UVEditor
+ },
+ {
+ name: 'Position',
+ icon: 'hierarchy',
+ nodeClass: PositionEditor
+ },
+ {
+ name: 'Normal',
+ icon: 'fold-up',
+ nodeClass: NormalEditor
+ }
+ ]
+ },
+ {
+ name: 'Display',
+ icon: 'brightness',
+ children: [
+ {
+ name: 'Blend',
+ icon: 'layers-subtract',
+ nodeClass: BlendEditor
+ }
+ ]
+ },
+ {
+ name: 'Math',
+ icon: 'calculator',
+ children: [
+ {
+ name: 'Operator',
+ icon: 'math-symbols',
+ nodeClass: OperatorEditor
+ },
+ {
+ name: 'Invert',
+ icon: 'flip-vertical',
+ tip: 'Negate',
+ nodeClass: OperatorEditor
+ },
+ {
+ name: 'Limiter',
+ icon: 'arrow-bar-to-up',
+ tip: 'Min / Max',
+ nodeClass: LimiterEditor
+ },
+ {
+ name: 'Dot Product',
+ icon: 'arrows-up-left',
+ nodeClass: DotEditor
+ },
+ {
+ name: 'Power',
+ icon: 'arrow-up-right',
+ nodeClass: PowerEditor
+ },
+ {
+ name: 'Trigonometry',
+ icon: 'wave-sine',
+ tip: 'Sin / Cos / Tan / ...',
+ nodeClass: TrigonometryEditor
+ },
+ {
+ name: 'Angle',
+ icon: 'angle',
+ tip: 'Degress / Radians',
+ nodeClass: AngleEditor
+ },
+ {
+ name: 'Normalize',
+ icon: 'fold',
+ nodeClass: NormalizeEditor
+ }
+ ]
+ },
+ {
+ name: 'Procedural',
+ icon: 'infinity',
+ children: [
+ {
+ name: 'Checker',
+ icon: 'border-outer',
+ nodeClass: CheckerEditor
+ }
+ ]
+ },
+ {
+ name: 'Utils',
+ icon: 'apps',
+ children: [
+ {
+ name: 'Timer',
+ icon: 'clock',
+ nodeClass: TimerEditor
+ },
+ {
+ name: 'Oscillator',
+ icon: 'wave-sine',
+ nodeClass: OscillatorEditor
+ },
+ {
+ name: 'Split',
+ icon: 'arrows-split-2',
+ nodeClass: SplitEditor
+ },
+ {
+ name: 'Join',
+ icon: 'arrows-join-2',
+ nodeClass: JoinEditor
+ }
+ ]
+ },
+ /*{
+ name: 'Scene',
+ icon: '3d-cube-sphere',
+ children: [
+ {
+ name: 'Mesh',
+ icon: '3d-cube-sphere',
+ nodeClass: MeshEditor
+ }
+ ]
+ },*/
+ {
+ name: 'Material',
+ icon: 'circles',
+ children: [
+ {
+ name: 'Basic Material',
+ icon: 'circle',
+ nodeClass: BasicMaterialEditor
+ },
+ {
+ name: 'Standard Material',
+ icon: 'circle',
+ nodeClass: StandardMaterialEditor
+ },
+ {
+ name: 'Points Material',
+ icon: 'circle-dotted',
+ nodeClass: PointsMaterialEditor
+ }
+ ]
+ }
+];
+
export const ClassLib = {
+ BasicMaterialEditor,
StandardMaterialEditor,
+ PointsMaterialEditor,
+ PointsEditor,
+ MeshEditor,
OperatorEditor,
NormalizeEditor,
InvertEditor,
LimiterEditor,
DotEditor,
PowerEditor,
+ AngleEditor,
TrigonometryEditor,
FloatEditor,
Vector2Editor,
@@ -44,19 +247,23 @@
NormalEditor,
TimerEditor,
OscillatorEditor,
+ SplitEditor,
+ JoinEditor,
CheckerEditor
};
export class NodeEditor extends EventDispatcher {
- constructor() {
+ constructor( scene = null ) {
super();
const domElement = document.createElement( 'flow' );
const canvas = new Canvas();
- domElement.appendChild( canvas.dom );
+ domElement.append( canvas.dom );
+
+ this.scene = scene;
this.canvas = canvas;
this.domElement = domElement;
@@ -64,16 +271,48 @@
this.nodesContext = null;
this.examplesContext = null;
+ this._initTips();
this._initMenu();
+ this._initSearch();
this._initNodesContext();
this._initExamplesContext();
}
+ centralizeNode( node ) {
+
+ const canvas = this.canvas;
+ const canvasRect = canvas.rect;
+
+ const nodeRect = node.dom.getBoundingClientRect();
+
+ const defaultOffsetX = nodeRect.width;
+ const defaultOffsetY = nodeRect.height;
+
+ node.setPosition(
+ ( canvas.relativeX + ( canvasRect.width / 2 ) ) - defaultOffsetX,
+ ( canvas.relativeY + ( canvasRect.height / 2 ) ) - defaultOffsetY
+ );
+
+ }
+
add( node ) {
+ const onRemove = () => {
+
+ node.removeEventListener( 'remove', onRemove );
+
+ node.setEditor( null );
+
+ };
+
+ node.setEditor( this );
+ node.addEventListener( 'remove', onRemove );
+
this.canvas.add( node );
+ this.dispatchEvent( { type: 'add', node } );
+
return this;
}
@@ -98,51 +337,49 @@
this.canvas.deserialize( json );
+ for ( const node of this.canvas.nodes ) {
+
+ this.add( node );
+
+ }
+
this.dispatchEvent( { type: 'load' } );
}
+ _initTips() {
+
+ this.tips = new Tips();
+
+ this.domElement.append( this.tips.dom );
+
+ }
+
_initMenu() {
const menu = new CircleMenu();
- const menuButton = new ButtonInput().setIcon( 'ti ti-menu-2' );
+ const menuButton = new ButtonInput().setIcon( 'ti ti-apps' ).setToolTip( 'Add' );
const examplesButton = new ButtonInput().setIcon( 'ti ti-file-symlink' ).setToolTip( 'Examples' );
const newButton = new ButtonInput().setIcon( 'ti ti-file' ).setToolTip( 'New' );
const openButton = new ButtonInput().setIcon( 'ti ti-upload' ).setToolTip( 'Open' );
const saveButton = new ButtonInput().setIcon( 'ti ti-download' ).setToolTip( 'Save' );
- const hideContext = () => {
-
- this.examplesContext.hide();
- this.nodesContext.hide();
-
- };
-
- menuButton.onClick( () => {
-
- this.nodesContext.show( 60, 50 );
-
- } );
-
- examplesButton.onClick( () => {
-
- this.examplesContext.show( 60, 175 );
-
- } );
+ menuButton.onClick( () => this.nodesContext.open() );
+ examplesButton.onClick( () => this.examplesContext.open() );
newButton.onClick( () => {
- hideContext();
+ if ( confirm( 'Are you sure?' ) === true ) {
this.newProject();
+ }
+
} );
openButton.onClick( () => {
- hideContext();
-
const input = document.createElement( 'input' );
input.type = 'file';
@@ -170,8 +407,6 @@
saveButton.onClick( () => {
- hideContext();
-
const json = JSON.stringify( this.canvas.toJSON() );
const a = document.createElement( 'a' );
@@ -183,13 +418,13 @@
} );
- menu.add( menuButton )
+ menu.add( examplesButton )
+ .add( menuButton )
.add( newButton )
- .add( examplesButton )
.add( openButton )
.add( saveButton );
- this.domElement.appendChild( menu.dom );
+ this.domElement.append( menu.dom );
this.menu = menu;
@@ -248,12 +483,133 @@
context.add( new ButtonInput( 'Basic' ), basicContext );
context.add( new ButtonInput( 'Advanced' ), advancedContext );
- this.domElement.appendChild( context.dom );
-
this.examplesContext = context;
}
+ _initSearch() {
+
+ const traverseNodeEditors = ( item ) => {
+
+ if ( item.nodeClass ) {
+
+ const button = new ButtonInput( item.name );
+ button.setIcon( `ti ti-${item.icon}` );
+ button.addEventListener( 'complete', () => {
+
+ const node = new item.nodeClass();
+
+ this.add( node );
+
+ this.centralizeNode( node );
+
+ } );
+
+ search.add( button );
+
+ }
+
+ if ( item.children ) {
+
+ for ( const subItem of item.children ) {
+
+ traverseNodeEditors( subItem );
+
+ }
+
+ }
+
+ };
+
+ const search = new Search();
+ search.forceAutoComplete = true;
+
+ search.onFilter( () => {
+
+ search.clear();
+
+ for ( const item of NodeList ) {
+
+ traverseNodeEditors( item );
+
+ }
+
+ const object3d = this.scene;
+
+ if ( object3d !== null ) {
+
+ object3d.traverse( ( obj3d ) => {
+
+ if ( obj3d.isMesh === true || obj3d.isPoints === true ) {
+
+ let prefix = null;
+ let icon = null;
+ let editorClass = null;
+
+ if ( obj3d.isMesh === true ) {
+
+ prefix = 'Mesh';
+ icon = 'ti ti-3d-cube-sphere';
+ editorClass = MeshEditor;
+
+ } else if ( obj3d.isPoints === true ) {
+
+ prefix = 'Points';
+ icon = 'ti ti-border-none';
+ editorClass = PointsEditor;
+
+ }
+
+ const button = new ButtonInput( `${prefix} - ${obj3d.name}` );
+ button.setIcon( icon );
+ button.addEventListener( 'complete', () => {
+
+ for ( const node of this.canvas.nodes ) {
+
+ if ( node.value === obj3d ) {
+
+ // prevent duplicated node
+
+ this.canvas.select( node );
+
+ return;
+
+ }
+
+ }
+
+ const node = new editorClass( obj3d );
+
+ this.add( node );
+
+ this.centralizeNode( node );
+
+ } );
+
+ search.add( button );
+
+ }
+
+ } );
+
+ }
+
+ } );
+
+ search.onSubmit( () => {
+
+ if ( search.currentFiltered !== null ) {
+
+ search.currentFiltered.button.dispatchEvent( new Event( 'complete' ) );
+
+ }
+
+ } );
+
+ this.domElement.append( search.dom );
+
+ }
+
_initNodesContext() {
const context = new ContextMenu( this.domElement );
@@ -263,9 +619,6 @@
const add = ( node ) => {
- const canvas = this.canvas;
- const canvasRect = canvas.rect;
-
if ( isContext ) {
node.setPosition(
@@ -275,13 +628,7 @@
} else {
- const defaultOffsetX = 350 / 2;
- const defaultOffsetY = 20;
-
- node.setPosition(
- ( canvas.relativeX + ( canvasRect.width / 2 ) ) - defaultOffsetX,
- ( canvas.relativeY + ( canvasRect.height / 2 ) ) - defaultOffsetY
- );
+ this.centralizeNode( node );
}
@@ -310,144 +657,50 @@
// INPUTS
//**************//
- const inputsContext = new ContextMenu();
-
- const sliderInput = new ButtonInput( 'Slider' ).setIcon( 'ti ti-adjustments-horizontal' )
- .onClick( () => add( new SliderEditor() ) );
-
- const floatInput = new ButtonInput( 'Float' ).setIcon( 'ti ti-box-multiple-1' )
- .onClick( () => add( new FloatEditor() ) );
-
- const vector2Input = new ButtonInput( 'Vector 2' ).setIcon( 'ti ti-box-multiple-2' )
- .onClick( () => add( new Vector2Editor() ) );
-
- const vector3Input = new ButtonInput( 'Vector 3' ).setIcon( 'ti ti-box-multiple-3' )
- .onClick( () => add( new Vector3Editor() ) );
-
- const vector4Input = new ButtonInput( 'Vector 4' ).setIcon( 'ti ti-box-multiple-4' )
- .onClick( () => add( new Vector4Editor() ) );
-
- const colorInput = new ButtonInput( 'Color' ).setIcon( 'ti ti-palette' )
- .onClick( () => add( new ColorEditor() ) );
-
- //const mapInput = new ButtonInput( 'Map' ).setIcon( 'ti ti-photo' );
- //const cubeMapInput = new ButtonInput( 'Cube Map' ).setIcon( 'ti ti-box' );
- //const integerInput = new ButtonInput( 'Integer' ).setIcon( 'ti ti-list-numbers' );
-
- inputsContext
- .add( sliderInput )
- .add( floatInput )
- .add( vector2Input )
- .add( vector3Input )
- .add( vector4Input )
- .add( colorInput );
-
- //**************//
- // MATH
- //**************//
-
- const mathContext = new ContextMenu();
-
- const operatorsNode = new ButtonInput( 'Operator' ).setIcon( 'ti ti-math-symbols' )
- .onClick( () => add( new OperatorEditor() ) );
-
- const normalizeNode = new ButtonInput( 'Normalize' ).setIcon( 'ti ti-fold' )
- .onClick( () => add( new NormalizeEditor() ) );
-
- const invertNode = new ButtonInput( 'Invert' ).setToolTip( 'Negate' ).setIcon( 'ti ti-flip-vertical' )
- .onClick( () => add( new InvertEditor() ) );
+ const createButtonMenu = ( item ) => {
- const limiterNode = new ButtonInput( 'Limiter' ).setToolTip( 'Min / Max' ).setIcon( 'ti ti-arrow-bar-to-up' )
- .onClick( () => add( new LimiterEditor() ) );
+ const button = new ButtonInput( item.name );
+ button.setIcon( `ti ti-${item.icon}` );
- const dotNode = new ButtonInput( 'Dot Product' ).setIcon( 'ti ti-arrows-up-left' )
- .onClick( () => add( new DotEditor() ) );
+ let context = null;
- const powNode = new ButtonInput( 'Power' ).setIcon( 'ti ti-arrow-up-right' )
- .onClick( () => add( new PowerEditor() ) );
+ if ( item.nodeClass ) {
- const triNode = new ButtonInput( 'Trigonometry' ).setToolTip( 'Sin / Cos / Tan' ).setIcon( 'ti ti-wave-sine' )
- .onClick( () => add( new TrigonometryEditor() ) );
+ button.onClick( () => add( new item.nodeClass() ) );
- mathContext
- .add( operatorsNode )
- .add( invertNode )
- .add( limiterNode )
- .add( dotNode )
- .add( powNode )
- .add( triNode )
- .add( normalizeNode );
-
- //**************//
- // ACCESSORS
- //**************//
-
- const accessorsContext = new ContextMenu();
-
- const uvNode = new ButtonInput( 'UV' ).setIcon( 'ti ti-details' )
- .onClick( () => add( new UVEditor() ) );
-
- const positionNode = new ButtonInput( 'Position' ).setIcon( 'ti ti-hierarchy' )
- .onClick( () => add( new PositionEditor() ) );
+ }
- const normalNode = new ButtonInput( 'Normal' ).setIcon( 'ti ti-fold-up' )
- .onClick( () => add( new NormalEditor() ) );
+ if ( item.tip ) {
- accessorsContext
- .add( uvNode )
- .add( positionNode )
- .add( normalNode );
+ button.setToolTip( item.tip );
- //**************//
- // PROCEDURAL
- //**************//
-
- const proceduralContext = new ContextMenu();
+ }
- const checkerNode = new ButtonInput( 'Checker' ).setIcon( 'ti ti-border-outer' )
- .onClick( () => add( new CheckerEditor() ) );
+ if ( item.children ) {
- proceduralContext
- .add( checkerNode );
+ context = new ContextMenu();
- //**************//
- // DISPLAY
- //**************//
+ for ( const subItem of item.children ) {
- const displayContext = new ContextMenu();
+ const buttonMenu = createButtonMenu( subItem );
- const blendNode = new ButtonInput( 'Blend' ).setIcon( 'ti ti-layers-subtract' )
- .onClick( () => add( new BlendEditor() ) );
+ context.add( buttonMenu.button, buttonMenu.context );
- displayContext
- .add( blendNode );
+ }
- //**************//
- // UTILS
- //**************//
+ }
- const utilsContext = new ContextMenu();
+ return { button, context };
- const timerNode = new ButtonInput( 'Timer' ).setIcon( 'ti ti-clock' )
- .onClick( () => add( new TimerEditor() ) );
+ };
- const oscNode = new ButtonInput( 'Oscillator' ).setIcon( 'ti ti-wave-sine' )
- .onClick( () => add( new OscillatorEditor() ) );
+ for ( const item of NodeList ) {
- utilsContext
- .add( timerNode )
- .add( oscNode );
+ const buttonMenu = createButtonMenu( item );
- //**************//
- // MAIN
- //**************//
+ context.add( buttonMenu.button, buttonMenu.context );
- context.add( new ButtonInput( 'Inputs' ).setIcon( 'ti ti-forms' ), inputsContext );
- context.add( new ButtonInput( 'Accessors' ).setIcon( 'ti ti-vector-triangle' ), accessorsContext );
- context.add( new ButtonInput( 'Display' ).setIcon( 'ti ti-brightness' ), displayContext );
- context.add( new ButtonInput( 'Math' ).setIcon( 'ti ti-calculator' ), mathContext );
- context.add( new ButtonInput( 'Procedural' ).setIcon( 'ti ti-infinity' ), proceduralContext );
- context.add( new ButtonInput( 'Utils' ).setIcon( 'ti ti-apps' ), utilsContext );
+ }
this.nodesContext = context;

examples/jsm/node-editor/procedural/CheckerEditor.js

@@ -1,9 +1,10 @@
-import { ObjectNode, LabelElement } from '../../libs/flow.module.js';
+import { LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { CheckerNode, UVNode } from '../../renderers/nodes/Nodes.js';
const DEFAULT_UV = new UVNode();
-export class CheckerEditor extends ObjectNode {
+export class CheckerEditor extends BaseNode {
constructor() {
@@ -15,7 +16,7 @@
field.onConnect( () => {
- node.uvNode = field.linkedExtra || DEFAULT_UV;
+ node.uvNode = field.getLinkedObject() || DEFAULT_UV;
} );

examples/jsm/node-editor/scene/MeshEditor.js

@@ -0,0 +1,99 @@
+import { LabelElement } from '../../libs/flow.module.js';
+import { Object3DEditor } from './Object3DEditor.js';
+import { Mesh } from 'three';
+
+export class MeshEditor extends Object3DEditor {
+
+ constructor( mesh = null ) {
+
+ if ( mesh === null ) {
+
+ mesh = new Mesh();
+
+ }
+
+ super( mesh, 'Mesh' );
+
+ this.material = null;
+
+ this.defaultMaterial = null;
+
+ this._initMaterial();
+
+ this.updateDefault();
+ this.restoreDefault();
+ this.update();
+
+ }
+
+ get mesh() {
+
+ return this.value;
+
+ }
+
+ _initMaterial() {
+
+ const materialElement = new LabelElement( 'Material' ).setInputColor( 'forestgreen' ).setInput( 1 );
+
+ materialElement.onValid( ( source, target, stage ) => {
+
+ const object = target.getObject();
+
+ if ( object && object.isMaterial !== true ) {
+
+ if ( stage === 'dragged' ) {
+
+ const name = target.node.getName();
+
+ this.editor.tips.error( `"${name}" is not a Material.` );
+
+ }
+
+ return false;
+
+ }
+
+ } ).onConnect( () => {
+
+ this.material = materialElement.getLinkedObject() || this.defaultMaterial;
+
+ this.update();
+
+ } );
+
+ this.add( materialElement );
+
+ }
+
+ update() {
+
+ super.update();
+
+ const mesh = this.mesh;
+
+ if ( mesh ) {
+
+ mesh.material = this.material || this.defaultMaterial;
+
+ }
+
+ }
+
+ updateDefault() {
+
+ super.updateDefault();
+
+ this.defaultMaterial = this.mesh.material;
+
+ }
+
+ restoreDefault() {
+
+ super.restoreDefault();
+
+ this.mesh.material = this.defaultMaterial;
+
+ }
+
+}

examples/jsm/node-editor/scene/Object3DEditor.js

@@ -0,0 +1,160 @@
+import { NumberInput, StringInput, LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
+import { Group, MathUtils, Vector3 } from 'three';
+
+export class Object3DEditor extends BaseNode {
+
+ constructor( object3d = null, name = 'Object 3D' ) {
+
+ if ( object3d === null ) {
+
+ object3d = new Group();
+
+ }
+
+ super( name, 1, object3d );
+
+ this.defaultPosition = new Vector3();
+ this.defaultRotation = new Vector3();
+ this.defaultScale = new Vector3( 100, 100, 100 );
+
+ this._initTags();
+ this._initTransform();
+
+ this.onValidElement = () => {};
+
+ }
+
+ setEditor( editor ) {
+
+ if ( this.editor ) {
+
+ this.restoreDefault();
+
+ }
+
+ super.setEditor( editor );
+
+ if ( editor ) {
+
+ const name = this.nameInput.getValue();
+ const object3d = editor.scene.getObjectByName( name );
+
+ this.value = object3d;
+
+ this.updateDefault();
+ this.restoreDefault();
+ this.update();
+
+ }
+
+ return this;
+
+ }
+
+ get object3d() {
+
+ return this.value;
+
+ }
+
+ _initTags() {
+
+ this.nameInput = new StringInput( this.object3d.name ).setReadOnly( true )
+ .onChange( () => this.object3d.name = this.nameInput.getValue() );
+
+ this.add( new LabelElement( 'Name' ).add( this.nameInput ) );
+
+ }
+
+ _initTransform() {
+
+ const update = () => this.update();
+
+ const posX = new NumberInput().setTagColor( 'red' ).onChange( update );
+ const posY = new NumberInput().setTagColor( 'green' ).onChange( update );
+ const posZ = new NumberInput().setTagColor( 'blue' ).onChange( update );
+
+ const rotationStep = 1;
+
+ const rotX = new NumberInput().setTagColor( 'red' ).setStep( rotationStep ).onChange( update );
+ const rotY = new NumberInput().setTagColor( 'green' ).setStep( rotationStep ).onChange( update );
+ const rotZ = new NumberInput().setTagColor( 'blue' ).setStep( rotationStep ).onChange( update );
+
+ const scaleX = new NumberInput( 100 ).setTagColor( 'red' ).setStep( rotationStep ).onChange( update );
+ const scaleY = new NumberInput( 100 ).setTagColor( 'green' ).setStep( rotationStep ).onChange( update );
+ const scaleZ = new NumberInput( 100 ).setTagColor( 'blue' ).setStep( rotationStep ).onChange( update );
+
+ this.add( new LabelElement( 'Position' ).add( posX ).add( posY ).add( posZ ) )
+ .add( new LabelElement( 'Rotation' ).add( rotX ).add( rotY ).add( rotZ ) )
+ .add( new LabelElement( 'Scale' ).add( scaleX ).add( scaleY ).add( scaleZ ) );
+
+ this.posX = posX;
+ this.posY = posY;
+ this.posZ = posZ;
+
+ this.rotX = rotX;
+ this.rotY = rotY;
+ this.rotZ = rotZ;
+
+ this.scaleX = scaleX;
+ this.scaleY = scaleY;
+ this.scaleZ = scaleZ;
+
+ }
+
+ update() {
+
+ const object3d = this.object3d;
+
+ if ( object3d ) {
+
+ const { position, rotation, scale } = object3d;
+
+ position.x = this.posX.getValue();
+ position.y = this.posY.getValue();
+ position.z = this.posZ.getValue();
+
+ rotation.x = MathUtils.degToRad( this.rotX.getValue() );
+ rotation.y = MathUtils.degToRad( this.rotY.getValue() );
+ rotation.z = MathUtils.degToRad( this.rotZ.getValue() );
+
+ scale.x = this.scaleX.getValue() / 100;
+ scale.y = this.scaleY.getValue() / 100;
+ scale.z = this.scaleZ.getValue() / 100;
+
+ }
+
+ }
+
+ updateDefault() {
+
+ const { position, rotation, scale } = this.object3d;
+
+ this.defaultPosition = position.clone();
+ this.defaultRotation = new Vector3( MathUtils.radToDeg( rotation.x ), MathUtils.radToDeg( rotation.y ), MathUtils.radToDeg( rotation.z ) );
+ this.defaultScale = scale.clone().multiplyScalar( 100 );
+
+ }
+
+ restoreDefault() {
+
+ const position = this.defaultPosition;
+ const rotation = this.defaultRotation;
+ const scale = this.defaultScale;
+
+ this.posX.setValue( position.x );
+ this.posY.setValue( position.y );
+ this.posZ.setValue( position.z );
+
+ this.rotX.setValue( rotation.x );
+ this.rotY.setValue( rotation.y );
+ this.rotZ.setValue( rotation.z );
+
+ this.scaleX.setValue( scale.x );
+ this.scaleY.setValue( scale.y );
+ this.scaleZ.setValue( scale.z );
+
+ }
+
+}

examples/jsm/node-editor/scene/PointsEditor.js

@@ -0,0 +1,99 @@
+import { LabelElement } from '../../libs/flow.module.js';
+import { Object3DEditor } from './Object3DEditor.js';
+import { Points } from 'three';
+
+export class PointsEditor extends Object3DEditor {
+
+ constructor( points = null ) {
+
+ if ( points === null ) {
+
+ points = new Points();
+
+ }
+
+ super( points, 'Points' );
+
+ this.material = null;
+
+ this.defaultMaterial = null;
+
+ this._initMaterial();
+
+ this.updateDefault();
+ this.restoreDefault();
+ this.update();
+
+ }
+
+ get points() {
+
+ return this.value;
+
+ }
+
+ _initMaterial() {
+
+ const materialElement = new LabelElement( 'Material' ).setInputColor( 'forestgreen' ).setInput( 1 );
+
+ materialElement.onValid( ( source, target, stage ) => {
+
+ const object = target.getObject();
+
+ if ( object && object.isMaterial !== true ) {
+
+ if ( stage === 'dragged' ) {
+
+ const name = target.node.getName();
+
+ this.editor.tips.error( `"${name}" is not a Material.` );
+
+ }
+
+ return false;
+
+ }
+
+ } ).onConnect( () => {
+
+ this.material = materialElement.getLinkedObject() || this.defaultMaterial;
+
+ this.update();
+
+ } );
+
+ this.add( materialElement );
+
+ }
+
+ update() {
+
+ super.update();
+
+ const points = this.points;
+
+ if ( points ) {
+
+ points.material = this.material || this.defaultMaterial;
+
+ }
+
+ }
+
+ updateDefault() {
+
+ super.updateDefault();
+
+ this.defaultMaterial = this.points.material;
+
+ }
+
+ restoreDefault() {
+
+ super.restoreDefault();
+
+ this.points.material = this.defaultMaterial;
+
+ }
+
+}

examples/jsm/node-editor/utils/JoinEditor.js

@@ -0,0 +1,58 @@
+import { LabelElement } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
+import { JoinNode, FloatNode } from '../../renderers/nodes/Nodes.js';
+
+const NULL_VALUE = new FloatNode();
+
+export class JoinEditor extends BaseNode {
+
+ constructor() {
+
+ const node = new JoinNode();
+
+ super( 'Join', 1, node, 175 );
+
+ const update = () => {
+
+ const values = [
+ xElement.getLinkedObject(),
+ yElement.getLinkedObject(),
+ zElement.getLinkedObject(),
+ wElement.getLinkedObject()
+ ];
+
+ let length = 1;
+
+ if ( values[ 3 ] !== null ) length = 4;
+ else if ( values[ 2 ] !== null ) length = 3;
+ else if ( values[ 1 ] !== null ) length = 2;
+
+ const nodes = [];
+
+ for ( let i = 0; i < length; i ++ ) {
+
+ nodes.push( values[ i ] || NULL_VALUE );
+
+ }
+
+ node.nodes = nodes;
+
+ this.invalidate();
+
+ };
+
+ const xElement = new LabelElement( 'X | R' ).setInput( 1 ).onConnect( update );
+ const yElement = new LabelElement( 'Y | G' ).setInput( 1 ).onConnect( update );
+ const zElement = new LabelElement( 'Z | B' ).setInput( 1 ).onConnect( update );
+ const wElement = new LabelElement( 'W | A' ).setInput( 1 ).onConnect( update );
+
+ this.add( xElement )
+ .add( yElement )
+ .add( zElement )
+ .add( wElement );
+
+ update();
+
+ }
+
+}

examples/jsm/node-editor/utils/OscillatorEditor.js

@@ -1,22 +1,23 @@
-import { ObjectNode, SelectInput, LabelElement } from '../../libs/flow.module.js';
+import { SelectInput, LabelElement, Element } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { OscNode, FloatNode } from '../../renderers/nodes/Nodes.js';
const NULL_VALUE = new FloatNode();
-export class OscillatorEditor extends ObjectNode {
+export class OscillatorEditor extends BaseNode {
constructor() {
const node = new OscNode( OscNode.SINE, NULL_VALUE );
- super( 'Oscillator', 1, node, 250 );
+ super( 'Oscillator', 1, node, 175 );
const methodInput = new SelectInput( [
{ name: 'Sine', value: OscNode.SINE },
{ name: 'Square', value: OscNode.SQUARE },
{ name: 'Triangle', value: OscNode.TRIANGLE },
{ name: 'Sawtooth', value: OscNode.SAWTOOTH }
- ] );
+ ], OscNode.SINE );
methodInput.onChange( () => {
@@ -30,11 +31,11 @@
timeElement.onConnect( () => {
- node.timeNode = timeElement.linkedExtra || NULL_VALUE;
+ node.timeNode = timeElement.getLinkedObject() || NULL_VALUE;
} );
- this.add( new LabelElement( 'Method' ).add( methodInput ) )
+ this.add( new Element().add( methodInput ) )
.add( timeElement );
}

examples/jsm/node-editor/utils/SplitEditor.js

@@ -0,0 +1,39 @@
+import { SelectInput, Element } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
+import { SplitNode, FloatNode } from '../../renderers/nodes/Nodes.js';
+
+const NULL_VALUE = new FloatNode();
+
+export class SplitEditor extends BaseNode {
+
+ constructor() {
+
+ const node = new SplitNode( NULL_VALUE, 'x' );
+
+ super( 'Split', 1, node, 175 );
+
+ const componentsField = new SelectInput( [
+ { name: 'X | R', value: 'x' },
+ { name: 'Y | G', value: 'y' },
+ { name: 'Z | B', value: 'z' },
+ { name: 'W | A', value: 'w' }
+ ], node.components ).onChange( () => {
+
+ node.components = componentsField.getValue();
+
+ this.invalidate();
+
+ } );
+
+ const componentsElement = new Element().add( componentsField ).setInput( 1 )
+ .onConnect( () => {
+
+ node.node = componentsElement.getLinkedObject() || NULL_VALUE;
+
+ } );
+
+ this.add( componentsElement );
+
+ }
+
+}

examples/jsm/node-editor/utils/TimerEditor.js

@@ -1,13 +1,14 @@
-import { ObjectNode, NumberInput, LabelElement, Element, ButtonInput } from '../../libs/flow.module.js';
+import { NumberInput, LabelElement, Element, ButtonInput } from '../../libs/flow.module.js';
+import { BaseNode } from '../core/BaseNode.js';
import { TimerNode } from '../../renderers/nodes/Nodes.js';
-export class TimerEditor extends ObjectNode {
+export class TimerEditor extends BaseNode {
constructor() {
const node = new TimerNode();
- super( 'Timer', 1, node, 250 );
+ super( 'Timer', 1, node, 200 );
this.title.setIcon( 'ti ti-clock' );
@@ -37,8 +38,8 @@
} ) ).setSerializable( false );
- this.add( new LabelElement( 'Value' ).add( field ).setSerializable( false ) )
- .add( new LabelElement( 'Scale' ).add( scaleField ) )
+ this.add( new Element().add( field ).setSerializable( false ) )
+ .add( new LabelElement( 'Speed' ).add( scaleField ) )
.add( moreElement );
// extends node

examples/jsm/nodes/utils/ColorSpaceNode.js

@@ -57,9 +57,11 @@
}
- fromDecoding( encoding ) {
+ fromDecoding() {
- const components = ColorSpaceNode.getEncodingComponents( encoding );
+ // TODO: Remove fromDecoding()
+
+ const components = ColorSpaceNode.getEncodingComponents( LinearEncoding );
this.method = components[ 0 ] + 'ToLinear';
this.factor = components[ 1 ];
@@ -106,14 +108,6 @@
}`
);
- const sRGBToLinear = new FunctionNode( /* glsl */`
- vec4 sRGBToLinear( 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.w );
-
- }`
- );
-
const LinearTosRGB = new FunctionNode( /* glsl */`
vec4 LinearTosRGB( in vec4 value ) {
@@ -124,15 +118,12 @@
return {
LinearToLinear: LinearToLinear,
- sRGBToLinear: sRGBToLinear,
LinearTosRGB: LinearTosRGB
};
} )();
ColorSpaceNode.LINEAR_TO_LINEAR = 'LinearToLinear';
-
-ColorSpaceNode.SRGB_TO_LINEAR = 'sRGBToLinear';
ColorSpaceNode.LINEAR_TO_SRGB = 'LinearTosRGB';
ColorSpaceNode.getEncodingComponents = function ( encoding ) {

examples/jsm/objects/Lensflare.js

@@ -8,11 +8,11 @@
InterleavedBufferAttribute,
Mesh,
MeshBasicMaterial,
- RGBFormat,
RawShaderMaterial,
Vector2,
Vector3,
- Vector4
+ Vector4,
+ RGBAFormat
} from 'three';
class Lensflare extends Mesh {
@@ -32,8 +32,8 @@
// textures
- const tempMap = new FramebufferTexture( 16, 16, RGBFormat );
- const occlusionMap = new FramebufferTexture( 16, 16, RGBFormat );
+ const tempMap = new FramebufferTexture( 16, 16, RGBAFormat );
+ const occlusionMap = new FramebufferTexture( 16, 16, RGBAFormat );
// material

examples/jsm/objects/ReflectorForSSRPass.js

@@ -1,11 +1,8 @@
import {
Color,
- LinearFilter,
- MathUtils,
Matrix4,
Mesh,
PerspectiveCamera,
- RGBFormat,
ShaderMaterial,
UniformsUtils,
Vector2,
@@ -104,20 +101,11 @@
}
const parameters = {
- minFilter: LinearFilter,
- magFilter: LinearFilter,
- format: RGBFormat,
depthTexture: useDepthTexture ? depthTexture : null,
};
const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, parameters );
- if ( ! MathUtils.isPowerOfTwo( textureWidth ) || ! MathUtils.isPowerOfTwo( textureHeight ) ) {
-
- renderTarget.texture.generateMipmaps = false;
-
- }
-
const material = new ShaderMaterial( {
transparent: useDepthTexture,
defines: Object.assign( {}, ReflectorForSSRPass.ReflectorShader.defines, {

examples/jsm/objects/Reflector.js

@@ -1,12 +1,9 @@
import {
Color,
- LinearFilter,
- MathUtils,
Matrix4,
Mesh,
PerspectiveCamera,
Plane,
- RGBFormat,
ShaderMaterial,
UniformsUtils,
Vector3,
@@ -47,19 +44,7 @@
const textureMatrix = new Matrix4();
const virtualCamera = new PerspectiveCamera();
- const parameters = {
- minFilter: LinearFilter,
- magFilter: LinearFilter,
- format: RGBFormat
- };
-
- const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, parameters );
-
- if ( ! MathUtils.isPowerOfTwo( textureWidth ) || ! MathUtils.isPowerOfTwo( textureHeight ) ) {
-
- renderTarget.texture.generateMipmaps = false;
-
- }
+ const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight );
const material = new ShaderMaterial( {
uniforms: UniformsUtils.clone( shader.uniforms ),

examples/jsm/objects/Refractor.js

@@ -1,13 +1,10 @@
import {
Color,
- LinearFilter,
- MathUtils,
Matrix4,
Mesh,
PerspectiveCamera,
Plane,
Quaternion,
- RGBFormat,
ShaderMaterial,
UniformsUtils,
Vector3,
@@ -44,19 +41,7 @@
// render target
- const parameters = {
- minFilter: LinearFilter,
- magFilter: LinearFilter,
- format: RGBFormat
- };
-
- const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, parameters );
-
- if ( ! MathUtils.isPowerOfTwo( textureWidth ) || ! MathUtils.isPowerOfTwo( textureHeight ) ) {
-
- renderTarget.texture.generateMipmaps = false;
-
- }
+ const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight );
// material

examples/jsm/objects/Water.js

@@ -1,13 +1,10 @@
import {
Color,
FrontSide,
- LinearFilter,
- MathUtils,
Matrix4,
Mesh,
PerspectiveCamera,
Plane,
- RGBFormat,
ShaderMaterial,
UniformsLib,
UniformsUtils,
@@ -64,19 +61,7 @@
const mirrorCamera = new PerspectiveCamera();
- const parameters = {
- minFilter: LinearFilter,
- magFilter: LinearFilter,
- format: RGBFormat
- };
-
- const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, parameters );
-
- if ( ! MathUtils.isPowerOfTwo( textureWidth ) || ! MathUtils.isPowerOfTwo( textureHeight ) ) {
-
- renderTarget.texture.generateMipmaps = false;
-
- }
+ const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight );
const mirrorShader = {

examples/jsm/postprocessing/GlitchPass.js

@@ -2,7 +2,8 @@
DataTexture,
FloatType,
MathUtils,
- RGBFormat,
+ RedFormat,
+ LuminanceFormat,
ShaderMaterial,
UniformsUtils
} from 'three';
@@ -39,6 +40,8 @@
render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
+ if ( renderer.capabilities.isWebGL2 === false ) this.uniforms[ 'tDisp' ].value.format = LuminanceFormat;
+
this.uniforms[ 'tDiffuse' ].value = readBuffer.texture;
this.uniforms[ 'seed' ].value = Math.random();//default seeding
this.uniforms[ 'byp' ].value = 0;
@@ -94,19 +97,17 @@
generateHeightmap( dt_size ) {
- const data_arr = new Float32Array( dt_size * dt_size * 3 );
+ const data_arr = new Float32Array( dt_size * dt_size );
const length = dt_size * dt_size;
for ( let i = 0; i < length; i ++ ) {
const val = MathUtils.randFloat( 0, 1 );
- data_arr[ i * 3 + 0 ] = val;
- data_arr[ i * 3 + 1 ] = val;
- data_arr[ i * 3 + 2 ] = val;
+ data_arr[ i ] = val;
}
- const texture = new DataTexture( data_arr, dt_size, dt_size, RGBFormat, FloatType );
+ const texture = new DataTexture( data_arr, dt_size, dt_size, RedFormat, FloatType );
texture.needsUpdate = true;
return texture;

examples/jsm/postprocessing/OutlinePass.js

@@ -4,7 +4,6 @@
DoubleSide,
LinearFilter,
Matrix4,
- MeshBasicMaterial,
MeshDepthMaterial,
NoBlending,
RGBADepthPacking,
@@ -46,8 +45,6 @@
const resx = Math.round( this.resolution.x / this.downSampleRatio );
const resy = Math.round( this.resolution.y / this.downSampleRatio );
- this.maskBufferMaterial = new MeshBasicMaterial( { color: 0xffffff } );
- this.maskBufferMaterial.side = DoubleSide;
this.renderTargetMaskBuffer = new WebGLRenderTarget( this.resolution.x, this.resolution.y, pars );
this.renderTargetMaskBuffer.texture.name = 'OutlinePass.mask';
this.renderTargetMaskBuffer.texture.generateMipmaps = false;
@@ -129,7 +126,7 @@
function replaceDepthToViewZ( string, camera ) {
- var type = camera.isPerspectiveCamera ? 'perspective' : 'orthographic';
+ const type = camera.isPerspectiveCamera ? 'perspective' : 'orthographic';
return string.replace( /DEPTH_TO_VIEW_Z/g, type + 'DepthToViewZ' );

examples/jsm/postprocessing/SavePass.js

@@ -1,6 +1,4 @@
import {
- LinearFilter,
- RGBFormat,
ShaderMaterial,
UniformsUtils,
WebGLRenderTarget
@@ -34,7 +32,7 @@
if ( this.renderTarget === undefined ) {
- this.renderTarget = new WebGLRenderTarget( window.innerWidth, window.innerHeight, { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBFormat } );
+ this.renderTarget = new WebGLRenderTarget( window.innerWidth, window.innerHeight );
this.renderTarget.texture.name = 'SavePass.rt';
}

examples/jsm/postprocessing/SMAAPass.js

@@ -1,8 +1,6 @@
import {
LinearFilter,
NearestFilter,
- RGBAFormat,
- RGBFormat,
ShaderMaterial,
Texture,
UniformsUtils,
@@ -22,18 +20,12 @@
// render targets
this.edgesRT = new WebGLRenderTarget( width, height, {
- depthBuffer: false,
- generateMipmaps: false,
- minFilter: LinearFilter,
- format: RGBFormat
+ depthBuffer: false
} );
this.edgesRT.texture.name = 'SMAAPass.edges';
this.weightsRT = new WebGLRenderTarget( width, height, {
- depthBuffer: false,
- generateMipmaps: false,
- minFilter: LinearFilter,
- format: RGBAFormat
+ depthBuffer: false
} );
this.weightsRT.texture.name = 'SMAAPass.weights';
@@ -52,7 +44,6 @@
this.areaTexture = new Texture();
this.areaTexture.name = 'SMAAPass.area';
this.areaTexture.image = areaTextureImage;
- this.areaTexture.format = RGBFormat;
this.areaTexture.minFilter = LinearFilter;
this.areaTexture.generateMipmaps = false;
this.areaTexture.flipY = false;

examples/jsm/postprocessing/SSAOPass.js

@@ -7,16 +7,17 @@
DstAlphaFactor,
DstColorFactor,
FloatType,
- LinearFilter,
MathUtils,
MeshNormalMaterial,
NearestFilter,
NoBlending,
- RGBAFormat,
+ RedFormat,
+ LuminanceFormat,
+ DepthStencilFormat,
+ UnsignedInt248Type,
RepeatWrapping,
ShaderMaterial,
UniformsUtils,
- UnsignedShortType,
Vector3,
WebGLRenderTarget,
ZeroFactor
@@ -61,30 +62,22 @@
// beauty render target
const depthTexture = new DepthTexture();
- depthTexture.type = UnsignedShortType;
+ depthTexture.format = DepthStencilFormat;
+ depthTexture.type = UnsignedInt248Type;
- this.beautyRenderTarget = new WebGLRenderTarget( this.width, this.height, {
- minFilter: LinearFilter,
- magFilter: LinearFilter,
- format: RGBAFormat
- } );
+ this.beautyRenderTarget = new WebGLRenderTarget( this.width, this.height );
// normal render target with depth buffer
this.normalRenderTarget = new WebGLRenderTarget( this.width, this.height, {
minFilter: NearestFilter,
magFilter: NearestFilter,
- format: RGBAFormat,
depthTexture: depthTexture
} );
// ssao render target
- this.ssaoRenderTarget = new WebGLRenderTarget( this.width, this.height, {
- minFilter: LinearFilter,
- magFilter: LinearFilter,
- format: RGBAFormat
- } );
+ this.ssaoRenderTarget = new WebGLRenderTarget( this.width, this.height );
this.blurRenderTarget = this.ssaoRenderTarget.clone();
@@ -191,6 +184,8 @@
render( renderer, writeBuffer /*, readBuffer, deltaTime, maskActive */ ) {
+ if ( renderer.capabilities.isWebGL2 === false ) this.noiseTexture.format = LuminanceFormat;
+
// render beauty
renderer.setRenderTarget( this.beautyRenderTarget );
@@ -391,26 +386,19 @@
const simplex = new SimplexNoise();
const size = width * height;
- const data = new Float32Array( size * 4 );
+ const data = new Float32Array( size );
for ( let i = 0; i < size; i ++ ) {
- const stride = i * 4;
-
const x = ( Math.random() * 2 ) - 1;
const y = ( Math.random() * 2 ) - 1;
const z = 0;
- const noise = simplex.noise3d( x, y, z );
-
- data[ stride ] = noise;
- data[ stride + 1 ] = noise;
- data[ stride + 2 ] = noise;
- data[ stride + 3 ] = 1;
+ data[ i ] = simplex.noise3d( x, y, z );
}
- this.noiseTexture = new DataTexture( data, width, height, RGBAFormat, FloatType );
+ this.noiseTexture = new DataTexture( data, width, height, RedFormat, FloatType );
this.noiseTexture.wrapS = RepeatWrapping;
this.noiseTexture.wrapT = RepeatWrapping;
this.noiseTexture.needsUpdate = true;

examples/jsm/renderers/CSS2DRenderer.js

@@ -113,6 +113,11 @@
if ( object.isCSS2DObject ) {
+ const visible = object.visible && _vector.z >= - 1 && _vector.z <= 1 && object.layers.test( camera.layers );
+ object.element.style.display = visible ? '' : 'none';
+
+ if ( visible ) {
+
object.onBeforeRender( _this, scene, camera );
_vector.setFromMatrixPosition( object.matrixWorld );
@@ -131,8 +136,6 @@
}
- element.style.display = ( object.visible && _vector.z >= - 1 && _vector.z <= 1 ) ? '' : 'none';
-
const objectData = {
distanceToCameraSquared: getDistanceToSquared( camera, object )
};
@@ -149,6 +152,8 @@
}
+ }
+
for ( let i = 0, l = object.children.length; i < l; i ++ ) {
renderObject( object.children[ i ], scene, camera );

examples/jsm/renderers/CSS3DRenderer.js

@@ -239,6 +239,12 @@
if ( object.isCSS3DObject ) {
+ const visible = object.visible && object.layers.test( camera.layers );
+ object.element.style.display = visible ? '' : 'none';
+
+ // only getObjectCSSMatrix when object.visible
+ if ( visible ) {
+
object.onBeforeRender( _this, scene, camera );
let style;
@@ -281,8 +287,6 @@
}
- element.style.display = object.visible ? '' : 'none';
-
if ( element.parentNode !== cameraElement ) {
cameraElement.appendChild( element );
@@ -293,6 +297,8 @@
}
+ }
+
for ( let i = 0, l = object.children.length; i < l; i ++ ) {
renderObject( object.children[ i ], scene, camera, cameraCSSMatrix );

examples/jsm/renderers/nodes/accessors/UVNode.js

@@ -2,19 +2,19 @@
class UVNode extends AttributeNode {
- constructor( value = 0 ) {
+ constructor( index = 0 ) {
super( null, 'vec2' );
- this.value = value;
+ this.index = index;
}
getAttributeName( /*builder*/ ) {
- const value = this.value;
+ const index = this.index;
- return 'uv' + ( value > 0 ? value + 1 : '' );
+ return 'uv' + ( index > 0 ? index + 1 : '' );
}

examples/jsm/renderers/nodes/core/NodeBuilder.js

@@ -8,7 +8,8 @@
import { REVISION, LinearEncoding } from 'three';
-const shaderStages = [ 'fragment', 'vertex' ];
+export const shaderStages = [ 'fragment', 'vertex' ];
+export const vector = [ 'x', 'y', 'z', 'w' ];
class NodeBuilder {

examples/jsm/renderers/nodes/display/ColorSpaceNode.js

@@ -1,7 +1,7 @@
import TempNode from '../core/Node.js';
import { ShaderNode,
vec3,
- pow, mul, add, sub, mix, join,
+ pow, mul, sub, mix, join,
lessThanEqual } from '../ShaderNode.js';
import { LinearEncoding, sRGBEncoding } from 'three';
@@ -12,22 +12,6 @@
} );
-export const sRGBToLinear = new ShaderNode( ( inputs ) => {
-
- const { value } = inputs;
-
- const rgb = value.rgb;
-
- const a = pow( add( mul( rgb, 0.9478672986 ), vec3( 0.0521327014 ) ), vec3( 2.4 ) );
- const b = mul( rgb, 0.0773993808 );
- const factor = vec3( lessThanEqual( rgb, vec3( 0.04045 ) ) );
-
- const rgbResult = mix( a, b, factor );
-
- return join( rgbResult.r, rgbResult.g, rgbResult.b, value.a );
-
-} );
-
export const LinearTosRGB = new ShaderNode( ( inputs ) => {
const { value } = inputs;
@@ -46,28 +30,12 @@
const EncodingLib = {
LinearToLinear,
- sRGBToLinear,
LinearTosRGB
};
-function getEncodingComponents( encoding ) {
-
- switch ( encoding ) {
-
- case LinearEncoding:
- return [ 'Linear' ];
- case sRGBEncoding:
- return [ 'sRGB' ];
-
- }
-
-}
-
class ColorSpaceNode extends TempNode {
static LINEAR_TO_LINEAR = 'LinearToLinear';
-
- static SRGB_TO_LINEAR = 'sRGBToLinear';
static LINEAR_TO_SRGB = 'LinearTosRGB';
constructor( method, node ) {
@@ -77,27 +45,24 @@
this.method = method;
this.node = node;
- this.factor = null;
}
fromEncoding( encoding ) {
- const components = getEncodingComponents( encoding );
+ let method = null;
- this.method = 'LinearTo' + components[ 0 ];
- this.factor = components[ 1 ];
+ if ( encoding === LinearEncoding ) {
- return this;
+ method = 'Linear';
- }
+ } else if ( encoding === sRGBEncoding ) {
- fromDecoding( encoding ) {
+ method = 'sRGB';
- const components = getEncodingComponents( encoding );
+ }
- this.method = components[ 0 ] + 'ToLinear';
- this.factor = components[ 1 ];
+ this.method = 'LinearTo' + method;
return this;
@@ -113,11 +78,9 @@
if ( method !== ColorSpaceNode.LINEAR_TO_LINEAR ) {
const encodingFunctionNode = EncodingLib[ method ];
- const factor = this.factor;
return encodingFunctionNode( {
- value: node,
- factor
+ value: node
} ).build( builder, type );
} else {

examples/jsm/renderers/nodes/inputs/TextureNode.js

@@ -1,7 +1,6 @@
import InputNode from '../core/InputNode.js';
import ExpressionNode from '../core/ExpressionNode.js';
import UVNode from '../accessors/UVNode.js';
-import ColorSpaceNode from '../display/ColorSpaceNode.js';
class TextureNode extends InputNode {
@@ -41,9 +40,9 @@
const nodeData = builder.getDataFromNode( this );
- let colorSpace = nodeData.colorSpace;
+ let snippet = nodeData.snippet;
- if ( colorSpace === undefined ) {
+ if ( snippet === undefined ) {
const uvSnippet = this.uv.build( builder, 'vec2' );
const bias = this.bias;
@@ -56,17 +55,13 @@
}
- const textureCallSnippet = builder.getTexture( textureProperty, uvSnippet, biasSnippet );
+ snippet = builder.getTexture( textureProperty, uvSnippet, biasSnippet );
- colorSpace = new ColorSpaceNode();
- colorSpace.node = new ExpressionNode( textureCallSnippet, 'vec4' );
- colorSpace.fromDecoding( builder.getTextureEncodingFromMap( texture ) );
-
- nodeData.colorSpace = colorSpace;
+ nodeData.snippet = snippet;
}
- return colorSpace.build( builder, output );
+ return builder.format( snippet, 'vec4', output );
}

examples/jsm/renderers/nodes/math/MathNode.js

@@ -33,7 +33,8 @@
static INVERT = 'invert';
static DFDX = 'dFdx';
static DFDY = 'dFdy';
- static SATURATE = 'saturate'
+ static SATURATE = 'saturate';
+ static ROUND = 'round';
// 2 inputs

examples/jsm/renderers/nodes/Nodes.js

@@ -55,6 +55,7 @@
// math
import MathNode from './math/MathNode.js';
import OperatorNode from './math/OperatorNode.js';
+import CondNode from './math/CondNode.js';
// lights
import LightContextNode from './lights/LightContextNode.js';
@@ -143,6 +144,7 @@
// math
MathNode,
OperatorNode,
+ CondNode,
// lights
LightContextNode,

examples/jsm/renderers/nodes/ShaderNode.js

@@ -69,6 +69,8 @@
};
+const nodeObjects = new WeakMap();
+
const ShaderNodeObject = ( obj ) => {
const type = typeof obj;
@@ -81,16 +83,17 @@
if ( obj.isNode === true ) {
- const node = obj;
-
- if ( node.isProxyNode !== true ) {
+ let nodeObject = nodeObjects.get( obj );
- node.isProxyNode = true;
+ if ( nodeObject === undefined ) {
- return new Proxy( node, NodeHandler );
+ nodeObject = new Proxy( obj, NodeHandler );
+ nodeObjects.set( obj, nodeObject );
}
+ return nodeObject;
+
}
}
@@ -183,27 +186,33 @@
} );
+export const nodeObject = ( val ) => {
+
+ return ShaderNodeObject( val );
+
+};
+
export const float = ( val ) => {
- return ShaderNodeObject( new FloatNode( val ).setConst( true ) );
+ return nodeObject( new FloatNode( val ).setConst( true ) );
};
export const color = ( ...params ) => {
- return ShaderNodeObject( new ColorNode( new Color( ...params ) ).setConst( true ) );
+ return nodeObject( new ColorNode( new Color( ...params ) ).setConst( true ) );
};
export const join = ( ...params ) => {
- return ShaderNodeObject( new JoinNode( ShaderNodeArray( params ) ) );
+ return nodeObject( new JoinNode( ShaderNodeArray( params ) ) );
};
export const cond = ( ...params ) => {
- return ShaderNodeObject( new CondNode( ...ShaderNodeArray( params ) ) );
+ return nodeObject( new CondNode( ...ShaderNodeArray( params ) ) );
};
@@ -211,7 +220,7 @@
if ( params[ 0 ]?.isNode === true ) {
- return ShaderNodeObject( new ConvertNode( params[ 0 ], 'vec2' ) );
+ return nodeObject( new ConvertNode( params[ 0 ], 'vec2' ) );
} else {
@@ -223,7 +232,7 @@
}
- return ShaderNodeObject( new Vector2Node( new Vector2( ...params ) ).setConst( true ) );
+ return nodeObject( new Vector2Node( new Vector2( ...params ) ).setConst( true ) );
}
@@ -233,7 +242,7 @@
if ( params[ 0 ]?.isNode === true ) {
- return ShaderNodeObject( new ConvertNode( params[ 0 ], 'vec3' ) );
+ return nodeObject( new ConvertNode( params[ 0 ], 'vec3' ) );
} else {
@@ -245,7 +254,7 @@
}
- return ShaderNodeObject( new Vector3Node( new Vector3( ...params ) ).setConst( true ) );
+ return nodeObject( new Vector3Node( new Vector3( ...params ) ).setConst( true ) );
}
@@ -255,7 +264,7 @@
if ( params[ 0 ]?.isNode === true ) {
- return ShaderNodeObject( new ConvertNode( params[ 0 ], 'vec4' ) );
+ return nodeObject( new ConvertNode( params[ 0 ], 'vec4' ) );
} else {
@@ -267,7 +276,7 @@
}
- return ShaderNodeObject( new Vector4Node( new Vector4( ...params ) ).setConst( true ) );
+ return nodeObject( new Vector4Node( new Vector4( ...params ) ).setConst( true ) );
}
@@ -277,7 +286,7 @@
varNode.node = add( varNode.node, ...ShaderNodeArray( params ) );
- return ShaderNodeObject( varNode );
+ return nodeObject( varNode );
};
@@ -318,29 +327,47 @@
export const specularColor = new PropertyNode( 'SpecularColor', 'color' );
export const abs = ShaderNodeProxy( MathNode, 'abs' );
-export const negate = ShaderNodeProxy( MathNode, 'negate' );
-export const floor = ShaderNodeProxy( MathNode, 'floor' );
-export const mod = ShaderNodeProxy( MathNode, 'mod' );
+export const acos = ShaderNodeProxy( MathNode, 'acos' );
+export const asin = ShaderNodeProxy( MathNode, 'asin' );
+export const atan = ShaderNodeProxy( MathNode, 'atan' );
+export const ceil = ShaderNodeProxy( MathNode, 'ceil' );
+export const clamp = ShaderNodeProxy( MathNode, 'clamp' );
+export const cos = ShaderNodeProxy( MathNode, 'cos' );
export const cross = ShaderNodeProxy( MathNode, 'cross' );
+export const degrees = ShaderNodeProxy( MathNode, 'degrees' );
+export const dFdx = ShaderNodeProxy( MathNode, 'dFdx' );
+export const dFdy = ShaderNodeProxy( MathNode, 'dFdy' );
+export const distance = ShaderNodeProxy( MathNode, 'distance' );
+export const dot = ShaderNodeProxy( MathNode, 'dot' );
+export const exp = ShaderNodeProxy( MathNode, 'exp' );
+export const exp2 = ShaderNodeProxy( MathNode, 'exp2' );
+export const faceforward = ShaderNodeProxy( MathNode, 'faceforward' );
+export const floor = ShaderNodeProxy( MathNode, 'floor' );
export const fract = ShaderNodeProxy( MathNode, 'fract' );
-export const round = ShaderNodeProxy( MathNode, 'round' );
+export const invert = ShaderNodeProxy( MathNode, 'invert' );
+export const inversesqrt = ShaderNodeProxy( MathNode, 'inversesqrt' );
+export const length = ShaderNodeProxy( MathNode, 'length' );
+export const log = ShaderNodeProxy( MathNode, 'log' );
+export const log2 = ShaderNodeProxy( MathNode, 'log2' );
export const max = ShaderNodeProxy( MathNode, 'max' );
export const min = ShaderNodeProxy( MathNode, 'min' );
-export const sin = ShaderNodeProxy( MathNode, 'sin' );
-export const cos = ShaderNodeProxy( MathNode, 'cos' );
-export const dot = ShaderNodeProxy( MathNode, 'dot' );
+export const mix = ShaderNodeProxy( MathNode, 'mix' );
+export const mod = ShaderNodeProxy( MathNode, 'mod' );
+export const negate = ShaderNodeProxy( MathNode, 'negate' );
export const normalize = ShaderNodeProxy( MathNode, 'normalize' );
-export const sqrt = ShaderNodeProxy( MathNode, 'sqrt' );
-export const inversesqrt = ShaderNodeProxy( MathNode, 'inversesqrt' );
-export const sign = ShaderNodeProxy( MathNode, 'sign' );
-export const dFdx = ShaderNodeProxy( MathNode, 'dFdx' );
-export const dFdy = ShaderNodeProxy( MathNode, 'dFdy' );
export const pow = ShaderNodeProxy( MathNode, 'pow' );
export const pow2 = ShaderNodeProxy( MathNode, 'pow', 2 );
export const pow3 = ShaderNodeProxy( MathNode, 'pow', 3 );
export const pow4 = ShaderNodeProxy( MathNode, 'pow', 4 );
-export const exp = ShaderNodeProxy( MathNode, 'exp' );
-export const exp2 = ShaderNodeProxy( MathNode, 'exp2' );
-export const mix = ShaderNodeProxy( MathNode, 'mix' );
+export const radians = ShaderNodeProxy( MathNode, 'radians' );
+export const reflect = ShaderNodeProxy( MathNode, 'reflect' );
+export const refract = ShaderNodeProxy( MathNode, 'refract' );
+export const round = ShaderNodeProxy( MathNode, 'round' );
export const saturate = ShaderNodeProxy( MathNode, 'saturate' );
+export const sign = ShaderNodeProxy( MathNode, 'sign' );
+export const sin = ShaderNodeProxy( MathNode, 'sin' );
+export const smoothstep = ShaderNodeProxy( MathNode, 'smoothstep' );
+export const sqrt = ShaderNodeProxy( MathNode, 'sqrt' );
+export const step = ShaderNodeProxy( MathNode, 'step' );
+export const tan = ShaderNodeProxy( MathNode, 'tan' );
export const transformDirection = ShaderNodeProxy( MathNode, 'transformDirection' );

examples/jsm/renderers/nodes/utils/SplitNode.js

@@ -1,4 +1,5 @@
import Node from '../core/Node.js';
+import { vector } from '../core/NodeBuilder.js';
class SplitNode extends Node {
@@ -11,6 +12,20 @@
}
+ getVectorLength() {
+
+ let vectorLength = this.components.length;
+
+ for ( const c of this.components ) {
+
+ vectorLength = Math.max( vector.indexOf( c ) + 1, vectorLength );
+
+ }
+
+ return vectorLength;
+
+ }
+
getNodeType( builder ) {
return builder.getTypeFromLength( this.components.length );
@@ -24,15 +39,15 @@
if ( nodeTypeLength > 1 ) {
- const components = this.components;
-
let type = null;
- if ( components.length >= nodeTypeLength ) {
+ const componentsLength = this.getVectorLength();
+
+ if ( componentsLength >= nodeTypeLength ) {
// need expand the input node
- type = this.getNodeType( builder );
+ type = builder.getTypeFromLength( this.getVectorLength() );
}

examples/jsm/renderers/webgpu/nodes/WebGPUNodeBuilder.js

@@ -25,7 +25,7 @@
import LightContextNode from '../../nodes/lights/LightContextNode.js';
import OperatorNode from '../../nodes/math/OperatorNode.js';
import WGSLNodeParser from '../../nodes/parsers/WGSLNodeParser.js';
-import { vec4 } from '../../nodes/ShaderNode.js';
+import { vec4, join, nodeObject } from '../../nodes/ShaderNode.js';
import { getRoughness } from '../../nodes/functions/PhysicalMaterialFunctions.js';
const wgslTypeLib = {
@@ -150,7 +150,7 @@
colorNode = this.addFlow( 'fragment', new VarNode( colorNode, 'Color', 'vec4' ) );
- this.addFlow( 'fragment', new VarNode( colorNode, 'DiffuseColor', 'vec4' ) );
+ const diffuseColorNode = this.addFlow( 'fragment', new VarNode( colorNode, 'DiffuseColor', 'vec4' ) );
// OPACITY
@@ -254,7 +254,7 @@
// LIGHT
- let outputNode = colorNode;
+ let outputNode = diffuseColorNode;
if ( lightNode && lightNode.isNode ) {
@@ -266,11 +266,17 @@
// RESULT
+ const outputNodeObj = nodeObject( outputNode );
+
+ outputNode = join( outputNodeObj.x, outputNodeObj.y, outputNodeObj.z, nodeObject( diffuseColorNode ).w );
+
+ //
+
const outputEncoding = this.renderer.outputEncoding;
if ( outputEncoding !== LinearEncoding ) {
- outputNode = new ColorSpaceNode( ColorSpaceNode.LINEAR_TO_LINEAR, vec4( outputNode ) );
+ outputNode = new ColorSpaceNode( ColorSpaceNode.LINEAR_TO_LINEAR, outputNode );
outputNode.fromEncoding( outputEncoding );
}

examples/jsm/renderers/webgpu/WebGPU.js

@@ -1,33 +0,0 @@
-class WebGPU {
-
- static isAvailable() {
-
- return ( navigator.gpu !== undefined );
-
- }
-
- static getErrorMessage() {
-
- const message = 'Your browser does not support <a href="https://gpuweb.github.io/gpuweb/" style="color:#000">WebGPU</a>.';
-
- const element = document.createElement( 'div' );
- element.id = 'webgpumessage';
- element.style.fontFamily = 'monospace';
- element.style.fontSize = '13px';
- element.style.fontWeight = 'normal';
- element.style.textAlign = 'center';
- element.style.background = '#fff';
- element.style.color = '#000';
- element.style.padding = '1.5em';
- element.style.width = '400px';
- element.style.margin = '5em auto 0';
-
- element.innerHTML = message;
-
- return element;
-
- }
-
-}
-
-export default WebGPU;

examples/jsm/renderers/webgpu/WebGPUObjects.js

@@ -17,7 +17,7 @@
if ( geometry.isBufferGeometry !== true ) {
- throw 'THREE.WebGPURenderer: This renderer only supports THREE.BufferGeometry for geometries.';
+ throw new Error( 'THREE.WebGPURenderer: This renderer only supports THREE.BufferGeometry for geometries.' );
}

examples/jsm/renderers/webgpu/WebGPURenderer.js

@@ -92,7 +92,6 @@
this._adapter = null;
this._device = null;
this._context = null;
- this._swapChain = null;
this._colorBuffer = null;
this._depthBuffer = null;
@@ -166,15 +165,14 @@
const context = ( parameters.context !== undefined ) ? parameters.context : this.domElement.getContext( 'webgpu' );
- const swapChain = context.configure( {
+ context.configure( {
device: device,
- format: GPUTextureFormat.BGRA8Unorm // this is the only valid swap chain format right now (r121)
+ format: GPUTextureFormat.BGRA8Unorm // this is the only valid context format right now (r121)
} );
this._adapter = adapter;
this._device = device;
this._context = context;
- this._swapChain = swapChain;
this._info = new WebGPUInfo();
this._properties = new WebGPUProperties();
@@ -489,7 +487,7 @@
} else {
- format = GPUTextureFormat.BGRA8Unorm; // default swap chain format
+ format = GPUTextureFormat.BGRA8Unorm; // default context format
}

examples/jsm/renderers/webgpu/WebGPUTextures.js

@@ -1,6 +1,6 @@
import { GPUTextureFormat, GPUAddressMode, GPUFilterMode, GPUTextureDimension } from './constants.js';
import { CubeTexture, Texture, NearestFilter, NearestMipmapNearestFilter, NearestMipmapLinearFilter, LinearFilter, RepeatWrapping, MirroredRepeatWrapping,
- RGBFormat, RGBAFormat, RedFormat, RGFormat, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, UnsignedByteType, FloatType, HalfFloatType, sRGBEncoding
+ RGBAFormat, RedFormat, RGFormat, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, UnsignedByteType, FloatType, HalfFloatType, sRGBEncoding
} from 'three';
import WebGPUTextureUtils from './WebGPUTextureUtils.js';
@@ -564,7 +564,6 @@
formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
break;
- case RGBFormat:
case RGBAFormat:
switch ( type ) {

examples/jsm/shaders/DigitalGlitch.js

@@ -62,7 +62,7 @@
float xs = floor(gl_FragCoord.x / 0.5);
float ys = floor(gl_FragCoord.y / 0.5);
//based on staffantans glitch shader for unity https://github.com/staffantan/unityglitch
- vec4 normal = texture2D (tDisp, p*seed*seed);
+ float disp = texture2D(tDisp, p*seed*seed).r;
if(p.y<distortion_x+col_s && p.y>distortion_x-col_s*seed) {
if(seed_x>0.){
p.y = 1. - (p.y + distortion_y);
@@ -79,8 +79,8 @@
p.x = 1. - (p.x + distortion_x);
}
}
- p.x+=normal.x*seed_x*(seed/5.);
- p.y+=normal.y*seed_y*(seed/5.);
+ p.x+=disp*seed_x*(seed/5.);
+ p.y+=disp*seed_y*(seed/5.);
//base from RGB shift shader
vec2 offset = amount * vec2( cos(angle), sin(angle));
vec4 cr = texture2D(tDiffuse, p + offset);

examples/jsm/shaders/MMDToonShader.js

@@ -57,7 +57,6 @@
vec3 y = cross( viewDir, x );
vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; // 0.495 to remove artifacts caused by undersized matcap disks
vec4 matcapColor = texture2D( matcap, uv );
- matcapColor = matcapTexelToLinear( matcapColor );
#ifdef MATCAP_BLENDING_MULTIPLY

examples/jsm/shaders/SSAOShader.js

@@ -134,7 +134,7 @@
vec3 viewNormal = getViewNormal( vUv );
vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 );
- vec3 random = texture2D( tNoise, vUv * noiseScale ).xyz;
+ vec3 random = vec3( texture2D( tNoise, vUv * noiseScale ).r );
// compute matrix used to reorient a kernel vector

examples/jsm/utils/LDrawUtils.js

@@ -0,0 +1,202 @@
+import {
+ BufferAttribute,
+ BufferGeometry,
+ Group,
+ LineSegments,
+ Matrix3,
+ Mesh
+} from 'three';
+
+import { mergeBufferGeometries } from './BufferGeometryUtils.js';
+
+class LDrawUtils {
+
+ static mergeObject( object ) {
+
+ // Merges geometries in object by materials and returns new object. Use on not indexed geometries.
+ // The object buffers reference the old object ones.
+ // Special treatment is done to the conditional lines generated by LDrawLoader.
+
+ function extractGroup( geometry, group, elementSize, isConditionalLine ) {
+
+ // Extracts a group from a geometry as a new geometry (with attribute buffers referencing original buffers)
+
+ const newGeometry = new BufferGeometry();
+
+ const originalPositions = geometry.getAttribute( 'position' ).array;
+ const originalNormals = elementSize === 3 ? geometry.getAttribute( 'normal' ).array : null;
+
+ const numVertsGroup = Math.min( group.count, Math.floor( originalPositions.length / 3 ) - group.start );
+ const vertStart = group.start * 3;
+ const vertEnd = ( group.start + numVertsGroup ) * 3;
+
+ const positions = originalPositions.subarray( vertStart, vertEnd );
+ const normals = originalNormals !== null ? originalNormals.subarray( vertStart, vertEnd ) : null;
+
+ newGeometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
+ if ( normals !== null ) newGeometry.setAttribute( 'normal', new BufferAttribute( normals, 3 ) );
+
+ if ( isConditionalLine ) {
+
+ const controlArray0 = geometry.getAttribute( 'control0' ).array.subarray( vertStart, vertEnd );
+ const controlArray1 = geometry.getAttribute( 'control1' ).array.subarray( vertStart, vertEnd );
+ const directionArray = geometry.getAttribute( 'direction' ).array.subarray( vertStart, vertEnd );
+
+ newGeometry.setAttribute( 'control0', new BufferAttribute( controlArray0, 3, false ) );
+ newGeometry.setAttribute( 'control1', new BufferAttribute( controlArray1, 3, false ) );
+ newGeometry.setAttribute( 'direction', new BufferAttribute( directionArray, 3, false ) );
+
+ }
+
+ return newGeometry;
+
+ }
+
+ function addGeometry( mat, geometry, geometries ) {
+
+ const geoms = geometries[ mat.uuid ];
+ if ( ! geoms ) {
+
+ geometries[ mat.uuid ] = {
+ mat: mat,
+ arr: [ geometry ]
+ };
+
+ } else {
+
+ geoms.arr.push( geometry );
+
+ }
+
+ }
+
+ function permuteAttribute( attribute, elemSize ) {
+
+ // Permutes first two vertices of each attribute element
+
+ if ( ! attribute ) return;
+
+ const verts = attribute.array;
+ const numVerts = Math.floor( verts.length / 3 );
+ let offset = 0;
+ for ( let i = 0; i < numVerts; i ++ ) {
+
+ const x = verts[ offset ];
+ const y = verts[ offset + 1 ];
+ const z = verts[ offset + 2 ];
+
+ verts[ offset ] = verts[ offset + 3 ];
+ verts[ offset + 1 ] = verts[ offset + 4 ];
+ verts[ offset + 2 ] = verts[ offset + 5 ];
+
+ verts[ offset + 3 ] = x;
+ verts[ offset + 4 ] = y;
+ verts[ offset + 5 ] = z;
+
+ offset += elemSize * 3;
+
+ }
+
+ }
+
+ // Traverse the object hierarchy collecting geometries and transforming them to world space
+
+ const meshGeometries = {};
+ const linesGeometries = {};
+ const condLinesGeometries = {};
+
+ object.updateMatrixWorld( true );
+ const normalMatrix = new Matrix3();
+
+ object.traverse( c => {
+
+ if ( c.isMesh | c.isLineSegments ) {
+
+ const elemSize = c.isMesh ? 3 : 2;
+
+ const geometry = c.geometry.clone();
+ const matrixIsInverted = c.matrixWorld.determinant() < 0;
+ if ( matrixIsInverted ) {
+
+ permuteAttribute( geometry.attributes.position, elemSize );
+ permuteAttribute( geometry.attributes.normal, elemSize );
+
+ }
+
+ geometry.applyMatrix4( c.matrixWorld );
+
+ if ( c.isConditionalLine ) {
+
+ geometry.attributes.control0.applyMatrix4( c.matrixWorld );
+ geometry.attributes.control1.applyMatrix4( c.matrixWorld );
+ normalMatrix.getNormalMatrix( c.matrixWorld );
+ geometry.attributes.direction.applyNormalMatrix( normalMatrix );
+
+ }
+
+ const geometries = c.isMesh ? meshGeometries : ( c.isConditionalLine ? condLinesGeometries : linesGeometries );
+
+ if ( Array.isArray( c.material ) ) {
+
+ for ( const groupIndex in geometry.groups ) {
+
+ const group = geometry.groups[ groupIndex ];
+ const mat = c.material[ group.materialIndex ];
+ const newGeometry = extractGroup( geometry, group, elemSize, c.isConditionalLine );
+ addGeometry( mat, newGeometry, geometries );
+
+ }
+
+ } else {
+
+ addGeometry( c.material, geometry, geometries );
+
+ }
+
+ }
+
+ } );
+
+ // Create object with merged geometries
+
+ const mergedObject = new Group();
+
+ const meshMaterialsIds = Object.keys( meshGeometries );
+ for ( const i in meshMaterialsIds ) {
+
+ const meshGeometry = meshGeometries[ meshMaterialsIds[ i ] ];
+ const mergedGeometry = mergeBufferGeometries( meshGeometry.arr );
+ mergedObject.add( new Mesh( mergedGeometry, meshGeometry.mat ) );
+
+ }
+
+ const linesMaterialsIds = Object.keys( linesGeometries );
+ for ( const i in linesMaterialsIds ) {
+
+ const lineGeometry = linesGeometries[ linesMaterialsIds[ i ] ];
+ const mergedGeometry = mergeBufferGeometries( lineGeometry.arr );
+ mergedObject.add( new LineSegments( mergedGeometry, lineGeometry.mat ) );
+
+ }
+
+ const condLinesMaterialsIds = Object.keys( condLinesGeometries );
+ for ( const i in condLinesMaterialsIds ) {
+
+ const condLineGeometry = condLinesGeometries[ condLinesMaterialsIds[ i ] ];
+ const mergedGeometry = mergeBufferGeometries( condLineGeometry.arr );
+ const condLines = new LineSegments( mergedGeometry, condLineGeometry.mat );
+ condLines.isConditionalLine = true;
+ mergedObject.add( condLines );
+
+ }
+
+ mergedObject.userData.constructionStep = 0;
+ mergedObject.userData.numConstructionSteps = 1;
+
+ return mergedObject;
+
+ }
+
+}
+
+export { LDrawUtils };

examples/jsm/utils/RoughnessMipmapper.js

@@ -1,288 +0,0 @@
-/**
- * This class generates custom mipmaps for a roughness map by encoding the lost variation in the
- * normal map mip levels as increased roughness in the corresponding roughness mip levels. This
- * helps with rendering accuracy for MeshStandardMaterial, and also helps with anti-aliasing when
- * using PMREM. If the normal map is larger than the roughness map, the roughness map will be
- * enlarged to match the dimensions of the normal map.
- */
-
-import {
- MathUtils,
- Mesh,
- NoBlending,
- OrthographicCamera,
- PlaneGeometry,
- RawShaderMaterial,
- Vector2,
- WebGLRenderTarget,
- FramebufferTexture
-} from 'three';
-
-const _mipmapMaterial = _getMipmapMaterial();
-
-const _mesh = new Mesh( new PlaneGeometry( 2, 2 ), _mipmapMaterial );
-
-const _flatCamera = new OrthographicCamera( 0, 1, 0, 1, 0, 1 );
-
-let _tempTarget = null;
-
-let _renderer = null;
-
-class RoughnessMipmapper {
-
- constructor( renderer ) {
-
- _renderer = renderer;
-
- _renderer.compile( _mesh, _flatCamera );
-
- }
-
- generateMipmaps( material ) {
-
- if ( 'roughnessMap' in material === false ) return;
-
- const { roughnessMap, normalMap } = material;
-
- if ( roughnessMap === null || normalMap === null || ! roughnessMap.generateMipmaps || material.userData.roughnessUpdated ) return;
-
- material.userData.roughnessUpdated = true;
-
- let width = Math.max( roughnessMap.image.width, normalMap.image.width );
- let height = Math.max( roughnessMap.image.height, normalMap.image.height );
-
- if ( ! MathUtils.isPowerOfTwo( width ) || ! MathUtils.isPowerOfTwo( height ) ) return;
-
- const oldTarget = _renderer.getRenderTarget();
-
- const autoClear = _renderer.autoClear;
-
- _renderer.autoClear = false;
-
- if ( _tempTarget === null || _tempTarget.width !== width || _tempTarget.height !== height ) {
-
- if ( _tempTarget !== null ) _tempTarget.dispose();
-
- _tempTarget = new WebGLRenderTarget( width, height, { depthBuffer: false } );
-
- _tempTarget.scissorTest = true;
-
- }
-
- const newRoughnessTexture = new FramebufferTexture( width, height, roughnessMap.format );
- newRoughnessTexture.wrapS = roughnessMap.wrapS;
- newRoughnessTexture.wrapT = roughnessMap.wrapT;
- newRoughnessTexture.minFilter = roughnessMap.minFilter;
- newRoughnessTexture.magFilter = roughnessMap.magFilter;
-
- material.roughnessMap = newRoughnessTexture;
-
- if ( material.metalnessMap == roughnessMap ) material.metalnessMap = material.roughnessMap;
-
- if ( material.aoMap == roughnessMap ) material.aoMap = material.roughnessMap;
-
- // Copy UV transform parameters
-
- material.roughnessMap.offset.copy( roughnessMap.offset );
- material.roughnessMap.repeat.copy( roughnessMap.repeat );
- material.roughnessMap.center.copy( roughnessMap.center );
- material.roughnessMap.rotation = roughnessMap.rotation;
- material.roughnessMap.image = roughnessMap.image; // required for USDZExporter, see #22741
-
- material.roughnessMap.matrixAutoUpdate = roughnessMap.matrixAutoUpdate;
- material.roughnessMap.matrix.copy( roughnessMap.matrix );
-
- _mipmapMaterial.uniforms.roughnessMap.value = roughnessMap;
-
- _mipmapMaterial.uniforms.normalMap.value = normalMap;
-
- const position = new Vector2( 0, 0 );
-
- const texelSize = _mipmapMaterial.uniforms.texelSize.value;
-
- for ( let mip = 0; width >= 1 && height >= 1; ++ mip, width /= 2, height /= 2 ) {
-
- // Rendering to a mip level is not allowed in webGL1. Instead we must set
- // up a secondary texture to write the result to, then copy it back to the
- // proper mipmap level.
-
- texelSize.set( 1.0 / width, 1.0 / height );
-
- if ( mip == 0 ) texelSize.set( 0.0, 0.0 );
-
- _tempTarget.viewport.set( position.x, position.y, width, height );
-
- _tempTarget.scissor.set( position.x, position.y, width, height );
-
- _renderer.setRenderTarget( _tempTarget );
-
- _renderer.render( _mesh, _flatCamera );
-
- _renderer.copyFramebufferToTexture( position, material.roughnessMap, mip );
-
- _mipmapMaterial.uniforms.roughnessMap.value = material.roughnessMap;
-
- }
-
- roughnessMap.dispose();
-
- _renderer.setRenderTarget( oldTarget );
-
- _renderer.autoClear = autoClear;
-
- }
-
- dispose() {
-
- _mipmapMaterial.dispose();
-
- _mesh.geometry.dispose();
-
- if ( _tempTarget != null ) _tempTarget.dispose();
-
- }
-
-}
-
-function _getMipmapMaterial() {
-
- const shaderMaterial = new RawShaderMaterial( {
-
- uniforms: {
- roughnessMap: { value: null },
- normalMap: { value: null },
- texelSize: { value: new Vector2( 1, 1 ) }
- },
-
- vertexShader: /* glsl */`
- precision mediump float;
- precision mediump int;
-
- attribute vec3 position;
- attribute vec2 uv;
-
- varying vec2 vUv;
-
- void main() {
-
- vUv = uv;
-
- gl_Position = vec4( position, 1.0 );
-
- }
- `,
-
- fragmentShader: /* glsl */`
- precision mediump float;
- precision mediump int;
-
- varying vec2 vUv;
-
- uniform sampler2D roughnessMap;
- uniform sampler2D normalMap;
- uniform vec2 texelSize;
-
- #define ENVMAP_TYPE_CUBE_UV
-
- vec4 envMapTexelToLinear( vec4 a ) { return a; }
-
- #include <cube_uv_reflection_fragment>
-
- float roughnessToVariance( float roughness ) {
-
- float variance = 0.0;
-
- if ( roughness >= r1 ) {
-
- variance = ( r0 - roughness ) * ( v1 - v0 ) / ( r0 - r1 ) + v0;
-
- } else if ( roughness >= r4 ) {
-
- variance = ( r1 - roughness ) * ( v4 - v1 ) / ( r1 - r4 ) + v1;
-
- } else if ( roughness >= r5 ) {
-
- variance = ( r4 - roughness ) * ( v5 - v4 ) / ( r4 - r5 ) + v4;
-
- } else {
-
- float roughness2 = roughness * roughness;
-
- variance = 1.79 * roughness2 * roughness2;
-
- }
-
- return variance;
-
- }
-
- float varianceToRoughness( float variance ) {
-
- float roughness = 0.0;
-
- if ( variance >= v1 ) {
-
- roughness = ( v0 - variance ) * ( r1 - r0 ) / ( v0 - v1 ) + r0;
-
- } else if ( variance >= v4 ) {
-
- roughness = ( v1 - variance ) * ( r4 - r1 ) / ( v1 - v4 ) + r1;
-
- } else if ( variance >= v5 ) {
-
- roughness = ( v4 - variance ) * ( r5 - r4 ) / ( v4 - v5 ) + r4;
-
- } else {
-
- roughness = pow( 0.559 * variance, 0.25 ); // 0.559 = 1.0 / 1.79
-
- }
-
- return roughness;
-
- }
-
- void main() {
-
- gl_FragColor = texture2D( roughnessMap, vUv, - 1.0 );
-
- if ( texelSize.x == 0.0 ) return;
-
- float roughness = gl_FragColor.g;
-
- float variance = roughnessToVariance( roughness );
-
- vec3 avgNormal;
-
- for ( float x = - 1.0; x < 2.0; x += 2.0 ) {
-
- for ( float y = - 1.0; y < 2.0; y += 2.0 ) {
-
- vec2 uv = vUv + vec2( x, y ) * 0.25 * texelSize;
-
- avgNormal += normalize( texture2D( normalMap, uv, - 1.0 ).xyz - 0.5 );
-
- }
-
- }
-
- variance += 1.0 - 0.25 * length( avgNormal );
-
- gl_FragColor.g = varianceToRoughness( variance );
-
- }
- `,
-
- blending: NoBlending,
- depthTest: false,
- depthWrite: false
-
- } );
-
- shaderMaterial.type = 'RoughnessMipmapper';
-
- return shaderMaterial;
-
-}
-
-export { RoughnessMipmapper };

examples/jsm/WebGL.js

@@ -1,91 +0,0 @@
-class WEBGL {
-
- static isWebGLAvailable() {
-
- try {
-
- const canvas = document.createElement( 'canvas' );
- return !! ( window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ) );
-
- } catch ( e ) {
-
- return false;
-
- }
-
- }
-
- static isWebGL2Available() {
-
- try {
-
- const canvas = document.createElement( 'canvas' );
- return !! ( window.WebGL2RenderingContext && canvas.getContext( 'webgl2' ) );
-
- } catch ( e ) {
-
- return false;
-
- }
-
- }
-
- static getWebGLErrorMessage() {
-
- return this.getErrorMessage( 1 );
-
- }
-
- static getWebGL2ErrorMessage() {
-
- return this.getErrorMessage( 2 );
-
- }
-
- static getErrorMessage( version ) {
-
- const names = {
- 1: 'WebGL',
- 2: 'WebGL 2'
- };
-
- const contexts = {
- 1: window.WebGLRenderingContext,
- 2: window.WebGL2RenderingContext
- };
-
- let message = 'Your $0 does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" style="color:#000">$1</a>';
-
- const element = document.createElement( 'div' );
- element.id = 'webglmessage';
- element.style.fontFamily = 'monospace';
- element.style.fontSize = '13px';
- element.style.fontWeight = 'normal';
- element.style.textAlign = 'center';
- element.style.background = '#fff';
- element.style.color = '#000';
- element.style.padding = '1.5em';
- element.style.width = '400px';
- element.style.margin = '5em auto 0';
-
- if ( contexts[ version ] ) {
-
- message = message.replace( '$0', 'graphics card' );
-
- } else {
-
- message = message.replace( '$0', 'browser' );
-
- }
-
- message = message.replace( '$1', names[ version ] );
-
- element.innerHTML = message;
-
- return element;
-
- }
-
-}
-
-export { WEBGL };

examples/jsm/webxr/VRButton.js

@@ -132,6 +132,12 @@
supported ? showEnterVR() : showWebXRNotFound();
+ if ( supported && VRButton.xrSessionIsGranted ) {
+
+ button.click();
+
+ }
+
} );
return button;
@@ -164,6 +170,24 @@
}
+ static xrSessionIsGranted = false;
+
+ static registerSessionGrantedListener() {
+
+ if ( 'xr' in navigator ) {
+
+ navigator.xr.addEventListener( 'sessiongranted', () => {
+
+ VRButton.xrSessionIsGranted = true;
+
+ } );
+
+ }
+
+ }
+
}
+VRButton.registerSessionGrantedListener();
+
export { VRButton };

examples/jsm/webxr/XREstimatedLight.js

@@ -69,6 +69,8 @@
textureProperties.__webglTexture = cubeMap;
+ this.xrLight.environment.needsPMREMUpdate = true;
+
}
}

LICENSE

@@ -1,6 +1,6 @@
The MIT License
-Copyright © 2010-2021 three.js authors
+Copyright © 2010-2022 three.js authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

package.json

@@ -1,9 +1,18 @@
{
"name": "three",
- "version": "0.136.0",
+ "version": "0.137.0",
"description": "JavaScript 3D library",
- "main": "build/three.js",
- "module": "build/three.module.js",
+ "type": "module",
+ "main": "./build/three.js",
+ "module": "./build/three.module.js",
+ "exports": {
+ ".": {
+ "import": "./build/three.module.js",
+ "require": "./build/three.cjs"
+ },
+ "./examples/jsm/*": "./examples/jsm/*.js",
+ "./src/*": "./src/*.js"
+ },
"repository": {
"type": "git",
"url": "https://github.com/mrdoob/three.js"
@@ -11,6 +20,7 @@
"sideEffects": false,
"files": [
"build/three.js",
+ "build/three.cjs",
"build/three.min.js",
"build/three.module.js",
"examples/js",
@@ -49,12 +58,15 @@
"Stats": "readonly",
"XRWebGLBinding": "readonly",
"XRWebGLLayer": "readonly",
-
"GPUShaderStage": "readonly",
"GPUBufferUsage": "readonly",
- "GPUTextureUsage": "readonly"
+ "GPUTextureUsage": "readonly",
+ "QUnit": "readonly"
},
"rules": {
+ "no-throw-literal": [
+ "error"
+ ],
"quotes": [
"error",
"single"
@@ -84,8 +96,7 @@
"test-e2e": "node test/e2e/puppeteer.js",
"test-e2e-cov": "node test/e2e/check-coverage.js",
"test-treeshake": "rollup -c test/rollup.treeshake.config.js",
- "make-screenshot": "node test/e2e/puppeteer.js --make",
- "prepublishOnly": "node utils/prepublish.js"
+ "make-screenshot": "node test/e2e/puppeteer.js --make"
},
"keywords": [
"three",
@@ -121,7 +132,6 @@
"eslint": "^7.32.0",
"eslint-config-mdcs": "^5.0.0",
"eslint-plugin-html": "^6.2.0",
- "glob": "^7.2.0",
"rollup": "^2.57.0",
"rollup-plugin-filesize": "^9.1.1",
"rollup-plugin-terser": "^7.0.2",

README.md

@@ -14,7 +14,7 @@
[Documentation](https://threejs.org/docs/) &mdash;
[Wiki](https://github.com/mrdoob/three.js/wiki) &mdash;
[Migrating](https://github.com/mrdoob/three.js/wiki/Migration-Guide) &mdash;
-[Questions](http://stackoverflow.com/questions/tagged/three.js) &mdash;
+[Questions](https://stackoverflow.com/questions/tagged/three.js) &mdash;
[Forum](https://discourse.threejs.org/) &mdash;
[Slack](https://join.slack.com/t/threejs/shared_invite/zt-rnuegz5e-FQpc6YboDVW~5idlp7GfDw) &mdash;
[Discord](https://discordapp.com/invite/HF4UdyF)

src/animation/AnimationMixer.js

@@ -48,6 +48,7 @@
if ( binding !== undefined ) {
+ ++ binding.referenceCount;
bindings[ i ] = binding;
} else {

src/cameras/CubeCamera.js

@@ -100,6 +100,8 @@
renderer.xr.enabled = currentXrEnabled;
+ renderTarget.texture.needsPMREMUpdate = true;
+
}
}

src/constants.js

@@ -1,4 +1,4 @@
-export const REVISION = '136';
+export const REVISION = '137';
export const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
export const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
export const CullFaceNone = 0;
@@ -84,10 +84,8 @@
export const HalfFloatType = 1016;
export const UnsignedShort4444Type = 1017;
export const UnsignedShort5551Type = 1018;
-export const UnsignedShort565Type = 1019;
export const UnsignedInt248Type = 1020;
export const AlphaFormat = 1021;
-export const RGBFormat = 1022;
export const RGBAFormat = 1023;
export const LuminanceFormat = 1024;
export const LuminanceAlphaFormat = 1025;
@@ -97,7 +95,6 @@
export const RedIntegerFormat = 1029;
export const RGFormat = 1030;
export const RGIntegerFormat = 1031;
-export const RGBIntegerFormat = 1032;
export const RGBAIntegerFormat = 1033;
export const RGB_S3TC_DXT1_Format = 33776;
@@ -126,20 +123,6 @@
export const RGBA_ASTC_12x10_Format = 37820;
export const RGBA_ASTC_12x12_Format = 37821;
export const RGBA_BPTC_Format = 36492;
-export const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
-export const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
-export const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
-export const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
-export const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
-export const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
-export const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
-export const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
-export const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
-export const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
-export const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
-export const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
-export const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
-export const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
export const LoopOnce = 2200;
export const LoopRepeat = 2201;
export const LoopPingPong = 2202;
@@ -191,3 +174,5 @@
export const GLSL1 = '100';
export const GLSL3 = '300 es';
+
+export const _SRGBAFormat = 1035; // fallback for WebGL 1

src/core/BufferGeometry.js

@@ -8,7 +8,7 @@
import { Matrix4 } from '../math/Matrix4.js';
import { Matrix3 } from '../math/Matrix3.js';
import * as MathUtils from '../math/MathUtils.js';
-import { arrayMax } from '../utils.js';
+import { arrayNeedsUint32 } from '../utils.js';
let _id = 0;
@@ -59,7 +59,7 @@
if ( Array.isArray( index ) ) {
- this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
+ this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
} else {

src/extras/ImageUtils.js

@@ -1,4 +1,5 @@
import { createElementNS } from '../utils.js';
+import { SRGBToLinear } from '../math/Color.js';
let _canvas;
@@ -59,6 +60,68 @@
}
+ }
+
+ 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 {
+
+ // assuming float
+
+ data[ i ] = SRGBToLinear( data[ i ] );
+
+ }
+
+ }
+
+ return {
+ data: data,
+ width: image.width,
+ height: image.height
+ };
+
+ } else {
+
+ console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
+ return image;
+
+ }
+
}
}

src/extras/PMREMGenerator.js

@@ -7,8 +7,6 @@
NoToneMapping,
NoBlending,
RGBAFormat,
- UnsignedByteType,
- sRGBEncoding,
HalfFloatType
} from '../constants.js';
@@ -42,11 +40,6 @@
// samples and exit early, but not recompile the shader.
const MAX_SAMPLES = 20;
-const ENCODINGS = {
- [ LinearEncoding ]: 0,
- [ sRGBEncoding ]: 1
-};
-
const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
const _clearColor = /*@__PURE__*/ new Color();
@@ -131,9 +124,9 @@
* or HDR. The ideal input image size is 1k (1024 x 512),
* as this matches best with the 256 x 256 cubemap output.
*/
- fromEquirectangular( equirectangular ) {
+ fromEquirectangular( equirectangular, renderTarget = null ) {
- return this._fromTexture( equirectangular );
+ return this._fromTexture( equirectangular, renderTarget );
}
@@ -142,9 +135,9 @@
* or HDR. The ideal input cube size is 256 x 256,
* as this matches best with the 256 x 256 cubemap output.
*/
- fromCubemap( cubemap ) {
+ fromCubemap( cubemap, renderTarget = null ) {
- return this._fromTexture( cubemap );
+ return this._fromTexture( cubemap, renderTarget );
}
@@ -187,6 +180,8 @@
this._blurMaterial.dispose();
+ if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
+
if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
if ( this._equirectShader !== null ) this._equirectShader.dispose();
@@ -202,17 +197,16 @@
_cleanup( outputTarget ) {
- this._pingPongRenderTarget.dispose();
this._renderer.setRenderTarget( _oldTarget );
outputTarget.scissorTest = false;
_setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
}
- _fromTexture( texture ) {
+ _fromTexture( texture, renderTarget ) {
_oldTarget = this._renderer.getRenderTarget();
- const cubeUVRenderTarget = this._allocateTargets( texture );
+ const cubeUVRenderTarget = renderTarget || this._allocateTargets( texture );
this._textureToCubeUV( texture, cubeUVRenderTarget );
this._applyPMREM( cubeUVRenderTarget );
this._cleanup( cubeUVRenderTarget );
@@ -235,7 +229,13 @@
const cubeUVRenderTarget = _createRenderTarget( params );
cubeUVRenderTarget.depthBuffer = texture ? false : true;
+
+ if ( this._pingPongRenderTarget === null ) {
+
this._pingPongRenderTarget = _createRenderTarget( params );
+
+ }
+
return cubeUVRenderTarget;
}
@@ -295,12 +295,12 @@
for ( let i = 0; i < 6; i ++ ) {
const col = i % 3;
- if ( col == 0 ) {
+ if ( col === 0 ) {
cubeCamera.up.set( 0, upSign[ i ], 0 );
cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
- } else if ( col == 1 ) {
+ } else if ( col === 1 ) {
cubeCamera.up.set( 0, 0, upSign[ i ] );
cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
@@ -335,20 +335,6 @@
}
- _setEncoding( uniform, texture ) {
-
- if ( this._renderer.capabilities.isWebGL2 === true && texture.format === RGBAFormat && texture.type === UnsignedByteType && texture.encoding === sRGBEncoding ) {
-
- uniform.value = ENCODINGS[ LinearEncoding ];
-
- } else {
-
- uniform.value = ENCODINGS[ texture.encoding ];
-
- }
-
- }
-
_textureToCubeUV( texture, cubeUVRenderTarget ) {
const renderer = this._renderer;
@@ -357,15 +343,17 @@
if ( isCubeTexture ) {
- if ( this._cubemapShader == null ) {
+ if ( this._cubemapShader === null ) {
this._cubemapShader = _getCubemapShader();
}
+ this._cubemapShader.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
+
} else {
- if ( this._equirectShader == null ) {
+ if ( this._equirectShader === null ) {
this._equirectShader = _getEquirectShader();
@@ -386,8 +374,6 @@
}
- this._setEncoding( uniforms[ 'inputEncoding' ], texture );
-
_setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
renderer.setRenderTarget( cubeUVRenderTarget );
@@ -486,7 +472,7 @@
const weight = Math.exp( - x * x / 2 );
weights.push( weight );
- if ( i == 0 ) {
+ if ( i === 0 ) {
sum += weight;
@@ -548,7 +534,7 @@
sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
- } else if ( i == 0 ) {
+ } else if ( i === 0 ) {
sigma = 0;
@@ -662,8 +648,6 @@
uniform float mipInt;
uniform vec3 poleAxis;
- ${ _getEncodings() }
-
#define ENVMAP_TYPE_CUBE_UV
#include <cube_uv_reflection_fragment>
@@ -730,8 +714,7 @@
uniforms: {
'envMap': { value: null },
- 'texelSize': { value: texelSize },
- 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }
+ 'texelSize': { value: texelSize }
},
vertexShader: _getCommonVertexShader(),
@@ -746,8 +729,6 @@
uniform sampler2D envMap;
uniform vec2 texelSize;
- ${ _getEncodings() }
-
#include <common>
void main() {
@@ -759,13 +740,13 @@
vec2 f = fract( uv / texelSize - 0.5 );
uv -= f * texelSize;
- vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
+ vec3 tl = texture2D ( envMap, uv ).rgb;
uv.x += texelSize.x;
- vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
+ vec3 tr = texture2D ( envMap, uv ).rgb;
uv.y += texelSize.y;
- vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
+ vec3 br = texture2D ( envMap, uv ).rgb;
uv.x -= texelSize.x;
- vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
+ vec3 bl = texture2D ( envMap, uv ).rgb;
vec3 tm = mix( tl, tr, f.x );
vec3 bm = mix( bl, br, f.x );
@@ -792,7 +773,7 @@
uniforms: {
'envMap': { value: null },
- 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }
+ 'flipEnvMap': { value: - 1 }
},
vertexShader: _getCommonVertexShader(),
@@ -802,15 +783,15 @@
precision mediump float;
precision mediump int;
+ uniform float flipEnvMap;
+
varying vec3 vOutputDirection;
uniform samplerCube envMap;
- ${ _getEncodings() }
-
void main() {
- gl_FragColor = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) );
+ gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
}
`,
@@ -885,37 +866,6 @@
}
`;
-
-}
-
-function _getEncodings() {
-
- return /* glsl */`
-
- uniform int inputEncoding;
-
- #include <encodings_pars_fragment>
-
- vec4 inputTexelToLinear( vec4 value ) {
-
- if ( inputEncoding == 0 ) {
-
- return value;
-
- } else {
-
- return sRGBToLinear( value );
-
- }
-
- }
-
- vec4 envMapTexelToLinear( vec4 color ) {
-
- return inputTexelToLinear( color );
-
- }
- `;
}

src/geometries/LatheGeometry.js

@@ -152,7 +152,7 @@
// faces
indices.push( a, b, d );
- indices.push( b, c, d );
+ indices.push( c, d, b );
}

src/loaders/FileLoader.js

@@ -69,6 +69,10 @@
// An abort controller could be added within a future PR
} );
+ // record states ( avoid data race )
+ const mimeType = this.mimeType;
+ const responseType = this.responseType;
+
// start the fetch
fetch( req )
.then( response => {
@@ -147,7 +151,7 @@
} )
.then( response => {
- switch ( this.responseType ) {
+ switch ( responseType ) {
case 'arraybuffer':
@@ -163,7 +167,7 @@
.then( text => {
const parser = new DOMParser();
- return parser.parseFromString( text, this.mimeType );
+ return parser.parseFromString( text, mimeType );
} );
@@ -173,8 +177,21 @@
default:
+ if ( mimeType === undefined ) {
+
return response.text();
+ } else {
+
+ // sniff encoding
+ const re = /charset="?([^;"\s]*)"?/i;
+ const exec = re.exec( mimeType );
+ const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
+ const decoder = new TextDecoder( label );
+ return response.arrayBuffer().then( ab => decoder.decode( ab ) );
+
+ }
+
}
} )

src/loaders/MaterialLoader.js

@@ -95,12 +95,12 @@
if ( json.side !== undefined ) material.side = json.side;
if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
if ( json.opacity !== undefined ) material.opacity = json.opacity;
- if ( json.format !== undefined ) material.format = json.format;
if ( json.transparent !== undefined ) material.transparent = json.transparent;
if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
+ if ( json.alphaWrite !== undefined ) material.alphaWrite = json.alphaWrite;
if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;

src/materials/Material.js

@@ -1,5 +1,5 @@
import { EventDispatcher } from '../core/EventDispatcher.js';
-import { FrontSide, FlatShading, NormalBlending, LessEqualDepth, AddEquation, OneMinusSrcAlphaFactor, SrcAlphaFactor, AlwaysStencilFunc, KeepStencilOp, RGBAFormat } from '../constants.js';
+import { FrontSide, FlatShading, NormalBlending, LessEqualDepth, AddEquation, OneMinusSrcAlphaFactor, SrcAlphaFactor, AlwaysStencilFunc, KeepStencilOp } from '../constants.js';
import * as MathUtils from '../math/MathUtils.js';
let materialId = 0;
@@ -24,7 +24,6 @@
this.vertexColors = false;
this.opacity = 1;
- this.format = RGBAFormat;
this.transparent = false;
this.blendSrc = SrcAlphaFactor;
@@ -54,6 +53,7 @@
this.shadowSide = null;
this.colorWrite = true;
+ this.alphaWrite = true;
this.precision = null; // override the renderer's default precision for this material
@@ -306,13 +306,13 @@
if ( this.vertexColors ) data.vertexColors = true;
if ( this.opacity < 1 ) data.opacity = this.opacity;
- if ( this.format !== RGBAFormat ) data.format = this.format;
if ( this.transparent === true ) data.transparent = this.transparent;
data.depthFunc = this.depthFunc;
data.depthTest = this.depthTest;
data.depthWrite = this.depthWrite;
data.colorWrite = this.colorWrite;
+ data.alphaWrite = this.alphaWrite;
data.stencilWrite = this.stencilWrite;
data.stencilWriteMask = this.stencilWriteMask;
@@ -403,7 +403,6 @@
this.vertexColors = source.vertexColors;
this.opacity = source.opacity;
- this.format = source.format;
this.transparent = source.transparent;
this.blendSrc = source.blendSrc;
@@ -449,6 +448,7 @@
this.shadowSide = source.shadowSide;
this.colorWrite = source.colorWrite;
+ this.alphaWrite = source.alphaWrite;
this.precision = source.precision;

src/math/Box3.js

@@ -109,11 +109,11 @@
}
- setFromObject( object ) {
+ setFromObject( object, precise = false ) {
this.makeEmpty();
- return this.expandByObject( object );
+ return this.expandByObject( object, precise );
}
@@ -188,7 +188,7 @@
}
- expandByObject( object ) {
+ expandByObject( object, precise = false ) {
// Computes the world-axis-aligned bounding box of an object (including its children),
// accounting for both the object's, and children's, world transforms
@@ -199,6 +199,18 @@
if ( geometry !== undefined ) {
+ if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
+
+ const position = geometry.attributes.position;
+ for ( let i = 0, l = position.count; i < l; i ++ ) {
+
+ _vector.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
+ this.expandByPoint( _vector );
+
+ }
+
+ } else {
+
if ( geometry.boundingBox === null ) {
geometry.computeBoundingBox();
@@ -212,11 +224,13 @@
}
+ }
+
const children = object.children;
for ( let i = 0, l = children.length; i < l; i ++ ) {
- this.expandByObject( children[ i ] );
+ this.expandByObject( children[ i ], precise );
}

src/math/Color.js

@@ -563,4 +563,4 @@
Color.prototype.g = 1;
Color.prototype.b = 1;
-export { Color };
+export { Color, SRGBToLinear };

src/math/Quaternion.js

@@ -604,7 +604,7 @@
slerpQuaternions( qa, qb, t ) {
- this.copy( qa ).slerp( qb, t );
+ return this.copy( qa ).slerp( qb, t );
}

src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl.js

@@ -3,8 +3,6 @@
vec4 emissiveColor = texture2D( emissiveMap, vUv );
- emissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;
-
totalEmissiveRadiance *= emissiveColor.rgb;
#endif

src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl.js

@@ -4,10 +4,6 @@
return value;
}
-vec4 sRGBToLinear( 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 LinearTosRGB( 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 );
}

src/renderers/shaders/ShaderChunk/envmap_fragment.glsl.js

@@ -38,8 +38,6 @@
vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
- envColor = envMapTexelToLinear( envColor );
-
#elif defined( ENVMAP_TYPE_CUBE_UV )
vec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );

src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl.js

@@ -2,7 +2,7 @@
#ifdef USE_LIGHTMAP
vec4 lightMapTexel = texture2D( lightMap, vUv2 );
- vec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;
+ vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
#ifndef PHYSICALLY_CORRECT_LIGHTS

src/renderers/shaders/ShaderChunk/lights_fragment_maps.glsl.js

@@ -4,7 +4,7 @@
#ifdef USE_LIGHTMAP
vec4 lightMapTexel = texture2D( lightMap, vUv2 );
- vec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;
+ vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
#ifndef PHYSICALLY_CORRECT_LIGHTS

src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl.js

@@ -24,7 +24,7 @@
#ifdef USE_SPECULARCOLORMAP
- specularColorFactor *= specularColorMapTexelToLinear( texture2D( specularColorMap, vUv ) ).rgb;
+ specularColorFactor *= texture2D( specularColorMap, vUv ).rgb;
#endif
@@ -79,7 +79,7 @@
#ifdef USE_SHEENCOLORMAP
- material.sheenColor *= sheenColorMapTexelToLinear( texture2D( sheenColorMap, vUv ) ).rgb;
+ material.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;
#endif

src/renderers/shaders/ShaderChunk/map_fragment.glsl.js

@@ -1,10 +1,17 @@
export default /* glsl */`
#ifdef USE_MAP
- vec4 texelColor = texture2D( map, vUv );
+ vec4 sampledDiffuseColor = texture2D( map, vUv );
- texelColor = mapTexelToLinear( texelColor );
- diffuseColor *= texelColor;
+ #ifdef DECODE_VIDEO_TEXTURE
+
+ // inline sRGB decode (TODO: Remove this code when https://crbug.com/1256340 is solved)
+
+ sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );
+
+ #endif
+
+ diffuseColor *= sampledDiffuseColor;
#endif
`;

src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl.js

@@ -7,8 +7,7 @@
#ifdef USE_MAP
- vec4 mapTexel = texture2D( map, uv );
- diffuseColor *= mapTexelToLinear( mapTexel );
+ diffuseColor *= texture2D( map, uv );
#endif

src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl.js

@@ -10,7 +10,7 @@
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
- if ( morphTargetInfluences[ i ] > 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];
+ if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];
}

src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl.js

@@ -12,11 +12,11 @@
#ifndef USE_MORPHNORMALS
- if ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];
+ if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];
#else
- if ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];
+ if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];
#endif

src/renderers/shaders/ShaderChunk/transmission_pars_fragment.glsl.js

@@ -29,7 +29,7 @@
varying vec3 vWorldPosition;
- vec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {
+ vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
// Direction of refracted light.
vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
@@ -45,7 +45,7 @@
}
- float applyIorToRoughness( float roughness, float ior ) {
+ float applyIorToRoughness( const in float roughness, const in float ior ) {
// Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
// an IOR of 1.5 results in the default amount of microfacet refraction.
@@ -53,7 +53,7 @@
}
- vec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {
+ vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
float framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
@@ -69,7 +69,7 @@
}
- vec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {
+ vec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
if ( attenuationDistance == 0.0 ) {
@@ -87,9 +87,10 @@
}
- vec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,
- vec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,
- vec3 attenuationColor, float attenuationDistance ) {
+ 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 ior, const in float thickness,
+ const in vec3 attenuationColor, const in float attenuationDistance ) {
vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
vec3 refractedRayExit = position + transmissionRay;

src/renderers/shaders/ShaderLib/background.glsl.js

@@ -18,9 +18,7 @@
void main() {
- vec4 texColor = texture2D( t2D, vUv );
-
- gl_FragColor = mapTexelToLinear( texColor );
+ gl_FragColor = texture2D( t2D, vUv );
#include <tonemapping_fragment>
#include <encodings_fragment>

src/renderers/shaders/ShaderLib/equirect.glsl.js

@@ -26,9 +26,7 @@
vec2 sampleUV = equirectUv( direction );
- vec4 texColor = texture2D( tEquirect, sampleUV );
-
- gl_FragColor = mapTexelToLinear( texColor );
+ gl_FragColor = texture2D( tEquirect, sampleUV );
#include <tonemapping_fragment>
#include <encodings_fragment>

src/renderers/shaders/ShaderLib/meshbasic.glsl.js

@@ -87,7 +87,7 @@
#ifdef USE_LIGHTMAP
vec4 lightMapTexel= texture2D( lightMap, vUv2 );
- reflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;
+ reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity;
#else

src/renderers/shaders/ShaderLib/meshmatcap.glsl.js

@@ -86,11 +86,10 @@
#ifdef USE_MATCAP
vec4 matcapColor = texture2D( matcap, uv );
- matcapColor = matcapTexelToLinear( matcapColor );
#else
- vec4 matcapColor = vec4( 1.0 );
+ vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); // default if matcap is missing
#endif

src/renderers/shaders/ShaderLib.js

@@ -299,7 +299,7 @@
sheen: { value: 0 },
sheenColor: { value: new Color( 0x000000 ) },
sheenColorMap: { value: null },
- sheenRoughness: { value: 0 },
+ sheenRoughness: { value: 1 },
sheenRoughnessMap: { value: null },
transmission: { value: 0 },
transmissionMap: { value: null },
@@ -309,7 +309,7 @@
thicknessMap: { value: null },
attenuationDistance: { value: 0 },
attenuationColor: { value: new Color( 0x000000 ) },
- specularIntensity: { value: 0 },
+ specularIntensity: { value: 1 },
specularIntensityMap: { value: null },
specularColor: { value: new Color( 1, 1, 1 ) },
specularColorMap: { value: null },

src/renderers/webgl/WebGLBackground.js

@@ -7,10 +7,10 @@
import { ShaderLib } from '../shaders/ShaderLib.js';
import { cloneUniforms } from '../shaders/UniformsUtils.js';
-function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
+function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipliedAlpha ) {
const clearColor = new Color( 0x000000 );
- let clearAlpha = 0;
+ let clearAlpha = alpha === true ? 0 : 1;
let planeMesh;
let boxMesh;

src/renderers/webgl/WebGLCubeMaps.js

@@ -40,14 +40,10 @@
if ( image && image.height > 0 ) {
- const currentRenderTarget = renderer.getRenderTarget();
-
const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
renderTarget.fromEquirectangularTexture( renderer, texture );
cubemaps.set( texture, renderTarget );
- renderer.setRenderTarget( currentRenderTarget );
-
texture.addEventListener( 'dispose', onTextureDispose );
return mapTextureMapping( renderTarget.texture, texture.mapping );

src/renderers/webgl/WebGLCubeUVMaps.js

@@ -9,16 +9,31 @@
function get( texture ) {
- if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
+ if ( texture && texture.isTexture ) {
const mapping = texture.mapping;
const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
+ // equirect/cube map to cubeUV conversion
+
if ( isEquirectMap || isCubeMap ) {
- // equirect/cube map to cubeUV conversion
+ if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
+
+ texture.needsPMREMUpdate = false;
+
+ let renderTarget = cubeUVmaps.get( texture );
+
+ if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
+
+ renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
+ cubeUVmaps.set( texture, renderTarget );
+
+ return renderTarget.texture;
+
+ } else {
if ( cubeUVmaps.has( texture ) ) {
@@ -30,15 +45,11 @@
if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
- const currentRenderTarget = renderer.getRenderTarget();
-
if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
cubeUVmaps.set( texture, renderTarget );
- renderer.setRenderTarget( currentRenderTarget );
-
texture.addEventListener( 'dispose', onTextureDispose );
return renderTarget.texture;
@@ -51,6 +62,8 @@
}
+ }
+
}
}

src/renderers/webgl/WebGLGeometries.js

@@ -1,5 +1,5 @@
import { Uint16BufferAttribute, Uint32BufferAttribute } from '../../core/BufferAttribute.js';
-import { arrayMax } from '../../utils.js';
+import { arrayNeedsUint32 } from '../../utils.js';
function WebGLGeometries( gl, attributes, info, bindingStates ) {
@@ -133,7 +133,7 @@
}
- const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
+ const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
attribute.version = version;
// Updating index buffer in VAO now. See WebGLBindingStates

src/renderers/webgl/WebGLMorphtargets.js

@@ -135,6 +135,18 @@
morphTextures.set( geometry, entry );
+ function disposeTexture() {
+
+ texture.dispose();
+
+ morphTextures.delete( geometry );
+
+ geometry.removeEventListener( 'dispose', disposeTexture );
+
+ }
+
+ geometry.addEventListener( 'dispose', disposeTexture );
+
}
//

src/renderers/webgl/WebGLProgram.js

@@ -1,7 +1,7 @@
import { WebGLUniforms } from './WebGLUniforms.js';
import { WebGLShader } from './WebGLShader.js';
import { ShaderChunk } from '../shaders/ShaderChunk.js';
-import { RGBFormat, NoToneMapping, AddOperation, MixOperation, MultiplyOperation, CubeRefractionMapping, CubeUVRefractionMapping, CubeUVReflectionMapping, CubeReflectionMapping, PCFSoftShadowMap, PCFShadowMap, VSMShadowMap, ACESFilmicToneMapping, CineonToneMapping, CustomToneMapping, ReinhardToneMapping, LinearToneMapping, sRGBEncoding, LinearEncoding, GLSL3 } from '../../constants.js';
+import { NoToneMapping, AddOperation, MixOperation, MultiplyOperation, CubeRefractionMapping, CubeUVRefractionMapping, CubeUVReflectionMapping, CubeReflectionMapping, PCFSoftShadowMap, PCFShadowMap, VSMShadowMap, ACESFilmicToneMapping, CineonToneMapping, CustomToneMapping, ReinhardToneMapping, LinearToneMapping, sRGBEncoding, LinearEncoding, GLSL3 } from '../../constants.js';
let programIdCount = 0;
@@ -49,13 +49,6 @@
}
-function getTexelDecodingFunction( functionName, encoding ) {
-
- const components = getEncodingComponents( encoding );
- return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
-
-}
-
function getTexelEncodingFunction( functionName, encoding ) {
const components = getEncodingComponents( encoding );
@@ -625,6 +618,8 @@
parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
+ parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
+
parameters.vertexTangents ? '#define USE_TANGENT' : '',
parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
@@ -659,16 +654,9 @@
( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
parameters.dithering ? '#define DITHERING' : '',
- parameters.format === RGBFormat ? '#define OPAQUE' : '',
+ parameters.alphaWrite ? '' : '#define OPAQUE',
ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
- parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
- parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
- parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
- parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
- parameters.specularColorMap ? getTexelDecodingFunction( 'specularColorMapTexelToLinear', parameters.specularColorMapEncoding ) : '',
- parameters.sheenColorMap ? getTexelDecodingFunction( 'sheenColorMapTexelToLinear', parameters.sheenColorMapEncoding ) : '',
- parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',

src/renderers/webgl/WebGLPrograms.js

@@ -1,4 +1,4 @@
-import { BackSide, DoubleSide, CubeUVRefractionMapping, CubeUVReflectionMapping, LinearEncoding, sRGBEncoding, ObjectSpaceNormalMap, TangentSpaceNormalMap, NoToneMapping, RGBAFormat, UnsignedByteType } from '../../constants.js';
+import { BackSide, DoubleSide, CubeUVRefractionMapping, CubeUVReflectionMapping, ObjectSpaceNormalMap, TangentSpaceNormalMap, NoToneMapping, LinearEncoding, sRGBEncoding } from '../../constants.js';
import { Layers } from '../../core/Layers.js';
import { WebGLProgram } from './WebGLProgram.js';
import { WebGLShaderCache } from './WebGLShaderCache.js';
@@ -72,35 +72,6 @@
}
- function getTextureEncodingFromMap( map ) {
-
- let encoding;
-
- if ( map && map.isTexture ) {
-
- encoding = map.encoding;
-
- } else if ( map && map.isWebGLRenderTarget ) {
-
- console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
- encoding = map.texture.encoding;
-
- } else {
-
- encoding = LinearEncoding;
-
- }
-
- if ( isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding ) {
-
- encoding = LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
-
- }
-
- return encoding;
-
- }
-
function getParameters( material, lights, shadows, scene, object ) {
const fog = scene.fog;
@@ -177,25 +148,22 @@
instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
supportsVertexTextures: vertexTextures,
- outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
+ outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
map: !! material.map,
- mapEncoding: getTextureEncodingFromMap( material.map ),
matcap: !! material.matcap,
- matcapEncoding: getTextureEncodingFromMap( material.matcap ),
envMap: !! envMap,
envMapMode: envMap && envMap.mapping,
- envMapEncoding: getTextureEncodingFromMap( envMap ),
envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
lightMap: !! material.lightMap,
- lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
aoMap: !! material.aoMap,
emissiveMap: !! material.emissiveMap,
- emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
bumpMap: !! material.bumpMap,
normalMap: !! material.normalMap,
objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
+ decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
+
clearcoat: useClearcoat,
clearcoatMap: useClearcoat && !! material.clearcoatMap,
clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
@@ -207,16 +175,15 @@
specularMap: !! material.specularMap,
specularIntensityMap: !! material.specularIntensityMap,
specularColorMap: !! material.specularColorMap,
- specularColorMapEncoding: getTextureEncodingFromMap( material.specularColorMap ),
alphaMap: !! material.alphaMap,
alphaTest: useAlphaTest,
+ alphaWrite: material.alphaWrite || material.transparent,
gradientMap: !! material.gradientMap,
sheen: material.sheen > 0,
sheenColorMap: !! material.sheenColorMap,
- sheenColorMapEncoding: getTextureEncodingFromMap( material.sheenColorMap ),
sheenRoughnessMap: !! material.sheenRoughnessMap,
transmission: material.transmission > 0,
@@ -261,7 +228,6 @@
numClippingPlanes: clipping.numPlanes,
numClipIntersection: clipping.numIntersection,
- format: material.format,
dithering: material.dithering,
shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
@@ -340,12 +306,7 @@
array.push( parameters.precision );
array.push( parameters.outputEncoding );
- array.push( parameters.mapEncoding );
- array.push( parameters.matcapEncoding );
array.push( parameters.envMapMode );
- array.push( parameters.envMapEncoding );
- array.push( parameters.lightMapEncoding );
- array.push( parameters.emissiveMapEncoding );
array.push( parameters.combine );
array.push( parameters.vertexUvs );
array.push( parameters.fogExp2 );
@@ -364,9 +325,7 @@
array.push( parameters.toneMapping );
array.push( parameters.numClippingPlanes );
array.push( parameters.numClipIntersection );
- array.push( parameters.format );
- array.push( parameters.specularColorMapEncoding );
- array.push( parameters.sheenColorMapEncoding );
+ array.push( parameters.alphaWrite );
}
@@ -486,6 +445,8 @@
_programLayers.enable( 20 );
if ( parameters.sheenRoughnessMap )
_programLayers.enable( 21 );
+ if ( parameters.decodeVideoTexture )
+ _programLayers.enable( 22 );
array.push( _programLayers.mask );

src/renderers/webgl/WebGLState.js

@@ -317,6 +317,8 @@
let enabledCapabilities = {};
let currentBoundFramebuffers = {};
+ let currentDrawbuffers = new WeakMap();
+ let defaultDrawbuffers = [];
let currentProgram = null;
@@ -461,6 +463,82 @@
}
+ function drawBuffers( renderTarget, framebuffer ) {
+
+ let drawBuffers = defaultDrawbuffers;
+
+ let needsUpdate = false;
+
+ if ( renderTarget ) {
+
+ drawBuffers = currentDrawbuffers.get( framebuffer );
+
+ if ( drawBuffers === undefined ) {
+
+ drawBuffers = [];
+ currentDrawbuffers.set( framebuffer, drawBuffers );
+
+ }
+
+ if ( renderTarget.isWebGLMultipleRenderTargets ) {
+
+ const textures = renderTarget.texture;
+
+ if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
+
+ for ( let i = 0, il = textures.length; i < il; i ++ ) {
+
+ drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
+
+ }
+
+ drawBuffers.length = textures.length;
+
+ needsUpdate = true;
+
+ }
+
+ } else {
+
+ if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
+
+ drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0;
+
+ needsUpdate = true;
+
+ }
+
+ }
+
+ } else {
+
+ if ( drawBuffers[ 0 ] !== gl.BACK ) {
+
+ drawBuffers[ 0 ] = gl.BACK;
+
+ needsUpdate = true;
+
+ }
+
+ }
+
+ if ( needsUpdate ) {
+
+ if ( capabilities.isWebGL2 ) {
+
+ gl.drawBuffers( drawBuffers );
+
+ } else {
+
+ extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
+
+ }
+
+ }
+
+
+ }
+
function useProgram( program ) {
if ( currentProgram !== program ) {
@@ -563,7 +641,7 @@
break;
case SubtractiveBlending:
- gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
+ gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
break;
case MultiplyBlending:
@@ -589,7 +667,7 @@
break;
case SubtractiveBlending:
- gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
+ gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
break;
case MultiplyBlending:
@@ -1047,6 +1125,8 @@
currentBoundTextures = {};
currentBoundFramebuffers = {};
+ currentDrawbuffers = new WeakMap();
+ defaultDrawbuffers = [];
currentProgram = null;
@@ -1089,6 +1169,7 @@
disable: disable,
bindFramebuffer: bindFramebuffer,
+ drawBuffers: drawBuffers,
useProgram: useProgram,

src/renderers/webgl/WebGLTextures.js

@@ -1,5 +1,6 @@
-import { LinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, RGBFormat, RGBAFormat, DepthFormat, DepthStencilFormat, UnsignedShortType, UnsignedIntType, UnsignedInt248Type, FloatType, HalfFloatType, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, sRGBEncoding } from '../../constants.js';
+import { LinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, RGBAFormat, DepthFormat, DepthStencilFormat, UnsignedShortType, UnsignedIntType, UnsignedInt248Type, FloatType, HalfFloatType, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, sRGBEncoding, LinearEncoding, UnsignedByteType, _SRGBAFormat } from '../../constants.js';
import * as MathUtils from '../../math/MathUtils.js';
+import { ImageUtils } from '../../extras/ImageUtils.js';
import { createElementNS } from '../../utils.js';
function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
@@ -130,7 +131,7 @@
}
- function getInternalFormat( internalFormatName, glFormat, glType, encoding ) {
+ function getInternalFormat( internalFormatName, glFormat, glType, encoding, isVideoTexture = false ) {
if ( isWebGL2 === false ) return glFormat;
@@ -152,11 +153,11 @@
}
- if ( glFormat === _gl.RGB ) {
+ if ( glFormat === _gl.RG ) {
- if ( glType === _gl.FLOAT ) internalFormat = _gl.RGB32F;
- if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGB16F;
- if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8;
+ if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
+ if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
+ if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
}
@@ -164,11 +165,14 @@
if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
- if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( encoding === sRGBEncoding ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
+ if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( encoding === sRGBEncoding && isVideoTexture === false ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
+ 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' );
@@ -550,13 +554,14 @@
_gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
- const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
+ let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
+ image = verifyColorSpace( texture, image );
const supportsMips = isPowerOfTwo( image ) || isWebGL2,
- glFormat = utils.convert( texture.format );
+ glFormat = utils.convert( texture.format, texture.encoding );
let glType = utils.convert( texture.type ),
- glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
+ glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
setTextureParameters( textureType, texture, supportsMips );
@@ -717,7 +722,7 @@
mipmap = mipmaps[ i ];
- if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
+ if ( texture.format !== RGBAFormat ) {
if ( glFormat !== null ) {
@@ -900,11 +905,13 @@
}
+ cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
+
}
const image = cubeImage[ 0 ],
supportsMips = isPowerOfTwo( image ) || isWebGL2,
- glFormat = utils.convert( texture.format ),
+ glFormat = utils.convert( texture.format, texture.encoding ),
glType = utils.convert( texture.type ),
glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
@@ -932,7 +939,7 @@
const mipmap = mipmaps[ j ];
- if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
+ if ( texture.format !== RGBAFormat ) {
if ( glFormat !== null ) {
@@ -1069,7 +1076,7 @@
// Setup storage for target texture and bind it to correct framebuffer
function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
- const glFormat = utils.convert( texture.format );
+ const glFormat = utils.convert( texture.format, texture.encoding );
const glType = utils.convert( texture.type );
const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
const renderTargetProperties = properties.get( renderTarget );
@@ -1177,7 +1184,7 @@
// Use the first texture for MRT so far
const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture;
- const glFormat = utils.convert( texture.format );
+ const glFormat = utils.convert( texture.format, texture.encoding );
const glType = utils.convert( texture.type );
const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
const samples = getRenderTargetSamples( renderTarget );
@@ -1351,16 +1358,6 @@
const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
- // Handles WebGL2 RGBFormat fallback - #18858
-
- if ( isWebGL2 && texture.format === RGBFormat && ( texture.type === FloatType || texture.type === HalfFloatType ) ) {
-
- texture.format = RGBAFormat;
-
- console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
-
- }
-
// Setup framebuffer
if ( isCube ) {
@@ -1412,7 +1409,7 @@
_gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer );
- const glFormat = utils.convert( texture.format );
+ const glFormat = utils.convert( texture.format, texture.encoding );
const glType = utils.convert( texture.type );
const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
const samples = getRenderTargetSamples( renderTarget );
@@ -1631,6 +1628,65 @@
}
+ function verifyColorSpace( texture, image ) {
+
+ const encoding = texture.encoding;
+ const format = texture.format;
+ const type = texture.type;
+
+ if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
+
+ if ( encoding !== LinearEncoding ) {
+
+ // sRGB
+
+ if ( encoding === sRGBEncoding ) {
+
+ if ( isWebGL2 === false ) {
+
+ // in WebGL 1, try to use EXT_sRGB extension and unsized formats
+
+ if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
+
+ texture.format = _SRGBAFormat;
+
+ // it's not possible to generate mips in WebGL 1 with this extension
+
+ texture.minFilter = LinearFilter;
+ texture.generateMipmaps = false;
+
+ } else {
+
+ // slow fallback (CPU decode)
+
+ image = ImageUtils.sRGBToLinear( image );
+
+ }
+
+ } else {
+
+ // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
+
+ if ( format !== RGBAFormat || type !== UnsignedByteType ) {
+
+ console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
+
+ }
+
+ }
+
+ } else {
+
+ console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
+
+ }
+
+ }
+
+ return image;
+
+ }
+
// backwards compatibility
let warnedTexture2D = false;

src/renderers/webgl/WebGLUtils.js

@@ -1,17 +1,16 @@
-import { RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT5_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT1_Format, RGB_S3TC_DXT1_Format, DepthFormat, DepthStencilFormat, LuminanceAlphaFormat, LuminanceFormat, RedFormat, RGBAFormat, RGBFormat, AlphaFormat, RedIntegerFormat, RGFormat, RGIntegerFormat, RGBIntegerFormat, RGBAIntegerFormat, HalfFloatType, FloatType, UnsignedIntType, IntType, UnsignedShortType, ShortType, ByteType, UnsignedInt248Type, UnsignedShort565Type, UnsignedShort5551Type, UnsignedShort4444Type, UnsignedByteType, SRGB8_ALPHA8_ASTC_4x4_Format, SRGB8_ALPHA8_ASTC_5x4_Format, SRGB8_ALPHA8_ASTC_5x5_Format, SRGB8_ALPHA8_ASTC_6x5_Format, SRGB8_ALPHA8_ASTC_6x6_Format, SRGB8_ALPHA8_ASTC_8x5_Format, SRGB8_ALPHA8_ASTC_8x6_Format, SRGB8_ALPHA8_ASTC_8x8_Format, SRGB8_ALPHA8_ASTC_10x5_Format, SRGB8_ALPHA8_ASTC_10x6_Format, SRGB8_ALPHA8_ASTC_10x8_Format, SRGB8_ALPHA8_ASTC_10x10_Format, SRGB8_ALPHA8_ASTC_12x10_Format, SRGB8_ALPHA8_ASTC_12x12_Format, RGBA_BPTC_Format } from '../../constants.js';
+import { RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT5_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT1_Format, RGB_S3TC_DXT1_Format, DepthFormat, DepthStencilFormat, LuminanceAlphaFormat, LuminanceFormat, RedFormat, RGBAFormat, AlphaFormat, RedIntegerFormat, RGFormat, RGIntegerFormat, RGBAIntegerFormat, HalfFloatType, FloatType, UnsignedIntType, IntType, UnsignedShortType, ShortType, ByteType, UnsignedInt248Type, UnsignedShort5551Type, UnsignedShort4444Type, UnsignedByteType, RGBA_BPTC_Format, sRGBEncoding, _SRGBAFormat } from '../../constants.js';
function WebGLUtils( gl, extensions, capabilities ) {
const isWebGL2 = capabilities.isWebGL2;
- function convert( p ) {
+ function convert( p, encoding = null ) {
let extension;
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 === UnsignedShort565Type ) return gl.UNSIGNED_SHORT_5_6_5;
if ( p === ByteType ) return gl.BYTE;
if ( p === ShortType ) return gl.SHORT;
@@ -39,7 +38,6 @@
}
if ( p === AlphaFormat ) return gl.ALPHA;
- if ( p === RGBFormat ) return gl.RGB;
if ( p === RGBAFormat ) return gl.RGBA;
if ( p === LuminanceFormat ) return gl.LUMINANCE;
if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
@@ -47,16 +45,53 @@
if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
if ( p === RedFormat ) return gl.RED;
+ // WebGL 1 sRGB fallback
+
+ if ( p === _SRGBAFormat ) {
+
+ extension = extensions.get( 'EXT_sRGB' );
+
+ if ( extension !== null ) {
+
+ return extension.SRGB_ALPHA_EXT;
+
+ } else {
+
+ return null;
+
+ }
+
+ }
+
// WebGL2 formats.
if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
if ( p === RGFormat ) return gl.RG;
if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
- if ( p === RGBIntegerFormat ) return gl.RGB_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 ) {
+ // S3TC
+
+ if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
+
+ if ( encoding === sRGBEncoding ) {
+
+ 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' );
@@ -75,8 +110,11 @@
}
- if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
- p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
+ }
+
+ // PVRTC
+
+ 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' );
@@ -95,6 +133,8 @@
}
+ // ETC1
+
if ( p === RGB_ETC1_Format ) {
extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
@@ -111,37 +151,51 @@
}
+ // ETC2
+
if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
extension = extensions.get( 'WEBGL_compressed_texture_etc' );
if ( extension !== null ) {
- if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
- if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
+ if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
+ if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
+
+ } else {
+
+ return null;
}
}
+ // ASTC
+
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 ||
- p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
- p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
- p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
- p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
- p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
+ p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
extension = extensions.get( 'WEBGL_compressed_texture_astc' );
if ( extension !== null ) {
- // TODO Complete?
-
- return p;
+ if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
+ if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
+ if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
+ if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
+ if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
+ if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
+ if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
+ if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
+ if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
+ if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
+ if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
+ if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
+ if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
+ if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
} else {
@@ -151,15 +205,15 @@
}
+ // BPTC
+
if ( p === RGBA_BPTC_Format ) {
extension = extensions.get( 'EXT_texture_compression_bptc' );
if ( extension !== null ) {
- // TODO Complete?
-
- return p;
+ if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
} else {
@@ -169,6 +223,8 @@
}
+ //
+
if ( p === UnsignedInt248Type ) {
if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8;

src/renderers/WebGLCubeRenderTarget.js

@@ -37,8 +37,6 @@
this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
- this.texture._needsFlipEnvMap = false;
-
}
fromEquirectangularTexture( renderer, texture ) {

src/renderers/WebGLRenderer.js

@@ -153,10 +153,6 @@
const _scissor = new Vector4( 0, 0, _width, _height );
let _scissorTest = false;
- //
-
- const _currentDrawBuffers = [];
-
// frustum
const _frustum = new Frustum();
@@ -205,7 +201,7 @@
try {
const contextAttributes = {
- alpha: _alpha,
+ alpha: true,
depth: _depth,
stencil: _stencil,
antialias: _antialias,
@@ -289,8 +285,6 @@
state = new WebGLState( _gl, extensions, capabilities );
- _currentDrawBuffers[ 0 ] = _gl.BACK;
-
info = new WebGLInfo( _gl );
properties = new WebGLProperties();
textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
@@ -306,7 +300,7 @@
materials = new WebGLMaterials( properties );
renderLists = new WebGLRenderLists();
renderStates = new WebGLRenderStates( extensions, capabilities );
- background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
+ background = new WebGLBackground( _this, cubemaps, state, objects, _alpha, _premultipliedAlpha );
shadowMap = new WebGLShadowMap( _this, objects, capabilities );
bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
@@ -1421,7 +1415,7 @@
const fog = scene.fog;
const environment = material.isMeshStandardMaterial ? scene.environment : null;
- const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
+ const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
@@ -1889,67 +1883,7 @@
if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
- let needsUpdate = false;
-
- if ( renderTarget ) {
-
- if ( renderTarget.isWebGLMultipleRenderTargets ) {
-
- const textures = renderTarget.texture;
-
- if ( _currentDrawBuffers.length !== textures.length || _currentDrawBuffers[ 0 ] !== _gl.COLOR_ATTACHMENT0 ) {
-
- for ( let i = 0, il = textures.length; i < il; i ++ ) {
-
- _currentDrawBuffers[ i ] = _gl.COLOR_ATTACHMENT0 + i;
-
- }
-
- _currentDrawBuffers.length = textures.length;
-
- needsUpdate = true;
-
- }
-
- } else {
-
- if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== _gl.COLOR_ATTACHMENT0 ) {
-
- _currentDrawBuffers[ 0 ] = _gl.COLOR_ATTACHMENT0;
- _currentDrawBuffers.length = 1;
-
- needsUpdate = true;
-
- }
-
- }
-
- } else {
-
- if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== _gl.BACK ) {
-
- _currentDrawBuffers[ 0 ] = _gl.BACK;
- _currentDrawBuffers.length = 1;
-
- needsUpdate = true;
-
- }
-
- }
-
- if ( needsUpdate ) {
-
- if ( capabilities.isWebGL2 ) {
-
- _gl.drawBuffers( _currentDrawBuffers );
-
- } else {
-
- extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( _currentDrawBuffers );
-
- }
-
- }
+ state.drawBuffers( renderTarget, framebuffer );
}

src/renderers/WebGLRenderTarget.js

@@ -86,7 +86,10 @@
this.viewport.copy( source.viewport );
this.texture = source.texture.clone();
- this.texture.image = { ...this.texture.image }; // See #20328.
+
+ // ensure image object is not shared, see #20328
+
+ this.texture.image = Object.assign( {}, source.texture.image );
this.depthBuffer = source.depthBuffer;
this.stencilBuffer = source.stencilBuffer;

src/renderers/webxr/WebXRManager.js

@@ -12,7 +12,7 @@
DepthFormat,
DepthStencilFormat,
RGBAFormat,
- RGBFormat,
+ sRGBEncoding,
UnsignedByteType,
UnsignedShortType,
UnsignedInt248Type,
@@ -281,7 +281,7 @@
}
const projectionlayerInit = {
- colorFormat: ( attributes.alpha || isMultisample ) ? gl.RGBA8 : gl.RGB8,
+ colorFormat: ( renderer.outputEncoding === sRGBEncoding ) ? gl.SRGB8_ALPHA8 : gl.RGBA8,
depthFormat: glDepthFormat,
scaleFactor: framebufferScaleFactor
};
@@ -313,7 +313,7 @@
glProjLayer.textureWidth,
glProjLayer.textureHeight,
{
- format: attributes.alpha ? RGBAFormat : RGBFormat,
+ format: RGBAFormat,
type: UnsignedByteType,
depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
stencilBuffer: attributes.stencil,
@@ -325,6 +325,8 @@
}
+ newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
+
// Set foveation to maximum.
this.setFoveation( 1.0 );

src/textures/Texture.js

@@ -70,7 +70,8 @@
this.version = 0;
this.onUpdate = null;
- this.isRenderTargetTexture = false;
+ this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
+ this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
}

src/textures/VideoTexture.js

@@ -1,4 +1,4 @@
-import { RGBFormat, LinearFilter } from '../constants.js';
+import { LinearFilter } from '../constants.js';
import { Texture } from './Texture.js';
class VideoTexture extends Texture {
@@ -7,8 +7,6 @@
super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
- this.format = format !== undefined ? format : RGBFormat;
-
this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;

src/utils.js

@@ -30,6 +30,20 @@
}
+function arrayNeedsUint32( array ) {
+
+ // assumes larger values usually on last
+
+ for ( let i = array.length - 1; i >= 0; -- i ) {
+
+ if ( array[ i ] > 65535 ) return true;
+
+ }
+
+ return false;
+
+}
+
const TYPED_ARRAYS = {
Int8Array: Int8Array,
Uint8Array: Uint8Array,
@@ -54,4 +68,4 @@
}
-export { arrayMin, arrayMax, getTypedArray, createElementNS };
+export { arrayMin, arrayMax, arrayNeedsUint32, getTypedArray, createElementNS };