2 (function (global, factory) {
3 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
4 typeof define === 'function' && define.amd ? define(['exports'], factory) :
5 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.THREE = {}));
6 }(this, (function (exports) { 'use strict';
9 if (Number.EPSILON === undefined) {
10 Number.EPSILON = Math.pow(2, -52);
13 if (Number.isInteger === undefined) {
15 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
16 Number.isInteger = function (value) {
17 return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
22 if (Math.sign === undefined) {
23 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
24 Math.sign = function (x) {
25 return x < 0 ? -1 : x > 0 ? 1 : +x;
29 if ('name' in Function.prototype === false) {
31 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
32 Object.defineProperty(Function.prototype, 'name', {
34 return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
39 if (Object.assign === undefined) {
41 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
42 Object.assign = function (target) {
44 if (target === undefined || target === null) {
45 throw new TypeError('Cannot convert undefined or null to object');
48 var output = Object(target);
50 for (var index = 1; index < arguments.length; index++) {
51 var source = arguments[index];
53 if (source !== undefined && source !== null) {
54 for (var nextKey in source) {
55 if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
56 output[nextKey] = source[nextKey];
83 var CullFaceFront = 2;
84 var CullFaceFrontBack = 3;
85 var BasicShadowMap = 0;
87 var PCFSoftShadowMap = 2;
93 var SmoothShading = 2;
95 var NormalBlending = 1;
96 var AdditiveBlending = 2;
97 var SubtractiveBlending = 3;
98 var MultiplyBlending = 4;
99 var CustomBlending = 5;
100 var AddEquation = 100;
101 var SubtractEquation = 101;
102 var ReverseSubtractEquation = 102;
103 var MinEquation = 103;
104 var MaxEquation = 104;
105 var ZeroFactor = 200;
107 var SrcColorFactor = 202;
108 var OneMinusSrcColorFactor = 203;
109 var SrcAlphaFactor = 204;
110 var OneMinusSrcAlphaFactor = 205;
111 var DstAlphaFactor = 206;
112 var OneMinusDstAlphaFactor = 207;
113 var DstColorFactor = 208;
114 var OneMinusDstColorFactor = 209;
115 var SrcAlphaSaturateFactor = 210;
119 var LessEqualDepth = 3;
121 var GreaterEqualDepth = 5;
122 var GreaterDepth = 6;
123 var NotEqualDepth = 7;
124 var MultiplyOperation = 0;
125 var MixOperation = 1;
126 var AddOperation = 2;
127 var NoToneMapping = 0;
128 var LinearToneMapping = 1;
129 var ReinhardToneMapping = 2;
130 var CineonToneMapping = 3;
131 var ACESFilmicToneMapping = 4;
132 var CustomToneMapping = 5;
134 var CubeReflectionMapping = 301;
135 var CubeRefractionMapping = 302;
136 var EquirectangularReflectionMapping = 303;
137 var EquirectangularRefractionMapping = 304;
138 var CubeUVReflectionMapping = 306;
139 var CubeUVRefractionMapping = 307;
140 var RepeatWrapping = 1000;
141 var ClampToEdgeWrapping = 1001;
142 var MirroredRepeatWrapping = 1002;
143 var NearestFilter = 1003;
144 var NearestMipmapNearestFilter = 1004;
145 var NearestMipMapNearestFilter = 1004;
146 var NearestMipmapLinearFilter = 1005;
147 var NearestMipMapLinearFilter = 1005;
148 var LinearFilter = 1006;
149 var LinearMipmapNearestFilter = 1007;
150 var LinearMipMapNearestFilter = 1007;
151 var LinearMipmapLinearFilter = 1008;
152 var LinearMipMapLinearFilter = 1008;
153 var UnsignedByteType = 1009;
155 var ShortType = 1011;
156 var UnsignedShortType = 1012;
158 var UnsignedIntType = 1014;
159 var FloatType = 1015;
160 var HalfFloatType = 1016;
161 var UnsignedShort4444Type = 1017;
162 var UnsignedShort5551Type = 1018;
163 var UnsignedShort565Type = 1019;
164 var UnsignedInt248Type = 1020;
165 var AlphaFormat = 1021;
166 var RGBFormat = 1022;
167 var RGBAFormat = 1023;
168 var LuminanceFormat = 1024;
169 var LuminanceAlphaFormat = 1025;
170 var RGBEFormat = RGBAFormat;
171 var DepthFormat = 1026;
172 var DepthStencilFormat = 1027;
173 var RedFormat = 1028;
174 var RedIntegerFormat = 1029;
176 var RGIntegerFormat = 1031;
177 var RGBIntegerFormat = 1032;
178 var RGBAIntegerFormat = 1033;
179 var RGB_S3TC_DXT1_Format = 33776;
180 var RGBA_S3TC_DXT1_Format = 33777;
181 var RGBA_S3TC_DXT3_Format = 33778;
182 var RGBA_S3TC_DXT5_Format = 33779;
183 var RGB_PVRTC_4BPPV1_Format = 35840;
184 var RGB_PVRTC_2BPPV1_Format = 35841;
185 var RGBA_PVRTC_4BPPV1_Format = 35842;
186 var RGBA_PVRTC_2BPPV1_Format = 35843;
187 var RGB_ETC1_Format = 36196;
188 var RGB_ETC2_Format = 37492;
189 var RGBA_ETC2_EAC_Format = 37496;
190 var RGBA_ASTC_4x4_Format = 37808;
191 var RGBA_ASTC_5x4_Format = 37809;
192 var RGBA_ASTC_5x5_Format = 37810;
193 var RGBA_ASTC_6x5_Format = 37811;
194 var RGBA_ASTC_6x6_Format = 37812;
195 var RGBA_ASTC_8x5_Format = 37813;
196 var RGBA_ASTC_8x6_Format = 37814;
197 var RGBA_ASTC_8x8_Format = 37815;
198 var RGBA_ASTC_10x5_Format = 37816;
199 var RGBA_ASTC_10x6_Format = 37817;
200 var RGBA_ASTC_10x8_Format = 37818;
201 var RGBA_ASTC_10x10_Format = 37819;
202 var RGBA_ASTC_12x10_Format = 37820;
203 var RGBA_ASTC_12x12_Format = 37821;
204 var RGBA_BPTC_Format = 36492;
205 var SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
206 var SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
207 var SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
208 var SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
209 var SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
210 var SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
211 var SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
212 var SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
213 var SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
214 var SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
215 var SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
216 var SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
217 var SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
218 var SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
220 var LoopRepeat = 2201;
221 var LoopPingPong = 2202;
222 var InterpolateDiscrete = 2300;
223 var InterpolateLinear = 2301;
224 var InterpolateSmooth = 2302;
225 var ZeroCurvatureEnding = 2400;
226 var ZeroSlopeEnding = 2401;
227 var WrapAroundEnding = 2402;
228 var NormalAnimationBlendMode = 2500;
229 var AdditiveAnimationBlendMode = 2501;
230 var TrianglesDrawMode = 0;
231 var TriangleStripDrawMode = 1;
232 var TriangleFanDrawMode = 2;
233 var LinearEncoding = 3000;
234 var sRGBEncoding = 3001;
235 var GammaEncoding = 3007;
236 var RGBEEncoding = 3002;
237 var LogLuvEncoding = 3003;
238 var RGBM7Encoding = 3004;
239 var RGBM16Encoding = 3005;
240 var RGBDEncoding = 3006;
241 var BasicDepthPacking = 3200;
242 var RGBADepthPacking = 3201;
243 var TangentSpaceNormalMap = 0;
244 var ObjectSpaceNormalMap = 1;
245 var ZeroStencilOp = 0;
246 var KeepStencilOp = 7680;
247 var ReplaceStencilOp = 7681;
248 var IncrementStencilOp = 7682;
249 var DecrementStencilOp = 7683;
250 var IncrementWrapStencilOp = 34055;
251 var DecrementWrapStencilOp = 34056;
252 var InvertStencilOp = 5386;
253 var NeverStencilFunc = 512;
254 var LessStencilFunc = 513;
255 var EqualStencilFunc = 514;
256 var LessEqualStencilFunc = 515;
257 var GreaterStencilFunc = 516;
258 var NotEqualStencilFunc = 517;
259 var GreaterEqualStencilFunc = 518;
260 var AlwaysStencilFunc = 519;
261 var StaticDrawUsage = 35044;
262 var DynamicDrawUsage = 35048;
263 var StreamDrawUsage = 35040;
264 var StaticReadUsage = 35045;
265 var DynamicReadUsage = 35049;
266 var StreamReadUsage = 35041;
267 var StaticCopyUsage = 35046;
268 var DynamicCopyUsage = 35050;
269 var StreamCopyUsage = 35042;
271 var GLSL3 = "300 es";
274 * https://github.com/mrdoob/eventdispatcher.js/
276 function EventDispatcher() {}
278 Object.assign(EventDispatcher.prototype, {
279 addEventListener: function addEventListener(type, listener) {
280 if (this._listeners === undefined) this._listeners = {};
281 var listeners = this._listeners;
283 if (listeners[type] === undefined) {
284 listeners[type] = [];
287 if (listeners[type].indexOf(listener) === -1) {
288 listeners[type].push(listener);
291 hasEventListener: function hasEventListener(type, listener) {
292 if (this._listeners === undefined) return false;
293 var listeners = this._listeners;
294 return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
296 removeEventListener: function removeEventListener(type, listener) {
297 if (this._listeners === undefined) return;
298 var listeners = this._listeners;
299 var listenerArray = listeners[type];
301 if (listenerArray !== undefined) {
302 var index = listenerArray.indexOf(listener);
305 listenerArray.splice(index, 1);
309 dispatchEvent: function dispatchEvent(event) {
310 if (this._listeners === undefined) return;
311 var listeners = this._listeners;
312 var listenerArray = listeners[event.type];
314 if (listenerArray !== undefined) {
315 event.target = this; // Make a copy, in case listeners are removed while iterating.
317 var array = listenerArray.slice(0);
319 for (var i = 0, l = array.length; i < l; i++) {
320 array[i].call(this, event);
328 for (var i = 0; i < 256; i++) {
329 _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
334 DEG2RAD: Math.PI / 180,
335 RAD2DEG: 180 / Math.PI,
336 generateUUID: function generateUUID() {
337 // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
338 var d0 = Math.random() * 0xffffffff | 0;
339 var d1 = Math.random() * 0xffffffff | 0;
340 var d2 = Math.random() * 0xffffffff | 0;
341 var d3 = Math.random() * 0xffffffff | 0;
342 var 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.
344 return uuid.toUpperCase();
346 clamp: function clamp(value, min, max) {
347 return Math.max(min, Math.min(max, value));
349 // compute euclidian modulo of m % n
350 // https://en.wikipedia.org/wiki/Modulo_operation
351 euclideanModulo: function euclideanModulo(n, m) {
352 return (n % m + m) % m;
354 // Linear mapping from range <a1, a2> to range <b1, b2>
355 mapLinear: function mapLinear(x, a1, a2, b1, b2) {
356 return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
358 // https://en.wikipedia.org/wiki/Linear_interpolation
359 lerp: function lerp(x, y, t) {
360 return (1 - t) * x + t * y;
362 // http://en.wikipedia.org/wiki/Smoothstep
363 smoothstep: function smoothstep(x, min, max) {
364 if (x <= min) return 0;
365 if (x >= max) return 1;
366 x = (x - min) / (max - min);
367 return x * x * (3 - 2 * x);
369 smootherstep: function smootherstep(x, min, max) {
370 if (x <= min) return 0;
371 if (x >= max) return 1;
372 x = (x - min) / (max - min);
373 return x * x * x * (x * (x * 6 - 15) + 10);
375 // Random integer from <low, high> interval
376 randInt: function randInt(low, high) {
377 return low + Math.floor(Math.random() * (high - low + 1));
379 // Random float from <low, high> interval
380 randFloat: function randFloat(low, high) {
381 return low + Math.random() * (high - low);
383 // Random float from <-range/2, range/2> interval
384 randFloatSpread: function randFloatSpread(range) {
385 return range * (0.5 - Math.random());
387 // Deterministic pseudo-random float in the interval [ 0, 1 ]
388 seededRandom: function seededRandom(s) {
389 if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
391 _seed = _seed * 16807 % 2147483647;
392 return (_seed - 1) / 2147483646;
394 degToRad: function degToRad(degrees) {
395 return degrees * MathUtils.DEG2RAD;
397 radToDeg: function radToDeg(radians) {
398 return radians * MathUtils.RAD2DEG;
400 isPowerOfTwo: function isPowerOfTwo(value) {
401 return (value & value - 1) === 0 && value !== 0;
403 ceilPowerOfTwo: function ceilPowerOfTwo(value) {
404 return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
406 floorPowerOfTwo: function floorPowerOfTwo(value) {
407 return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
409 setQuaternionFromProperEuler: function setQuaternionFromProperEuler(q, a, b, c, order) {
410 // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
411 // rotations are applied to the axes in the order specified by 'order'
412 // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
413 // angles are in radians
418 var c13 = cos((a + c) / 2);
419 var s13 = sin((a + c) / 2);
420 var c1_3 = cos((a - c) / 2);
421 var s1_3 = sin((a - c) / 2);
422 var c3_1 = cos((c - a) / 2);
423 var s3_1 = sin((c - a) / 2);
427 q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
431 q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
435 q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
439 q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
443 q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
447 q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
451 console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
456 function _defineProperties(target, props) {
457 for (var i = 0; i < props.length; i++) {
458 var descriptor = props[i];
459 descriptor.enumerable = descriptor.enumerable || false;
460 descriptor.configurable = true;
461 if ("value" in descriptor) descriptor.writable = true;
462 Object.defineProperty(target, descriptor.key, descriptor);
466 function _createClass(Constructor, protoProps, staticProps) {
467 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
468 if (staticProps) _defineProperties(Constructor, staticProps);
472 function _inheritsLoose(subClass, superClass) {
473 subClass.prototype = Object.create(superClass.prototype);
474 subClass.prototype.constructor = subClass;
475 subClass.__proto__ = superClass;
478 function _assertThisInitialized(self) {
479 if (self === void 0) {
480 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
486 var Vector2 = /*#__PURE__*/function () {
487 function Vector2(x, y) {
496 Object.defineProperty(this, 'isVector2', {
503 var _proto = Vector2.prototype;
505 _proto.set = function set(x, y) {
511 _proto.setScalar = function setScalar(scalar) {
517 _proto.setX = function setX(x) {
522 _proto.setY = function setY(y) {
527 _proto.setComponent = function setComponent(index, value) {
538 throw new Error('index is out of range: ' + index);
544 _proto.getComponent = function getComponent(index) {
553 throw new Error('index is out of range: ' + index);
557 _proto.clone = function clone() {
558 return new this.constructor(this.x, this.y);
561 _proto.copy = function copy(v) {
567 _proto.add = function add(v, w) {
568 if (w !== undefined) {
569 console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
570 return this.addVectors(v, w);
578 _proto.addScalar = function addScalar(s) {
584 _proto.addVectors = function addVectors(a, b) {
590 _proto.addScaledVector = function addScaledVector(v, s) {
596 _proto.sub = function sub(v, w) {
597 if (w !== undefined) {
598 console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
599 return this.subVectors(v, w);
607 _proto.subScalar = function subScalar(s) {
613 _proto.subVectors = function subVectors(a, b) {
619 _proto.multiply = function multiply(v) {
625 _proto.multiplyScalar = function multiplyScalar(scalar) {
631 _proto.divide = function divide(v) {
637 _proto.divideScalar = function divideScalar(scalar) {
638 return this.multiplyScalar(1 / scalar);
641 _proto.applyMatrix3 = function applyMatrix3(m) {
645 this.x = e[0] * x + e[3] * y + e[6];
646 this.y = e[1] * x + e[4] * y + e[7];
650 _proto.min = function min(v) {
651 this.x = Math.min(this.x, v.x);
652 this.y = Math.min(this.y, v.y);
656 _proto.max = function max(v) {
657 this.x = Math.max(this.x, v.x);
658 this.y = Math.max(this.y, v.y);
662 _proto.clamp = function clamp(min, max) {
663 // assumes min < max, componentwise
664 this.x = Math.max(min.x, Math.min(max.x, this.x));
665 this.y = Math.max(min.y, Math.min(max.y, this.y));
669 _proto.clampScalar = function clampScalar(minVal, maxVal) {
670 this.x = Math.max(minVal, Math.min(maxVal, this.x));
671 this.y = Math.max(minVal, Math.min(maxVal, this.y));
675 _proto.clampLength = function clampLength(min, max) {
676 var length = this.length();
677 return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
680 _proto.floor = function floor() {
681 this.x = Math.floor(this.x);
682 this.y = Math.floor(this.y);
686 _proto.ceil = function ceil() {
687 this.x = Math.ceil(this.x);
688 this.y = Math.ceil(this.y);
692 _proto.round = function round() {
693 this.x = Math.round(this.x);
694 this.y = Math.round(this.y);
698 _proto.roundToZero = function roundToZero() {
699 this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
700 this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
704 _proto.negate = function negate() {
710 _proto.dot = function dot(v) {
711 return this.x * v.x + this.y * v.y;
714 _proto.cross = function cross(v) {
715 return this.x * v.y - this.y * v.x;
718 _proto.lengthSq = function lengthSq() {
719 return this.x * this.x + this.y * this.y;
722 _proto.length = function length() {
723 return Math.sqrt(this.x * this.x + this.y * this.y);
726 _proto.manhattanLength = function manhattanLength() {
727 return Math.abs(this.x) + Math.abs(this.y);
730 _proto.normalize = function normalize() {
731 return this.divideScalar(this.length() || 1);
734 _proto.angle = function angle() {
735 // computes the angle in radians with respect to the positive x-axis
736 var angle = Math.atan2(-this.y, -this.x) + Math.PI;
740 _proto.distanceTo = function distanceTo(v) {
741 return Math.sqrt(this.distanceToSquared(v));
744 _proto.distanceToSquared = function distanceToSquared(v) {
745 var dx = this.x - v.x,
747 return dx * dx + dy * dy;
750 _proto.manhattanDistanceTo = function manhattanDistanceTo(v) {
751 return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
754 _proto.setLength = function setLength(length) {
755 return this.normalize().multiplyScalar(length);
758 _proto.lerp = function lerp(v, alpha) {
759 this.x += (v.x - this.x) * alpha;
760 this.y += (v.y - this.y) * alpha;
764 _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
765 this.x = v1.x + (v2.x - v1.x) * alpha;
766 this.y = v1.y + (v2.y - v1.y) * alpha;
770 _proto.equals = function equals(v) {
771 return v.x === this.x && v.y === this.y;
774 _proto.fromArray = function fromArray(array, offset) {
775 if (offset === void 0) {
779 this.x = array[offset];
780 this.y = array[offset + 1];
784 _proto.toArray = function toArray(array, offset) {
785 if (array === void 0) {
789 if (offset === void 0) {
793 array[offset] = this.x;
794 array[offset + 1] = this.y;
798 _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
799 if (offset !== undefined) {
800 console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
803 this.x = attribute.getX(index);
804 this.y = attribute.getY(index);
808 _proto.rotateAround = function rotateAround(center, angle) {
809 var c = Math.cos(angle),
811 var x = this.x - center.x;
812 var y = this.y - center.y;
813 this.x = x * c - y * s + center.x;
814 this.y = x * s + y * c + center.y;
818 _proto.random = function random() {
819 this.x = Math.random();
820 this.y = Math.random();
824 _createClass(Vector2, [{
826 get: function get() {
829 set: function set(value) {
834 get: function get() {
837 set: function set(value) {
845 var Matrix3 = /*#__PURE__*/function () {
847 Object.defineProperty(this, 'isMatrix3', {
850 this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
852 if (arguments.length > 0) {
853 console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
857 var _proto = Matrix3.prototype;
859 _proto.set = function set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
860 var te = this.elements;
873 _proto.identity = function identity() {
874 this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
878 _proto.clone = function clone() {
879 return new this.constructor().fromArray(this.elements);
882 _proto.copy = function copy(m) {
883 var te = this.elements;
897 _proto.extractBasis = function extractBasis(xAxis, yAxis, zAxis) {
898 xAxis.setFromMatrix3Column(this, 0);
899 yAxis.setFromMatrix3Column(this, 1);
900 zAxis.setFromMatrix3Column(this, 2);
904 _proto.setFromMatrix4 = function setFromMatrix4(m) {
906 this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
910 _proto.multiply = function multiply(m) {
911 return this.multiplyMatrices(this, m);
914 _proto.premultiply = function premultiply(m) {
915 return this.multiplyMatrices(m, this);
918 _proto.multiplyMatrices = function multiplyMatrices(a, b) {
921 var te = this.elements;
940 te[0] = a11 * b11 + a12 * b21 + a13 * b31;
941 te[3] = a11 * b12 + a12 * b22 + a13 * b32;
942 te[6] = a11 * b13 + a12 * b23 + a13 * b33;
943 te[1] = a21 * b11 + a22 * b21 + a23 * b31;
944 te[4] = a21 * b12 + a22 * b22 + a23 * b32;
945 te[7] = a21 * b13 + a22 * b23 + a23 * b33;
946 te[2] = a31 * b11 + a32 * b21 + a33 * b31;
947 te[5] = a31 * b12 + a32 * b22 + a33 * b32;
948 te[8] = a31 * b13 + a32 * b23 + a33 * b33;
952 _proto.multiplyScalar = function multiplyScalar(s) {
953 var te = this.elements;
966 _proto.determinant = function determinant() {
967 var te = this.elements;
977 return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
980 _proto.invert = function invert() {
981 var te = this.elements,
991 t11 = n33 * n22 - n32 * n23,
992 t12 = n32 * n13 - n33 * n12,
993 t13 = n23 * n12 - n22 * n13,
994 det = n11 * t11 + n21 * t12 + n31 * t13;
995 if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
996 var detInv = 1 / det;
997 te[0] = t11 * detInv;
998 te[1] = (n31 * n23 - n33 * n21) * detInv;
999 te[2] = (n32 * n21 - n31 * n22) * detInv;
1000 te[3] = t12 * detInv;
1001 te[4] = (n33 * n11 - n31 * n13) * detInv;
1002 te[5] = (n31 * n12 - n32 * n11) * detInv;
1003 te[6] = t13 * detInv;
1004 te[7] = (n21 * n13 - n23 * n11) * detInv;
1005 te[8] = (n22 * n11 - n21 * n12) * detInv;
1009 _proto.transpose = function transpose() {
1011 var m = this.elements;
1024 _proto.getNormalMatrix = function getNormalMatrix(matrix4) {
1025 return this.setFromMatrix4(matrix4).copy(this).invert().transpose();
1028 _proto.transposeIntoArray = function transposeIntoArray(r) {
1029 var m = this.elements;
1042 _proto.setUvTransform = function setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
1043 var c = Math.cos(rotation);
1044 var s = Math.sin(rotation);
1045 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);
1048 _proto.scale = function scale(sx, sy) {
1049 var te = this.elements;
1059 _proto.rotate = function rotate(theta) {
1060 var c = Math.cos(theta);
1061 var s = Math.sin(theta);
1062 var te = this.elements;
1069 te[0] = c * a11 + s * a21;
1070 te[3] = c * a12 + s * a22;
1071 te[6] = c * a13 + s * a23;
1072 te[1] = -s * a11 + c * a21;
1073 te[4] = -s * a12 + c * a22;
1074 te[7] = -s * a13 + c * a23;
1078 _proto.translate = function translate(tx, ty) {
1079 var te = this.elements;
1080 te[0] += tx * te[2];
1081 te[3] += tx * te[5];
1082 te[6] += tx * te[8];
1083 te[1] += ty * te[2];
1084 te[4] += ty * te[5];
1085 te[7] += ty * te[8];
1089 _proto.equals = function equals(matrix) {
1090 var te = this.elements;
1091 var me = matrix.elements;
1093 for (var i = 0; i < 9; i++) {
1094 if (te[i] !== me[i]) return false;
1100 _proto.fromArray = function fromArray(array, offset) {
1101 if (offset === void 0) {
1105 for (var i = 0; i < 9; i++) {
1106 this.elements[i] = array[i + offset];
1112 _proto.toArray = function toArray(array, offset) {
1113 if (array === void 0) {
1117 if (offset === void 0) {
1121 var te = this.elements;
1122 array[offset] = te[0];
1123 array[offset + 1] = te[1];
1124 array[offset + 2] = te[2];
1125 array[offset + 3] = te[3];
1126 array[offset + 4] = te[4];
1127 array[offset + 5] = te[5];
1128 array[offset + 6] = te[6];
1129 array[offset + 7] = te[7];
1130 array[offset + 8] = te[8];
1140 getDataURL: function getDataURL(image) {
1141 if (/^data:/i.test(image.src)) {
1145 if (typeof HTMLCanvasElement == 'undefined') {
1151 if (image instanceof HTMLCanvasElement) {
1154 if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
1155 _canvas.width = image.width;
1156 _canvas.height = image.height;
1158 var context = _canvas.getContext('2d');
1160 if (image instanceof ImageData) {
1161 context.putImageData(image, 0, 0);
1163 context.drawImage(image, 0, 0, image.width, image.height);
1169 if (canvas.width > 2048 || canvas.height > 2048) {
1170 return canvas.toDataURL('image/jpeg', 0.6);
1172 return canvas.toDataURL('image/png');
1179 function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
1180 if (image === void 0) {
1181 image = Texture.DEFAULT_IMAGE;
1184 if (mapping === void 0) {
1185 mapping = Texture.DEFAULT_MAPPING;
1188 if (wrapS === void 0) {
1189 wrapS = ClampToEdgeWrapping;
1192 if (wrapT === void 0) {
1193 wrapT = ClampToEdgeWrapping;
1196 if (magFilter === void 0) {
1197 magFilter = LinearFilter;
1200 if (minFilter === void 0) {
1201 minFilter = LinearMipmapLinearFilter;
1204 if (format === void 0) {
1205 format = RGBAFormat;
1208 if (type === void 0) {
1209 type = UnsignedByteType;
1212 if (anisotropy === void 0) {
1216 if (encoding === void 0) {
1217 encoding = LinearEncoding;
1220 Object.defineProperty(this, 'id', {
1223 this.uuid = MathUtils.generateUUID();
1227 this.mapping = mapping;
1230 this.magFilter = magFilter;
1231 this.minFilter = minFilter;
1232 this.anisotropy = anisotropy;
1233 this.format = format;
1234 this.internalFormat = null;
1236 this.offset = new Vector2(0, 0);
1237 this.repeat = new Vector2(1, 1);
1238 this.center = new Vector2(0, 0);
1240 this.matrixAutoUpdate = true;
1241 this.matrix = new Matrix3();
1242 this.generateMipmaps = true;
1243 this.premultiplyAlpha = false;
1245 this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
1246 // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
1248 // Also changing the encoding after already used by a Material will not automatically make the Material
1249 // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
1251 this.encoding = encoding;
1253 this.onUpdate = null;
1256 Texture.DEFAULT_IMAGE = undefined;
1257 Texture.DEFAULT_MAPPING = UVMapping;
1258 Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
1259 constructor: Texture,
1261 updateMatrix: function updateMatrix() {
1262 this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
1264 clone: function clone() {
1265 return new this.constructor().copy(this);
1267 copy: function copy(source) {
1268 this.name = source.name;
1269 this.image = source.image;
1270 this.mipmaps = source.mipmaps.slice(0);
1271 this.mapping = source.mapping;
1272 this.wrapS = source.wrapS;
1273 this.wrapT = source.wrapT;
1274 this.magFilter = source.magFilter;
1275 this.minFilter = source.minFilter;
1276 this.anisotropy = source.anisotropy;
1277 this.format = source.format;
1278 this.internalFormat = source.internalFormat;
1279 this.type = source.type;
1280 this.offset.copy(source.offset);
1281 this.repeat.copy(source.repeat);
1282 this.center.copy(source.center);
1283 this.rotation = source.rotation;
1284 this.matrixAutoUpdate = source.matrixAutoUpdate;
1285 this.matrix.copy(source.matrix);
1286 this.generateMipmaps = source.generateMipmaps;
1287 this.premultiplyAlpha = source.premultiplyAlpha;
1288 this.flipY = source.flipY;
1289 this.unpackAlignment = source.unpackAlignment;
1290 this.encoding = source.encoding;
1293 toJSON: function toJSON(meta) {
1294 var isRootObject = meta === undefined || typeof meta === 'string';
1296 if (!isRootObject && meta.textures[this.uuid] !== undefined) {
1297 return meta.textures[this.uuid];
1304 generator: 'Texture.toJSON'
1308 mapping: this.mapping,
1309 repeat: [this.repeat.x, this.repeat.y],
1310 offset: [this.offset.x, this.offset.y],
1311 center: [this.center.x, this.center.y],
1312 rotation: this.rotation,
1313 wrap: [this.wrapS, this.wrapT],
1314 format: this.format,
1316 encoding: this.encoding,
1317 minFilter: this.minFilter,
1318 magFilter: this.magFilter,
1319 anisotropy: this.anisotropy,
1321 premultiplyAlpha: this.premultiplyAlpha,
1322 unpackAlignment: this.unpackAlignment
1325 if (this.image !== undefined) {
1326 // TODO: Move to THREE.Image
1327 var image = this.image;
1329 if (image.uuid === undefined) {
1330 image.uuid = MathUtils.generateUUID(); // UGH
1333 if (!isRootObject && meta.images[image.uuid] === undefined) {
1336 if (Array.isArray(image)) {
1337 // process array of images e.g. CubeTexture
1340 for (var i = 0, l = image.length; i < l; i++) {
1341 // check cube texture with data textures
1342 if (image[i].isDataTexture) {
1343 url.push(serializeImage(image[i].image));
1345 url.push(serializeImage(image[i]));
1349 // process single image
1350 url = serializeImage(image);
1353 meta.images[image.uuid] = {
1359 output.image = image.uuid;
1362 if (!isRootObject) {
1363 meta.textures[this.uuid] = output;
1368 dispose: function dispose() {
1369 this.dispatchEvent({
1373 transformUv: function transformUv(uv) {
1374 if (this.mapping !== UVMapping) return uv;
1375 uv.applyMatrix3(this.matrix);
1377 if (uv.x < 0 || uv.x > 1) {
1378 switch (this.wrapS) {
1379 case RepeatWrapping:
1380 uv.x = uv.x - Math.floor(uv.x);
1383 case ClampToEdgeWrapping:
1384 uv.x = uv.x < 0 ? 0 : 1;
1387 case MirroredRepeatWrapping:
1388 if (Math.abs(Math.floor(uv.x) % 2) === 1) {
1389 uv.x = Math.ceil(uv.x) - uv.x;
1391 uv.x = uv.x - Math.floor(uv.x);
1398 if (uv.y < 0 || uv.y > 1) {
1399 switch (this.wrapT) {
1400 case RepeatWrapping:
1401 uv.y = uv.y - Math.floor(uv.y);
1404 case ClampToEdgeWrapping:
1405 uv.y = uv.y < 0 ? 0 : 1;
1408 case MirroredRepeatWrapping:
1409 if (Math.abs(Math.floor(uv.y) % 2) === 1) {
1410 uv.y = Math.ceil(uv.y) - uv.y;
1412 uv.y = uv.y - Math.floor(uv.y);
1426 Object.defineProperty(Texture.prototype, "needsUpdate", {
1427 set: function set(value) {
1428 if (value === true) this.version++;
1432 function serializeImage(image) {
1433 if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
1435 return ImageUtils.getDataURL(image);
1438 // images of DataTexture
1440 data: Array.prototype.slice.call(image.data),
1442 height: image.height,
1443 type: image.data.constructor.name
1446 console.warn('THREE.Texture: Unable to serialize Texture.');
1452 var Vector4 = /*#__PURE__*/function () {
1453 function Vector4(x, y, z, w) {
1470 Object.defineProperty(this, 'isVector4', {
1479 var _proto = Vector4.prototype;
1481 _proto.set = function set(x, y, z, w) {
1489 _proto.setScalar = function setScalar(scalar) {
1497 _proto.setX = function setX(x) {
1502 _proto.setY = function setY(y) {
1507 _proto.setZ = function setZ(z) {
1512 _proto.setW = function setW(w) {
1517 _proto.setComponent = function setComponent(index, value) {
1536 throw new Error('index is out of range: ' + index);
1542 _proto.getComponent = function getComponent(index) {
1557 throw new Error('index is out of range: ' + index);
1561 _proto.clone = function clone() {
1562 return new this.constructor(this.x, this.y, this.z, this.w);
1565 _proto.copy = function copy(v) {
1569 this.w = v.w !== undefined ? v.w : 1;
1573 _proto.add = function add(v, w) {
1574 if (w !== undefined) {
1575 console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
1576 return this.addVectors(v, w);
1586 _proto.addScalar = function addScalar(s) {
1594 _proto.addVectors = function addVectors(a, b) {
1602 _proto.addScaledVector = function addScaledVector(v, s) {
1610 _proto.sub = function sub(v, w) {
1611 if (w !== undefined) {
1612 console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
1613 return this.subVectors(v, w);
1623 _proto.subScalar = function subScalar(s) {
1631 _proto.subVectors = function subVectors(a, b) {
1639 _proto.multiplyScalar = function multiplyScalar(scalar) {
1647 _proto.applyMatrix4 = function applyMatrix4(m) {
1653 this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
1654 this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
1655 this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
1656 this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
1660 _proto.divideScalar = function divideScalar(scalar) {
1661 return this.multiplyScalar(1 / scalar);
1664 _proto.setAxisAngleFromQuaternion = function setAxisAngleFromQuaternion(q) {
1665 // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
1666 // q is assumed to be normalized
1667 this.w = 2 * Math.acos(q.w);
1668 var s = Math.sqrt(1 - q.w * q.w);
1683 _proto.setAxisAngleFromRotationMatrix = function setAxisAngleFromRotationMatrix(m) {
1684 // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
1685 // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
1686 var angle, x, y, z; // variables for result
1689 // margin to allow for rounding errors
1691 // margin to distinguish between 0 and 180 degrees
1703 if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
1704 // singularity found
1705 // first check for identity matrix which must have +1 for all terms
1706 // in leading diagonal and zero in other terms
1707 if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
1708 // this singularity is identity matrix so angle = 0
1709 this.set(1, 0, 0, 0);
1710 return this; // zero angle, arbitrary axis
1711 } // otherwise this singularity is angle = 180
1715 var xx = (m11 + 1) / 2;
1716 var yy = (m22 + 1) / 2;
1717 var zz = (m33 + 1) / 2;
1718 var xy = (m12 + m21) / 4;
1719 var xz = (m13 + m31) / 4;
1720 var yz = (m23 + m32) / 4;
1722 if (xx > yy && xx > zz) {
1723 // m11 is the largest diagonal term
1733 } else if (yy > zz) {
1734 // m22 is the largest diagonal term
1745 // m33 is the largest diagonal term so base result on this
1757 this.set(x, y, z, angle);
1758 return this; // return 180 deg rotation
1759 } // as we have reached here there are no singularities so we can handle normally
1762 var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
1764 if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
1765 // caught by singularity test above, but I've left it in just in case
1767 this.x = (m32 - m23) / s;
1768 this.y = (m13 - m31) / s;
1769 this.z = (m21 - m12) / s;
1770 this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
1774 _proto.min = function min(v) {
1775 this.x = Math.min(this.x, v.x);
1776 this.y = Math.min(this.y, v.y);
1777 this.z = Math.min(this.z, v.z);
1778 this.w = Math.min(this.w, v.w);
1782 _proto.max = function max(v) {
1783 this.x = Math.max(this.x, v.x);
1784 this.y = Math.max(this.y, v.y);
1785 this.z = Math.max(this.z, v.z);
1786 this.w = Math.max(this.w, v.w);
1790 _proto.clamp = function clamp(min, max) {
1791 // assumes min < max, componentwise
1792 this.x = Math.max(min.x, Math.min(max.x, this.x));
1793 this.y = Math.max(min.y, Math.min(max.y, this.y));
1794 this.z = Math.max(min.z, Math.min(max.z, this.z));
1795 this.w = Math.max(min.w, Math.min(max.w, this.w));
1799 _proto.clampScalar = function clampScalar(minVal, maxVal) {
1800 this.x = Math.max(minVal, Math.min(maxVal, this.x));
1801 this.y = Math.max(minVal, Math.min(maxVal, this.y));
1802 this.z = Math.max(minVal, Math.min(maxVal, this.z));
1803 this.w = Math.max(minVal, Math.min(maxVal, this.w));
1807 _proto.clampLength = function clampLength(min, max) {
1808 var length = this.length();
1809 return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
1812 _proto.floor = function floor() {
1813 this.x = Math.floor(this.x);
1814 this.y = Math.floor(this.y);
1815 this.z = Math.floor(this.z);
1816 this.w = Math.floor(this.w);
1820 _proto.ceil = function ceil() {
1821 this.x = Math.ceil(this.x);
1822 this.y = Math.ceil(this.y);
1823 this.z = Math.ceil(this.z);
1824 this.w = Math.ceil(this.w);
1828 _proto.round = function round() {
1829 this.x = Math.round(this.x);
1830 this.y = Math.round(this.y);
1831 this.z = Math.round(this.z);
1832 this.w = Math.round(this.w);
1836 _proto.roundToZero = function roundToZero() {
1837 this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
1838 this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
1839 this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
1840 this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
1844 _proto.negate = function negate() {
1852 _proto.dot = function dot(v) {
1853 return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
1856 _proto.lengthSq = function lengthSq() {
1857 return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
1860 _proto.length = function length() {
1861 return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
1864 _proto.manhattanLength = function manhattanLength() {
1865 return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
1868 _proto.normalize = function normalize() {
1869 return this.divideScalar(this.length() || 1);
1872 _proto.setLength = function setLength(length) {
1873 return this.normalize().multiplyScalar(length);
1876 _proto.lerp = function lerp(v, alpha) {
1877 this.x += (v.x - this.x) * alpha;
1878 this.y += (v.y - this.y) * alpha;
1879 this.z += (v.z - this.z) * alpha;
1880 this.w += (v.w - this.w) * alpha;
1884 _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
1885 this.x = v1.x + (v2.x - v1.x) * alpha;
1886 this.y = v1.y + (v2.y - v1.y) * alpha;
1887 this.z = v1.z + (v2.z - v1.z) * alpha;
1888 this.w = v1.w + (v2.w - v1.w) * alpha;
1892 _proto.equals = function equals(v) {
1893 return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
1896 _proto.fromArray = function fromArray(array, offset) {
1897 if (offset === void 0) {
1901 this.x = array[offset];
1902 this.y = array[offset + 1];
1903 this.z = array[offset + 2];
1904 this.w = array[offset + 3];
1908 _proto.toArray = function toArray(array, offset) {
1909 if (array === void 0) {
1913 if (offset === void 0) {
1917 array[offset] = this.x;
1918 array[offset + 1] = this.y;
1919 array[offset + 2] = this.z;
1920 array[offset + 3] = this.w;
1924 _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
1925 if (offset !== undefined) {
1926 console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
1929 this.x = attribute.getX(index);
1930 this.y = attribute.getY(index);
1931 this.z = attribute.getZ(index);
1932 this.w = attribute.getW(index);
1936 _proto.random = function random() {
1937 this.x = Math.random();
1938 this.y = Math.random();
1939 this.z = Math.random();
1940 this.w = Math.random();
1944 _createClass(Vector4, [{
1946 get: function get() {
1949 set: function set(value) {
1954 get: function get() {
1957 set: function set(value) {
1966 In options, we can specify:
1967 * Texture parameters for an auto-generated target texture
1968 * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
1971 function WebGLRenderTarget(width, height, options) {
1973 this.height = height;
1974 this.scissor = new Vector4(0, 0, width, height);
1975 this.scissorTest = false;
1976 this.viewport = new Vector4(0, 0, width, height);
1977 options = options || {};
1978 this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
1979 this.texture.image = {};
1980 this.texture.image.width = width;
1981 this.texture.image.height = height;
1982 this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
1983 this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
1984 this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
1985 this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
1986 this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
1989 WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
1990 constructor: WebGLRenderTarget,
1991 isWebGLRenderTarget: true,
1992 setSize: function setSize(width, height) {
1993 if (this.width !== width || this.height !== height) {
1995 this.height = height;
1996 this.texture.image.width = width;
1997 this.texture.image.height = height;
2001 this.viewport.set(0, 0, width, height);
2002 this.scissor.set(0, 0, width, height);
2004 clone: function clone() {
2005 return new this.constructor().copy(this);
2007 copy: function copy(source) {
2008 this.width = source.width;
2009 this.height = source.height;
2010 this.viewport.copy(source.viewport);
2011 this.texture = source.texture.clone();
2012 this.depthBuffer = source.depthBuffer;
2013 this.stencilBuffer = source.stencilBuffer;
2014 this.depthTexture = source.depthTexture;
2017 dispose: function dispose() {
2018 this.dispatchEvent({
2024 function WebGLMultisampleRenderTarget(width, height, options) {
2025 WebGLRenderTarget.call(this, width, height, options);
2029 WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
2030 constructor: WebGLMultisampleRenderTarget,
2031 isWebGLMultisampleRenderTarget: true,
2032 copy: function copy(source) {
2033 WebGLRenderTarget.prototype.copy.call(this, source);
2034 this.samples = source.samples;
2039 var Quaternion = /*#__PURE__*/function () {
2040 function Quaternion(x, y, z, w) {
2057 Object.defineProperty(this, 'isQuaternion', {
2066 Quaternion.slerp = function slerp(qa, qb, qm, t) {
2067 return qm.copy(qa).slerp(qb, t);
2070 Quaternion.slerpFlat = function slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
2071 // fuzz-free, array-based Quaternion SLERP operation
2072 var x0 = src0[srcOffset0 + 0],
2073 y0 = src0[srcOffset0 + 1],
2074 z0 = src0[srcOffset0 + 2],
2075 w0 = src0[srcOffset0 + 3];
2076 var x1 = src1[srcOffset1 + 0],
2077 y1 = src1[srcOffset1 + 1],
2078 z1 = src1[srcOffset1 + 2],
2079 w1 = src1[srcOffset1 + 3];
2081 if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
2083 var cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
2084 dir = cos >= 0 ? 1 : -1,
2085 sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
2087 if (sqrSin > Number.EPSILON) {
2088 var sin = Math.sqrt(sqrSin),
2089 len = Math.atan2(sin, cos * dir);
2090 s = Math.sin(s * len) / sin;
2091 t = Math.sin(t * len) / sin;
2095 x0 = x0 * s + x1 * tDir;
2096 y0 = y0 * s + y1 * tDir;
2097 z0 = z0 * s + z1 * tDir;
2098 w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
2101 var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
2109 dst[dstOffset] = x0;
2110 dst[dstOffset + 1] = y0;
2111 dst[dstOffset + 2] = z0;
2112 dst[dstOffset + 3] = w0;
2115 Quaternion.multiplyQuaternionsFlat = function multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
2116 var x0 = src0[srcOffset0];
2117 var y0 = src0[srcOffset0 + 1];
2118 var z0 = src0[srcOffset0 + 2];
2119 var w0 = src0[srcOffset0 + 3];
2120 var x1 = src1[srcOffset1];
2121 var y1 = src1[srcOffset1 + 1];
2122 var z1 = src1[srcOffset1 + 2];
2123 var w1 = src1[srcOffset1 + 3];
2124 dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
2125 dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
2126 dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
2127 dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
2131 var _proto = Quaternion.prototype;
2133 _proto.set = function set(x, y, z, w) {
2139 this._onChangeCallback();
2144 _proto.clone = function clone() {
2145 return new this.constructor(this._x, this._y, this._z, this._w);
2148 _proto.copy = function copy(quaternion) {
2149 this._x = quaternion.x;
2150 this._y = quaternion.y;
2151 this._z = quaternion.z;
2152 this._w = quaternion.w;
2154 this._onChangeCallback();
2159 _proto.setFromEuler = function setFromEuler(euler, update) {
2160 if (!(euler && euler.isEuler)) {
2161 throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
2167 order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
2168 // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
2169 // content/SpinCalc.m
2173 var c1 = cos(x / 2);
2174 var c2 = cos(y / 2);
2175 var c3 = cos(z / 2);
2176 var s1 = sin(x / 2);
2177 var s2 = sin(y / 2);
2178 var s3 = sin(z / 2);
2182 this._x = s1 * c2 * c3 + c1 * s2 * s3;
2183 this._y = c1 * s2 * c3 - s1 * c2 * s3;
2184 this._z = c1 * c2 * s3 + s1 * s2 * c3;
2185 this._w = c1 * c2 * c3 - s1 * s2 * s3;
2189 this._x = s1 * c2 * c3 + c1 * s2 * s3;
2190 this._y = c1 * s2 * c3 - s1 * c2 * s3;
2191 this._z = c1 * c2 * s3 - s1 * s2 * c3;
2192 this._w = c1 * c2 * c3 + s1 * s2 * s3;
2196 this._x = s1 * c2 * c3 - c1 * s2 * s3;
2197 this._y = c1 * s2 * c3 + s1 * c2 * s3;
2198 this._z = c1 * c2 * s3 + s1 * s2 * c3;
2199 this._w = c1 * c2 * c3 - s1 * s2 * s3;
2203 this._x = s1 * c2 * c3 - c1 * s2 * s3;
2204 this._y = c1 * s2 * c3 + s1 * c2 * s3;
2205 this._z = c1 * c2 * s3 - s1 * s2 * c3;
2206 this._w = c1 * c2 * c3 + s1 * s2 * s3;
2210 this._x = s1 * c2 * c3 + c1 * s2 * s3;
2211 this._y = c1 * s2 * c3 + s1 * c2 * s3;
2212 this._z = c1 * c2 * s3 - s1 * s2 * c3;
2213 this._w = c1 * c2 * c3 - s1 * s2 * s3;
2217 this._x = s1 * c2 * c3 - c1 * s2 * s3;
2218 this._y = c1 * s2 * c3 - s1 * c2 * s3;
2219 this._z = c1 * c2 * s3 + s1 * s2 * c3;
2220 this._w = c1 * c2 * c3 + s1 * s2 * s3;
2224 console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
2227 if (update !== false) this._onChangeCallback();
2231 _proto.setFromAxisAngle = function setFromAxisAngle(axis, angle) {
2232 // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
2233 // assumes axis is normalized
2234 var halfAngle = angle / 2,
2235 s = Math.sin(halfAngle);
2236 this._x = axis.x * s;
2237 this._y = axis.y * s;
2238 this._z = axis.z * s;
2239 this._w = Math.cos(halfAngle);
2241 this._onChangeCallback();
2246 _proto.setFromRotationMatrix = function setFromRotationMatrix(m) {
2247 // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
2248 // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
2249 var te = m.elements,
2259 trace = m11 + m22 + m33;
2262 var s = 0.5 / Math.sqrt(trace + 1.0);
2264 this._x = (m32 - m23) * s;
2265 this._y = (m13 - m31) * s;
2266 this._z = (m21 - m12) * s;
2267 } else if (m11 > m22 && m11 > m33) {
2268 var _s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
2270 this._w = (m32 - m23) / _s;
2271 this._x = 0.25 * _s;
2272 this._y = (m12 + m21) / _s;
2273 this._z = (m13 + m31) / _s;
2274 } else if (m22 > m33) {
2275 var _s2 = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
2277 this._w = (m13 - m31) / _s2;
2278 this._x = (m12 + m21) / _s2;
2279 this._y = 0.25 * _s2;
2280 this._z = (m23 + m32) / _s2;
2282 var _s3 = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
2284 this._w = (m21 - m12) / _s3;
2285 this._x = (m13 + m31) / _s3;
2286 this._y = (m23 + m32) / _s3;
2287 this._z = 0.25 * _s3;
2290 this._onChangeCallback();
2295 _proto.setFromUnitVectors = function setFromUnitVectors(vFrom, vTo) {
2296 // assumes direction vectors vFrom and vTo are normalized
2298 var r = vFrom.dot(vTo) + 1;
2303 if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
2315 // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
2316 this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
2317 this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
2318 this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
2322 return this.normalize();
2325 _proto.angleTo = function angleTo(q) {
2326 return 2 * Math.acos(Math.abs(MathUtils.clamp(this.dot(q), -1, 1)));
2329 _proto.rotateTowards = function rotateTowards(q, step) {
2330 var angle = this.angleTo(q);
2331 if (angle === 0) return this;
2332 var t = Math.min(1, step / angle);
2337 _proto.identity = function identity() {
2338 return this.set(0, 0, 0, 1);
2341 _proto.invert = function invert() {
2342 // quaternion is assumed to have unit length
2343 return this.conjugate();
2346 _proto.conjugate = function conjugate() {
2351 this._onChangeCallback();
2356 _proto.dot = function dot(v) {
2357 return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
2360 _proto.lengthSq = function lengthSq() {
2361 return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
2364 _proto.length = function length() {
2365 return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
2368 _proto.normalize = function normalize() {
2369 var l = this.length();
2378 this._x = this._x * l;
2379 this._y = this._y * l;
2380 this._z = this._z * l;
2381 this._w = this._w * l;
2384 this._onChangeCallback();
2389 _proto.multiply = function multiply(q, p) {
2390 if (p !== undefined) {
2391 console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
2392 return this.multiplyQuaternions(q, p);
2395 return this.multiplyQuaternions(this, q);
2398 _proto.premultiply = function premultiply(q) {
2399 return this.multiplyQuaternions(q, this);
2402 _proto.multiplyQuaternions = function multiplyQuaternions(a, b) {
2403 // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
2412 this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
2413 this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
2414 this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
2415 this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
2417 this._onChangeCallback();
2422 _proto.slerp = function slerp(qb, t) {
2423 if (t === 0) return this;
2424 if (t === 1) return this.copy(qb);
2428 w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
2430 var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
2432 if (cosHalfTheta < 0) {
2437 cosHalfTheta = -cosHalfTheta;
2442 if (cosHalfTheta >= 1.0) {
2450 var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
2452 if (sqrSinHalfTheta <= Number.EPSILON) {
2454 this._w = s * w + t * this._w;
2455 this._x = s * x + t * this._x;
2456 this._y = s * y + t * this._y;
2457 this._z = s * z + t * this._z;
2460 this._onChangeCallback();
2465 var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
2466 var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
2467 var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
2468 ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
2469 this._w = w * ratioA + this._w * ratioB;
2470 this._x = x * ratioA + this._x * ratioB;
2471 this._y = y * ratioA + this._y * ratioB;
2472 this._z = z * ratioA + this._z * ratioB;
2474 this._onChangeCallback();
2479 _proto.equals = function equals(quaternion) {
2480 return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
2483 _proto.fromArray = function fromArray(array, offset) {
2484 if (offset === void 0) {
2488 this._x = array[offset];
2489 this._y = array[offset + 1];
2490 this._z = array[offset + 2];
2491 this._w = array[offset + 3];
2493 this._onChangeCallback();
2498 _proto.toArray = function toArray(array, offset) {
2499 if (array === void 0) {
2503 if (offset === void 0) {
2507 array[offset] = this._x;
2508 array[offset + 1] = this._y;
2509 array[offset + 2] = this._z;
2510 array[offset + 3] = this._w;
2514 _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index) {
2515 this._x = attribute.getX(index);
2516 this._y = attribute.getY(index);
2517 this._z = attribute.getZ(index);
2518 this._w = attribute.getW(index);
2522 _proto._onChange = function _onChange(callback) {
2523 this._onChangeCallback = callback;
2527 _proto._onChangeCallback = function _onChangeCallback() {};
2529 _createClass(Quaternion, [{
2531 get: function get() {
2534 set: function set(value) {
2537 this._onChangeCallback();
2541 get: function get() {
2544 set: function set(value) {
2547 this._onChangeCallback();
2551 get: function get() {
2554 set: function set(value) {
2557 this._onChangeCallback();
2561 get: function get() {
2564 set: function set(value) {
2567 this._onChangeCallback();
2574 var Vector3 = /*#__PURE__*/function () {
2575 function Vector3(x, y, z) {
2588 Object.defineProperty(this, 'isVector3', {
2596 var _proto = Vector3.prototype;
2598 _proto.set = function set(x, y, z) {
2599 if (z === undefined) z = this.z; // sprite.scale.set(x,y)
2607 _proto.setScalar = function setScalar(scalar) {
2614 _proto.setX = function setX(x) {
2619 _proto.setY = function setY(y) {
2624 _proto.setZ = function setZ(z) {
2629 _proto.setComponent = function setComponent(index, value) {
2644 throw new Error('index is out of range: ' + index);
2650 _proto.getComponent = function getComponent(index) {
2662 throw new Error('index is out of range: ' + index);
2666 _proto.clone = function clone() {
2667 return new this.constructor(this.x, this.y, this.z);
2670 _proto.copy = function copy(v) {
2677 _proto.add = function add(v, w) {
2678 if (w !== undefined) {
2679 console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
2680 return this.addVectors(v, w);
2689 _proto.addScalar = function addScalar(s) {
2696 _proto.addVectors = function addVectors(a, b) {
2703 _proto.addScaledVector = function addScaledVector(v, s) {
2710 _proto.sub = function sub(v, w) {
2711 if (w !== undefined) {
2712 console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
2713 return this.subVectors(v, w);
2722 _proto.subScalar = function subScalar(s) {
2729 _proto.subVectors = function subVectors(a, b) {
2736 _proto.multiply = function multiply(v, w) {
2737 if (w !== undefined) {
2738 console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
2739 return this.multiplyVectors(v, w);
2748 _proto.multiplyScalar = function multiplyScalar(scalar) {
2755 _proto.multiplyVectors = function multiplyVectors(a, b) {
2762 _proto.applyEuler = function applyEuler(euler) {
2763 if (!(euler && euler.isEuler)) {
2764 console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
2767 return this.applyQuaternion(_quaternion.setFromEuler(euler));
2770 _proto.applyAxisAngle = function applyAxisAngle(axis, angle) {
2771 return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
2774 _proto.applyMatrix3 = function applyMatrix3(m) {
2779 this.x = e[0] * x + e[3] * y + e[6] * z;
2780 this.y = e[1] * x + e[4] * y + e[7] * z;
2781 this.z = e[2] * x + e[5] * y + e[8] * z;
2785 _proto.applyNormalMatrix = function applyNormalMatrix(m) {
2786 return this.applyMatrix3(m).normalize();
2789 _proto.applyMatrix4 = function applyMatrix4(m) {
2794 var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
2795 this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
2796 this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
2797 this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
2801 _proto.applyQuaternion = function applyQuaternion(q) {
2808 qw = q.w; // calculate quat * vector
2810 var ix = qw * x + qy * z - qz * y;
2811 var iy = qw * y + qz * x - qx * z;
2812 var iz = qw * z + qx * y - qy * x;
2813 var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
2815 this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
2816 this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
2817 this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
2821 _proto.project = function project(camera) {
2822 return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
2825 _proto.unproject = function unproject(camera) {
2826 return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
2829 _proto.transformDirection = function transformDirection(m) {
2830 // input: THREE.Matrix4 affine matrix
2831 // vector interpreted as a direction
2836 this.x = e[0] * x + e[4] * y + e[8] * z;
2837 this.y = e[1] * x + e[5] * y + e[9] * z;
2838 this.z = e[2] * x + e[6] * y + e[10] * z;
2839 return this.normalize();
2842 _proto.divide = function divide(v) {
2849 _proto.divideScalar = function divideScalar(scalar) {
2850 return this.multiplyScalar(1 / scalar);
2853 _proto.min = function min(v) {
2854 this.x = Math.min(this.x, v.x);
2855 this.y = Math.min(this.y, v.y);
2856 this.z = Math.min(this.z, v.z);
2860 _proto.max = function max(v) {
2861 this.x = Math.max(this.x, v.x);
2862 this.y = Math.max(this.y, v.y);
2863 this.z = Math.max(this.z, v.z);
2867 _proto.clamp = function clamp(min, max) {
2868 // assumes min < max, componentwise
2869 this.x = Math.max(min.x, Math.min(max.x, this.x));
2870 this.y = Math.max(min.y, Math.min(max.y, this.y));
2871 this.z = Math.max(min.z, Math.min(max.z, this.z));
2875 _proto.clampScalar = function clampScalar(minVal, maxVal) {
2876 this.x = Math.max(minVal, Math.min(maxVal, this.x));
2877 this.y = Math.max(minVal, Math.min(maxVal, this.y));
2878 this.z = Math.max(minVal, Math.min(maxVal, this.z));
2882 _proto.clampLength = function clampLength(min, max) {
2883 var length = this.length();
2884 return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
2887 _proto.floor = function floor() {
2888 this.x = Math.floor(this.x);
2889 this.y = Math.floor(this.y);
2890 this.z = Math.floor(this.z);
2894 _proto.ceil = function ceil() {
2895 this.x = Math.ceil(this.x);
2896 this.y = Math.ceil(this.y);
2897 this.z = Math.ceil(this.z);
2901 _proto.round = function round() {
2902 this.x = Math.round(this.x);
2903 this.y = Math.round(this.y);
2904 this.z = Math.round(this.z);
2908 _proto.roundToZero = function roundToZero() {
2909 this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
2910 this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
2911 this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
2915 _proto.negate = function negate() {
2922 _proto.dot = function dot(v) {
2923 return this.x * v.x + this.y * v.y + this.z * v.z;
2924 } // TODO lengthSquared?
2927 _proto.lengthSq = function lengthSq() {
2928 return this.x * this.x + this.y * this.y + this.z * this.z;
2931 _proto.length = function length() {
2932 return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
2935 _proto.manhattanLength = function manhattanLength() {
2936 return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
2939 _proto.normalize = function normalize() {
2940 return this.divideScalar(this.length() || 1);
2943 _proto.setLength = function setLength(length) {
2944 return this.normalize().multiplyScalar(length);
2947 _proto.lerp = function lerp(v, alpha) {
2948 this.x += (v.x - this.x) * alpha;
2949 this.y += (v.y - this.y) * alpha;
2950 this.z += (v.z - this.z) * alpha;
2954 _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
2955 this.x = v1.x + (v2.x - v1.x) * alpha;
2956 this.y = v1.y + (v2.y - v1.y) * alpha;
2957 this.z = v1.z + (v2.z - v1.z) * alpha;
2961 _proto.cross = function cross(v, w) {
2962 if (w !== undefined) {
2963 console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
2964 return this.crossVectors(v, w);
2967 return this.crossVectors(this, v);
2970 _proto.crossVectors = function crossVectors(a, b) {
2977 this.x = ay * bz - az * by;
2978 this.y = az * bx - ax * bz;
2979 this.z = ax * by - ay * bx;
2983 _proto.projectOnVector = function projectOnVector(v) {
2984 var denominator = v.lengthSq();
2985 if (denominator === 0) return this.set(0, 0, 0);
2986 var scalar = v.dot(this) / denominator;
2987 return this.copy(v).multiplyScalar(scalar);
2990 _proto.projectOnPlane = function projectOnPlane(planeNormal) {
2991 _vector.copy(this).projectOnVector(planeNormal);
2993 return this.sub(_vector);
2996 _proto.reflect = function reflect(normal) {
2997 // reflect incident vector off plane orthogonal to normal
2998 // normal is assumed to have unit length
2999 return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
3002 _proto.angleTo = function angleTo(v) {
3003 var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
3004 if (denominator === 0) return Math.PI / 2;
3005 var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
3007 return Math.acos(MathUtils.clamp(theta, -1, 1));
3010 _proto.distanceTo = function distanceTo(v) {
3011 return Math.sqrt(this.distanceToSquared(v));
3014 _proto.distanceToSquared = function distanceToSquared(v) {
3015 var dx = this.x - v.x,
3018 return dx * dx + dy * dy + dz * dz;
3021 _proto.manhattanDistanceTo = function manhattanDistanceTo(v) {
3022 return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
3025 _proto.setFromSpherical = function setFromSpherical(s) {
3026 return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
3029 _proto.setFromSphericalCoords = function setFromSphericalCoords(radius, phi, theta) {
3030 var sinPhiRadius = Math.sin(phi) * radius;
3031 this.x = sinPhiRadius * Math.sin(theta);
3032 this.y = Math.cos(phi) * radius;
3033 this.z = sinPhiRadius * Math.cos(theta);
3037 _proto.setFromCylindrical = function setFromCylindrical(c) {
3038 return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
3041 _proto.setFromCylindricalCoords = function setFromCylindricalCoords(radius, theta, y) {
3042 this.x = radius * Math.sin(theta);
3044 this.z = radius * Math.cos(theta);
3048 _proto.setFromMatrixPosition = function setFromMatrixPosition(m) {
3056 _proto.setFromMatrixScale = function setFromMatrixScale(m) {
3057 var sx = this.setFromMatrixColumn(m, 0).length();
3058 var sy = this.setFromMatrixColumn(m, 1).length();
3059 var sz = this.setFromMatrixColumn(m, 2).length();
3066 _proto.setFromMatrixColumn = function setFromMatrixColumn(m, index) {
3067 return this.fromArray(m.elements, index * 4);
3070 _proto.setFromMatrix3Column = function setFromMatrix3Column(m, index) {
3071 return this.fromArray(m.elements, index * 3);
3074 _proto.equals = function equals(v) {
3075 return v.x === this.x && v.y === this.y && v.z === this.z;
3078 _proto.fromArray = function fromArray(array, offset) {
3079 if (offset === void 0) {
3083 this.x = array[offset];
3084 this.y = array[offset + 1];
3085 this.z = array[offset + 2];
3089 _proto.toArray = function toArray(array, offset) {
3090 if (array === void 0) {
3094 if (offset === void 0) {
3098 array[offset] = this.x;
3099 array[offset + 1] = this.y;
3100 array[offset + 2] = this.z;
3104 _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
3105 if (offset !== undefined) {
3106 console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
3109 this.x = attribute.getX(index);
3110 this.y = attribute.getY(index);
3111 this.z = attribute.getZ(index);
3115 _proto.random = function random() {
3116 this.x = Math.random();
3117 this.y = Math.random();
3118 this.z = Math.random();
3125 var _vector = /*@__PURE__*/new Vector3();
3127 var _quaternion = /*@__PURE__*/new Quaternion();
3129 var Box3 = /*#__PURE__*/function () {
3130 function Box3(min, max) {
3131 Object.defineProperty(this, 'isBox3', {
3134 this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
3135 this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
3138 var _proto = Box3.prototype;
3140 _proto.set = function set(min, max) {
3146 _proto.setFromArray = function setFromArray(array) {
3147 var minX = +Infinity;
3148 var minY = +Infinity;
3149 var minZ = +Infinity;
3150 var maxX = -Infinity;
3151 var maxY = -Infinity;
3152 var maxZ = -Infinity;
3154 for (var i = 0, l = array.length; i < l; i += 3) {
3156 var y = array[i + 1];
3157 var z = array[i + 2];
3158 if (x < minX) minX = x;
3159 if (y < minY) minY = y;
3160 if (z < minZ) minZ = z;
3161 if (x > maxX) maxX = x;
3162 if (y > maxY) maxY = y;
3163 if (z > maxZ) maxZ = z;
3166 this.min.set(minX, minY, minZ);
3167 this.max.set(maxX, maxY, maxZ);
3171 _proto.setFromBufferAttribute = function setFromBufferAttribute(attribute) {
3172 var minX = +Infinity;
3173 var minY = +Infinity;
3174 var minZ = +Infinity;
3175 var maxX = -Infinity;
3176 var maxY = -Infinity;
3177 var maxZ = -Infinity;
3179 for (var i = 0, l = attribute.count; i < l; i++) {
3180 var x = attribute.getX(i);
3181 var y = attribute.getY(i);
3182 var z = attribute.getZ(i);
3183 if (x < minX) minX = x;
3184 if (y < minY) minY = y;
3185 if (z < minZ) minZ = z;
3186 if (x > maxX) maxX = x;
3187 if (y > maxY) maxY = y;
3188 if (z > maxZ) maxZ = z;
3191 this.min.set(minX, minY, minZ);
3192 this.max.set(maxX, maxY, maxZ);
3196 _proto.setFromPoints = function setFromPoints(points) {
3199 for (var i = 0, il = points.length; i < il; i++) {
3200 this.expandByPoint(points[i]);
3206 _proto.setFromCenterAndSize = function setFromCenterAndSize(center, size) {
3207 var halfSize = _vector$1.copy(size).multiplyScalar(0.5);
3209 this.min.copy(center).sub(halfSize);
3210 this.max.copy(center).add(halfSize);
3214 _proto.setFromObject = function setFromObject(object) {
3216 return this.expandByObject(object);
3219 _proto.clone = function clone() {
3220 return new this.constructor().copy(this);
3223 _proto.copy = function copy(box) {
3224 this.min.copy(box.min);
3225 this.max.copy(box.max);
3229 _proto.makeEmpty = function makeEmpty() {
3230 this.min.x = this.min.y = this.min.z = +Infinity;
3231 this.max.x = this.max.y = this.max.z = -Infinity;
3235 _proto.isEmpty = function isEmpty() {
3236 // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
3237 return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
3240 _proto.getCenter = function getCenter(target) {
3241 if (target === undefined) {
3242 console.warn('THREE.Box3: .getCenter() target is now required');
3243 target = new Vector3();
3246 return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
3249 _proto.getSize = function getSize(target) {
3250 if (target === undefined) {
3251 console.warn('THREE.Box3: .getSize() target is now required');
3252 target = new Vector3();
3255 return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
3258 _proto.expandByPoint = function expandByPoint(point) {
3259 this.min.min(point);
3260 this.max.max(point);
3264 _proto.expandByVector = function expandByVector(vector) {
3265 this.min.sub(vector);
3266 this.max.add(vector);
3270 _proto.expandByScalar = function expandByScalar(scalar) {
3271 this.min.addScalar(-scalar);
3272 this.max.addScalar(scalar);
3276 _proto.expandByObject = function expandByObject(object) {
3277 // Computes the world-axis-aligned bounding box of an object (including its children),
3278 // accounting for both the object's, and children's, world transforms
3279 object.updateWorldMatrix(false, false);
3280 var geometry = object.geometry;
3282 if (geometry !== undefined) {
3283 if (geometry.boundingBox === null) {
3284 geometry.computeBoundingBox();
3287 _box.copy(geometry.boundingBox);
3289 _box.applyMatrix4(object.matrixWorld);
3294 var children = object.children;
3296 for (var i = 0, l = children.length; i < l; i++) {
3297 this.expandByObject(children[i]);
3303 _proto.containsPoint = function containsPoint(point) {
3304 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;
3307 _proto.containsBox = function containsBox(box) {
3308 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;
3311 _proto.getParameter = function getParameter(point, target) {
3312 // This can potentially have a divide by zero if the box
3313 // has a size dimension of 0.
3314 if (target === undefined) {
3315 console.warn('THREE.Box3: .getParameter() target is now required');
3316 target = new Vector3();
3319 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));
3322 _proto.intersectsBox = function intersectsBox(box) {
3323 // using 6 splitting planes to rule out intersections.
3324 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;
3327 _proto.intersectsSphere = function intersectsSphere(sphere) {
3328 // Find the point on the AABB closest to the sphere center.
3329 this.clampPoint(sphere.center, _vector$1); // If that point is inside the sphere, the AABB and sphere intersect.
3331 return _vector$1.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
3334 _proto.intersectsPlane = function intersectsPlane(plane) {
3335 // We compute the minimum and maximum dot product values. If those values
3336 // are on the same side (back or front) of the plane, then there is no intersection.
3339 if (plane.normal.x > 0) {
3340 min = plane.normal.x * this.min.x;
3341 max = plane.normal.x * this.max.x;
3343 min = plane.normal.x * this.max.x;
3344 max = plane.normal.x * this.min.x;
3347 if (plane.normal.y > 0) {
3348 min += plane.normal.y * this.min.y;
3349 max += plane.normal.y * this.max.y;
3351 min += plane.normal.y * this.max.y;
3352 max += plane.normal.y * this.min.y;
3355 if (plane.normal.z > 0) {
3356 min += plane.normal.z * this.min.z;
3357 max += plane.normal.z * this.max.z;
3359 min += plane.normal.z * this.max.z;
3360 max += plane.normal.z * this.min.z;
3363 return min <= -plane.constant && max >= -plane.constant;
3366 _proto.intersectsTriangle = function intersectsTriangle(triangle) {
3367 if (this.isEmpty()) {
3369 } // compute box center and extents
3372 this.getCenter(_center);
3374 _extents.subVectors(this.max, _center); // translate triangle to aabb origin
3377 _v0.subVectors(triangle.a, _center);
3379 _v1.subVectors(triangle.b, _center);
3381 _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
3384 _f0.subVectors(_v1, _v0);
3386 _f1.subVectors(_v2, _v1);
3388 _f2.subVectors(_v0, _v2); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
3389 // 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
3390 // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
3393 var 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];
3395 if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
3397 } // test 3 face normals from the aabb
3400 axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
3402 if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
3404 } // finally testing the face normal of the triangle
3405 // use already existing triangle edge vectors here
3408 _triangleNormal.crossVectors(_f0, _f1);
3410 axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
3411 return satForAxes(axes, _v0, _v1, _v2, _extents);
3414 _proto.clampPoint = function clampPoint(point, target) {
3415 if (target === undefined) {
3416 console.warn('THREE.Box3: .clampPoint() target is now required');
3417 target = new Vector3();
3420 return target.copy(point).clamp(this.min, this.max);
3423 _proto.distanceToPoint = function distanceToPoint(point) {
3424 var clampedPoint = _vector$1.copy(point).clamp(this.min, this.max);
3426 return clampedPoint.sub(point).length();
3429 _proto.getBoundingSphere = function getBoundingSphere(target) {
3430 if (target === undefined) {
3431 console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
3434 this.getCenter(target.center);
3435 target.radius = this.getSize(_vector$1).length() * 0.5;
3439 _proto.intersect = function intersect(box) {
3440 this.min.max(box.min);
3441 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.
3443 if (this.isEmpty()) this.makeEmpty();
3447 _proto.union = function union(box) {
3448 this.min.min(box.min);
3449 this.max.max(box.max);
3453 _proto.applyMatrix4 = function applyMatrix4(matrix) {
3454 // transform of empty box is an empty box.
3455 if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
3457 _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
3460 _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
3463 _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
3466 _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
3469 _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
3472 _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
3475 _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
3478 _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
3481 this.setFromPoints(_points);
3485 _proto.translate = function translate(offset) {
3486 this.min.add(offset);
3487 this.max.add(offset);
3491 _proto.equals = function equals(box) {
3492 return box.min.equals(this.min) && box.max.equals(this.max);
3498 function satForAxes(axes, v0, v1, v2, extents) {
3499 for (var i = 0, j = axes.length - 3; i <= j; i += 3) {
3500 _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
3503 var 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
3505 var p0 = v0.dot(_testAxis);
3506 var p1 = v1.dot(_testAxis);
3507 var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
3509 if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
3510 // points of the projected triangle are outside the projected half-length of the aabb
3511 // the axis is seperating and we can exit
3519 var _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()];
3521 var _vector$1 = /*@__PURE__*/new Vector3();
3523 var _box = /*@__PURE__*/new Box3(); // triangle centered vertices
3526 var _v0 = /*@__PURE__*/new Vector3();
3528 var _v1 = /*@__PURE__*/new Vector3();
3530 var _v2 = /*@__PURE__*/new Vector3(); // triangle edge vectors
3533 var _f0 = /*@__PURE__*/new Vector3();
3535 var _f1 = /*@__PURE__*/new Vector3();
3537 var _f2 = /*@__PURE__*/new Vector3();
3539 var _center = /*@__PURE__*/new Vector3();
3541 var _extents = /*@__PURE__*/new Vector3();
3543 var _triangleNormal = /*@__PURE__*/new Vector3();
3545 var _testAxis = /*@__PURE__*/new Vector3();
3547 var _box$1 = /*@__PURE__*/new Box3();
3549 var Sphere = /*#__PURE__*/function () {
3550 function Sphere(center, radius) {
3551 this.center = center !== undefined ? center : new Vector3();
3552 this.radius = radius !== undefined ? radius : -1;
3555 var _proto = Sphere.prototype;
3557 _proto.set = function set(center, radius) {
3558 this.center.copy(center);
3559 this.radius = radius;
3563 _proto.setFromPoints = function setFromPoints(points, optionalCenter) {
3564 var center = this.center;
3566 if (optionalCenter !== undefined) {
3567 center.copy(optionalCenter);
3569 _box$1.setFromPoints(points).getCenter(center);
3572 var maxRadiusSq = 0;
3574 for (var i = 0, il = points.length; i < il; i++) {
3575 maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
3578 this.radius = Math.sqrt(maxRadiusSq);
3582 _proto.clone = function clone() {
3583 return new this.constructor().copy(this);
3586 _proto.copy = function copy(sphere) {
3587 this.center.copy(sphere.center);
3588 this.radius = sphere.radius;
3592 _proto.isEmpty = function isEmpty() {
3593 return this.radius < 0;
3596 _proto.makeEmpty = function makeEmpty() {
3597 this.center.set(0, 0, 0);
3602 _proto.containsPoint = function containsPoint(point) {
3603 return point.distanceToSquared(this.center) <= this.radius * this.radius;
3606 _proto.distanceToPoint = function distanceToPoint(point) {
3607 return point.distanceTo(this.center) - this.radius;
3610 _proto.intersectsSphere = function intersectsSphere(sphere) {
3611 var radiusSum = this.radius + sphere.radius;
3612 return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
3615 _proto.intersectsBox = function intersectsBox(box) {
3616 return box.intersectsSphere(this);
3619 _proto.intersectsPlane = function intersectsPlane(plane) {
3620 return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
3623 _proto.clampPoint = function clampPoint(point, target) {
3624 var deltaLengthSq = this.center.distanceToSquared(point);
3626 if (target === undefined) {
3627 console.warn('THREE.Sphere: .clampPoint() target is now required');
3628 target = new Vector3();
3633 if (deltaLengthSq > this.radius * this.radius) {
3634 target.sub(this.center).normalize();
3635 target.multiplyScalar(this.radius).add(this.center);
3641 _proto.getBoundingBox = function getBoundingBox(target) {
3642 if (target === undefined) {
3643 console.warn('THREE.Sphere: .getBoundingBox() target is now required');
3644 target = new Box3();
3647 if (this.isEmpty()) {
3648 // Empty sphere produces empty bounding box
3653 target.set(this.center, this.center);
3654 target.expandByScalar(this.radius);
3658 _proto.applyMatrix4 = function applyMatrix4(matrix) {
3659 this.center.applyMatrix4(matrix);
3660 this.radius = this.radius * matrix.getMaxScaleOnAxis();
3664 _proto.translate = function translate(offset) {
3665 this.center.add(offset);
3669 _proto.equals = function equals(sphere) {
3670 return sphere.center.equals(this.center) && sphere.radius === this.radius;
3676 var _vector$2 = /*@__PURE__*/new Vector3();
3678 var _segCenter = /*@__PURE__*/new Vector3();
3680 var _segDir = /*@__PURE__*/new Vector3();
3682 var _diff = /*@__PURE__*/new Vector3();
3684 var _edge1 = /*@__PURE__*/new Vector3();
3686 var _edge2 = /*@__PURE__*/new Vector3();
3688 var _normal = /*@__PURE__*/new Vector3();
3690 var Ray = /*#__PURE__*/function () {
3691 function Ray(origin, direction) {
3692 this.origin = origin !== undefined ? origin : new Vector3();
3693 this.direction = direction !== undefined ? direction : new Vector3(0, 0, -1);
3696 var _proto = Ray.prototype;
3698 _proto.set = function set(origin, direction) {
3699 this.origin.copy(origin);
3700 this.direction.copy(direction);
3704 _proto.clone = function clone() {
3705 return new this.constructor().copy(this);
3708 _proto.copy = function copy(ray) {
3709 this.origin.copy(ray.origin);
3710 this.direction.copy(ray.direction);
3714 _proto.at = function at(t, target) {
3715 if (target === undefined) {
3716 console.warn('THREE.Ray: .at() target is now required');
3717 target = new Vector3();
3720 return target.copy(this.direction).multiplyScalar(t).add(this.origin);
3723 _proto.lookAt = function lookAt(v) {
3724 this.direction.copy(v).sub(this.origin).normalize();
3728 _proto.recast = function recast(t) {
3729 this.origin.copy(this.at(t, _vector$2));
3733 _proto.closestPointToPoint = function closestPointToPoint(point, target) {
3734 if (target === undefined) {
3735 console.warn('THREE.Ray: .closestPointToPoint() target is now required');
3736 target = new Vector3();
3739 target.subVectors(point, this.origin);
3740 var directionDistance = target.dot(this.direction);
3742 if (directionDistance < 0) {
3743 return target.copy(this.origin);
3746 return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
3749 _proto.distanceToPoint = function distanceToPoint(point) {
3750 return Math.sqrt(this.distanceSqToPoint(point));
3753 _proto.distanceSqToPoint = function distanceSqToPoint(point) {
3754 var directionDistance = _vector$2.subVectors(point, this.origin).dot(this.direction); // point behind the ray
3757 if (directionDistance < 0) {
3758 return this.origin.distanceToSquared(point);
3761 _vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
3763 return _vector$2.distanceToSquared(point);
3766 _proto.distanceSqToSegment = function distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
3767 // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
3768 // It returns the min distance between the ray and the segment
3769 // defined by v0 and v1
3770 // It can also set two optional targets :
3771 // - The closest point on the ray
3772 // - The closest point on the segment
3773 _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
3775 _segDir.copy(v1).sub(v0).normalize();
3777 _diff.copy(this.origin).sub(_segCenter);
3779 var segExtent = v0.distanceTo(v1) * 0.5;
3780 var a01 = -this.direction.dot(_segDir);
3782 var b0 = _diff.dot(this.direction);
3784 var b1 = -_diff.dot(_segDir);
3786 var c = _diff.lengthSq();
3788 var det = Math.abs(1 - a01 * a01);
3789 var s0, s1, sqrDist, extDet;
3792 // The ray and segment are not parallel.
3795 extDet = segExtent * det;
3798 if (s1 >= -extDet) {
3801 // Minimum at interior points of ray and segment.
3802 var invDet = 1 / det;
3805 sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
3809 s0 = Math.max(0, -(a01 * s1 + b0));
3810 sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
3815 s0 = Math.max(0, -(a01 * s1 + b0));
3816 sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
3819 if (s1 <= -extDet) {
3821 s0 = Math.max(0, -(-a01 * segExtent + b0));
3822 s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
3823 sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
3824 } else if (s1 <= extDet) {
3827 s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
3828 sqrDist = s1 * (s1 + 2 * b1) + c;
3831 s0 = Math.max(0, -(a01 * segExtent + b0));
3832 s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
3833 sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
3837 // Ray and segment are parallel.
3838 s1 = a01 > 0 ? -segExtent : segExtent;
3839 s0 = Math.max(0, -(a01 * s1 + b0));
3840 sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
3843 if (optionalPointOnRay) {
3844 optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
3847 if (optionalPointOnSegment) {
3848 optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
3854 _proto.intersectSphere = function intersectSphere(sphere, target) {
3855 _vector$2.subVectors(sphere.center, this.origin);
3857 var tca = _vector$2.dot(this.direction);
3859 var d2 = _vector$2.dot(_vector$2) - tca * tca;
3860 var radius2 = sphere.radius * sphere.radius;
3861 if (d2 > radius2) return null;
3862 var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
3864 var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
3866 var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
3868 if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
3869 // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
3870 // in order to always return an intersect point that is in front of the ray.
3872 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
3874 return this.at(t0, target);
3877 _proto.intersectsSphere = function intersectsSphere(sphere) {
3878 return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
3881 _proto.distanceToPlane = function distanceToPlane(plane) {
3882 var denominator = plane.normal.dot(this.direction);
3884 if (denominator === 0) {
3885 // line is coplanar, return origin
3886 if (plane.distanceToPoint(this.origin) === 0) {
3888 } // Null is preferable to undefined since undefined means.... it is undefined
3894 var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
3896 return t >= 0 ? t : null;
3899 _proto.intersectPlane = function intersectPlane(plane, target) {
3900 var t = this.distanceToPlane(plane);
3906 return this.at(t, target);
3909 _proto.intersectsPlane = function intersectsPlane(plane) {
3910 // check if the ray lies on the plane first
3911 var distToPoint = plane.distanceToPoint(this.origin);
3913 if (distToPoint === 0) {
3917 var denominator = plane.normal.dot(this.direction);
3919 if (denominator * distToPoint < 0) {
3921 } // ray origin is behind the plane (and is pointing behind it)
3927 _proto.intersectBox = function intersectBox(box, target) {
3928 var tmin, tmax, tymin, tymax, tzmin, tzmax;
3929 var invdirx = 1 / this.direction.x,
3930 invdiry = 1 / this.direction.y,
3931 invdirz = 1 / this.direction.z;
3932 var origin = this.origin;
3935 tmin = (box.min.x - origin.x) * invdirx;
3936 tmax = (box.max.x - origin.x) * invdirx;
3938 tmin = (box.max.x - origin.x) * invdirx;
3939 tmax = (box.min.x - origin.x) * invdirx;
3943 tymin = (box.min.y - origin.y) * invdiry;
3944 tymax = (box.max.y - origin.y) * invdiry;
3946 tymin = (box.max.y - origin.y) * invdiry;
3947 tymax = (box.min.y - origin.y) * invdiry;
3950 if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
3951 // (result of 0 * Infinity). x !== x returns true if x is NaN
3953 if (tymin > tmin || tmin !== tmin) tmin = tymin;
3954 if (tymax < tmax || tmax !== tmax) tmax = tymax;
3957 tzmin = (box.min.z - origin.z) * invdirz;
3958 tzmax = (box.max.z - origin.z) * invdirz;
3960 tzmin = (box.max.z - origin.z) * invdirz;
3961 tzmax = (box.min.z - origin.z) * invdirz;
3964 if (tmin > tzmax || tzmin > tmax) return null;
3965 if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
3966 if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
3968 if (tmax < 0) return null;
3969 return this.at(tmin >= 0 ? tmin : tmax, target);
3972 _proto.intersectsBox = function intersectsBox(box) {
3973 return this.intersectBox(box, _vector$2) !== null;
3976 _proto.intersectTriangle = function intersectTriangle(a, b, c, backfaceCulling, target) {
3977 // Compute the offset origin, edges, and normal.
3978 // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
3979 _edge1.subVectors(b, a);
3981 _edge2.subVectors(c, a);
3983 _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
3984 // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
3985 // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
3986 // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
3987 // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
3990 var DdN = this.direction.dot(_normal);
3994 if (backfaceCulling) return null;
3996 } else if (DdN < 0) {
4003 _diff.subVectors(this.origin, a);
4005 var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
4011 var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
4015 } // b1+b2 > 1, no intersection
4018 if (DdQxE2 + DdE1xQ > DdN) {
4020 } // Line intersects triangle, check if ray does.
4023 var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
4028 } // Ray intersects triangle.
4031 return this.at(QdN / DdN, target);
4034 _proto.applyMatrix4 = function applyMatrix4(matrix4) {
4035 this.origin.applyMatrix4(matrix4);
4036 this.direction.transformDirection(matrix4);
4040 _proto.equals = function equals(ray) {
4041 return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
4047 var Matrix4 = /*#__PURE__*/function () {
4048 function Matrix4() {
4049 Object.defineProperty(this, 'isMatrix4', {
4052 this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
4054 if (arguments.length > 0) {
4055 console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
4059 var _proto = Matrix4.prototype;
4061 _proto.set = function set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
4062 var te = this.elements;
4082 _proto.identity = function identity() {
4083 this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
4087 _proto.clone = function clone() {
4088 return new Matrix4().fromArray(this.elements);
4091 _proto.copy = function copy(m) {
4092 var te = this.elements;
4093 var me = m.elements;
4113 _proto.copyPosition = function copyPosition(m) {
4114 var te = this.elements,
4122 _proto.extractBasis = function extractBasis(xAxis, yAxis, zAxis) {
4123 xAxis.setFromMatrixColumn(this, 0);
4124 yAxis.setFromMatrixColumn(this, 1);
4125 zAxis.setFromMatrixColumn(this, 2);
4129 _proto.makeBasis = function makeBasis(xAxis, yAxis, zAxis) {
4130 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);
4134 _proto.extractRotation = function extractRotation(m) {
4135 // this method does not support reflection matrices
4136 var te = this.elements;
4137 var me = m.elements;
4139 var scaleX = 1 / _v1$1.setFromMatrixColumn(m, 0).length();
4141 var scaleY = 1 / _v1$1.setFromMatrixColumn(m, 1).length();
4143 var scaleZ = 1 / _v1$1.setFromMatrixColumn(m, 2).length();
4145 te[0] = me[0] * scaleX;
4146 te[1] = me[1] * scaleX;
4147 te[2] = me[2] * scaleX;
4149 te[4] = me[4] * scaleY;
4150 te[5] = me[5] * scaleY;
4151 te[6] = me[6] * scaleY;
4153 te[8] = me[8] * scaleZ;
4154 te[9] = me[9] * scaleZ;
4155 te[10] = me[10] * scaleZ;
4164 _proto.makeRotationFromEuler = function makeRotationFromEuler(euler) {
4165 if (!(euler && euler.isEuler)) {
4166 console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
4169 var te = this.elements;
4173 var a = Math.cos(x),
4175 var c = Math.cos(y),
4177 var e = Math.cos(z),
4180 if (euler.order === 'XYZ') {
4188 te[1] = af + be * d;
4189 te[5] = ae - bf * d;
4191 te[2] = bf - ae * d;
4192 te[6] = be + af * d;
4194 } else if (euler.order === 'YXZ') {
4199 te[0] = ce + df * b;
4200 te[4] = de * b - cf;
4205 te[2] = cf * b - de;
4206 te[6] = df + ce * b;
4208 } else if (euler.order === 'ZXY') {
4214 te[0] = _ce - _df * b;
4216 te[8] = _de + _cf * b;
4217 te[1] = _cf + _de * b;
4219 te[9] = _df - _ce * b;
4223 } else if (euler.order === 'ZYX') {
4230 te[4] = _be * d - _af;
4231 te[8] = _ae * d + _bf;
4233 te[5] = _bf * d + _ae;
4234 te[9] = _af * d - _be;
4238 } else if (euler.order === 'YZX') {
4244 te[4] = bd - ac * f;
4245 te[8] = bc * f + ad;
4250 te[6] = ad * f + bc;
4251 te[10] = ac - bd * f;
4252 } else if (euler.order === 'XZY') {
4261 te[1] = _ac * f + _bd;
4263 te[9] = _ad * f - _bc;
4264 te[2] = _bc * f - _ad;
4266 te[10] = _bd * f + _ac;
4272 te[11] = 0; // last column
4281 _proto.makeRotationFromQuaternion = function makeRotationFromQuaternion(q) {
4282 return this.compose(_zero, q, _one);
4285 _proto.lookAt = function lookAt(eye, target, up) {
4286 var te = this.elements;
4288 _z.subVectors(eye, target);
4290 if (_z.lengthSq() === 0) {
4291 // eye and target are in the same position
4297 _x.crossVectors(up, _z);
4299 if (_x.lengthSq() === 0) {
4300 // up and z are parallel
4301 if (Math.abs(up.z) === 1) {
4309 _x.crossVectors(up, _z);
4314 _y.crossVectors(_z, _x);
4328 _proto.multiply = function multiply(m, n) {
4329 if (n !== undefined) {
4330 console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
4331 return this.multiplyMatrices(m, n);
4334 return this.multiplyMatrices(this, m);
4337 _proto.premultiply = function premultiply(m) {
4338 return this.multiplyMatrices(m, this);
4341 _proto.multiplyMatrices = function multiplyMatrices(a, b) {
4342 var ae = a.elements;
4343 var be = b.elements;
4344 var te = this.elements;
4377 te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
4378 te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
4379 te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
4380 te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
4381 te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
4382 te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
4383 te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
4384 te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
4385 te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
4386 te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
4387 te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
4388 te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
4389 te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
4390 te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
4391 te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
4392 te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
4396 _proto.multiplyScalar = function multiplyScalar(s) {
4397 var te = this.elements;
4417 _proto.determinant = function determinant() {
4418 var te = this.elements;
4434 n44 = te[15]; //TODO: make this more efficient
4435 //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
4437 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);
4440 _proto.transpose = function transpose() {
4441 var te = this.elements;
4464 _proto.setPosition = function setPosition(x, y, z) {
4465 var te = this.elements;
4480 _proto.invert = function invert() {
4481 // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
4482 var te = this.elements,
4499 t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
4500 t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
4501 t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
4502 t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
4503 var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
4504 if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
4505 var detInv = 1 / det;
4506 te[0] = t11 * detInv;
4507 te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
4508 te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
4509 te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
4510 te[4] = t12 * detInv;
4511 te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
4512 te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
4513 te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
4514 te[8] = t13 * detInv;
4515 te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
4516 te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
4517 te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
4518 te[12] = t14 * detInv;
4519 te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
4520 te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
4521 te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
4525 _proto.scale = function scale(v) {
4526 var te = this.elements;
4545 _proto.getMaxScaleOnAxis = function getMaxScaleOnAxis() {
4546 var te = this.elements;
4547 var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
4548 var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
4549 var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
4550 return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
4553 _proto.makeTranslation = function makeTranslation(x, y, z) {
4554 this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
4558 _proto.makeRotationX = function makeRotationX(theta) {
4559 var c = Math.cos(theta),
4560 s = Math.sin(theta);
4561 this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
4565 _proto.makeRotationY = function makeRotationY(theta) {
4566 var c = Math.cos(theta),
4567 s = Math.sin(theta);
4568 this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
4572 _proto.makeRotationZ = function makeRotationZ(theta) {
4573 var c = Math.cos(theta),
4574 s = Math.sin(theta);
4575 this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
4579 _proto.makeRotationAxis = function makeRotationAxis(axis, angle) {
4580 // Based on http://www.gamedev.net/reference/articles/article1199.asp
4581 var c = Math.cos(angle);
4582 var s = Math.sin(angle);
4589 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);
4593 _proto.makeScale = function makeScale(x, y, z) {
4594 this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
4598 _proto.makeShear = function makeShear(x, y, z) {
4599 this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
4603 _proto.compose = function compose(position, quaternion, scale) {
4604 var te = this.elements;
4605 var x = quaternion._x,
4624 te[0] = (1 - (yy + zz)) * sx;
4625 te[1] = (xy + wz) * sx;
4626 te[2] = (xz - wy) * sx;
4628 te[4] = (xy - wz) * sy;
4629 te[5] = (1 - (xx + zz)) * sy;
4630 te[6] = (yz + wx) * sy;
4632 te[8] = (xz + wy) * sz;
4633 te[9] = (yz - wx) * sz;
4634 te[10] = (1 - (xx + yy)) * sz;
4636 te[12] = position.x;
4637 te[13] = position.y;
4638 te[14] = position.z;
4643 _proto.decompose = function decompose(position, quaternion, scale) {
4644 var te = this.elements;
4646 var sx = _v1$1.set(te[0], te[1], te[2]).length();
4648 var sy = _v1$1.set(te[4], te[5], te[6]).length();
4650 var sz = _v1$1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
4653 var det = this.determinant();
4654 if (det < 0) sx = -sx;
4655 position.x = te[12];
4656 position.y = te[13];
4657 position.z = te[14]; // scale the rotation part
4664 _m1.elements[0] *= invSX;
4665 _m1.elements[1] *= invSX;
4666 _m1.elements[2] *= invSX;
4667 _m1.elements[4] *= invSY;
4668 _m1.elements[5] *= invSY;
4669 _m1.elements[6] *= invSY;
4670 _m1.elements[8] *= invSZ;
4671 _m1.elements[9] *= invSZ;
4672 _m1.elements[10] *= invSZ;
4673 quaternion.setFromRotationMatrix(_m1);
4680 _proto.makePerspective = function makePerspective(left, right, top, bottom, near, far) {
4681 if (far === undefined) {
4682 console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
4685 var te = this.elements;
4686 var x = 2 * near / (right - left);
4687 var y = 2 * near / (top - bottom);
4688 var a = (right + left) / (right - left);
4689 var b = (top + bottom) / (top - bottom);
4690 var c = -(far + near) / (far - near);
4691 var d = -2 * far * near / (far - near);
4711 _proto.makeOrthographic = function makeOrthographic(left, right, top, bottom, near, far) {
4712 var te = this.elements;
4713 var w = 1.0 / (right - left);
4714 var h = 1.0 / (top - bottom);
4715 var p = 1.0 / (far - near);
4716 var x = (right + left) * w;
4717 var y = (top + bottom) * h;
4718 var z = (far + near) * p;
4738 _proto.equals = function equals(matrix) {
4739 var te = this.elements;
4740 var me = matrix.elements;
4742 for (var i = 0; i < 16; i++) {
4743 if (te[i] !== me[i]) return false;
4749 _proto.fromArray = function fromArray(array, offset) {
4750 if (offset === void 0) {
4754 for (var i = 0; i < 16; i++) {
4755 this.elements[i] = array[i + offset];
4761 _proto.toArray = function toArray(array, offset) {
4762 if (array === void 0) {
4766 if (offset === void 0) {
4770 var te = this.elements;
4771 array[offset] = te[0];
4772 array[offset + 1] = te[1];
4773 array[offset + 2] = te[2];
4774 array[offset + 3] = te[3];
4775 array[offset + 4] = te[4];
4776 array[offset + 5] = te[5];
4777 array[offset + 6] = te[6];
4778 array[offset + 7] = te[7];
4779 array[offset + 8] = te[8];
4780 array[offset + 9] = te[9];
4781 array[offset + 10] = te[10];
4782 array[offset + 11] = te[11];
4783 array[offset + 12] = te[12];
4784 array[offset + 13] = te[13];
4785 array[offset + 14] = te[14];
4786 array[offset + 15] = te[15];
4793 var _v1$1 = /*@__PURE__*/new Vector3();
4795 var _m1 = /*@__PURE__*/new Matrix4();
4797 var _zero = /*@__PURE__*/new Vector3(0, 0, 0);
4799 var _one = /*@__PURE__*/new Vector3(1, 1, 1);
4801 var _x = /*@__PURE__*/new Vector3();
4803 var _y = /*@__PURE__*/new Vector3();
4805 var _z = /*@__PURE__*/new Vector3();
4807 var Euler = /*#__PURE__*/function () {
4808 function Euler(x, y, z, order) {
4821 if (order === void 0) {
4822 order = Euler.DefaultOrder;
4825 Object.defineProperty(this, 'isEuler', {
4831 this._order = order;
4834 var _proto = Euler.prototype;
4836 _proto.set = function set(x, y, z, order) {
4840 this._order = order || this._order;
4842 this._onChangeCallback();
4847 _proto.clone = function clone() {
4848 return new this.constructor(this._x, this._y, this._z, this._order);
4851 _proto.copy = function copy(euler) {
4855 this._order = euler._order;
4857 this._onChangeCallback();
4862 _proto.setFromRotationMatrix = function setFromRotationMatrix(m, order, update) {
4863 var clamp = MathUtils.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
4865 var te = m.elements;
4875 order = order || this._order;
4879 this._y = Math.asin(clamp(m13, -1, 1));
4881 if (Math.abs(m13) < 0.9999999) {
4882 this._x = Math.atan2(-m23, m33);
4883 this._z = Math.atan2(-m12, m11);
4885 this._x = Math.atan2(m32, m22);
4892 this._x = Math.asin(-clamp(m23, -1, 1));
4894 if (Math.abs(m23) < 0.9999999) {
4895 this._y = Math.atan2(m13, m33);
4896 this._z = Math.atan2(m21, m22);
4898 this._y = Math.atan2(-m31, m11);
4905 this._x = Math.asin(clamp(m32, -1, 1));
4907 if (Math.abs(m32) < 0.9999999) {
4908 this._y = Math.atan2(-m31, m33);
4909 this._z = Math.atan2(-m12, m22);
4912 this._z = Math.atan2(m21, m11);
4918 this._y = Math.asin(-clamp(m31, -1, 1));
4920 if (Math.abs(m31) < 0.9999999) {
4921 this._x = Math.atan2(m32, m33);
4922 this._z = Math.atan2(m21, m11);
4925 this._z = Math.atan2(-m12, m22);
4931 this._z = Math.asin(clamp(m21, -1, 1));
4933 if (Math.abs(m21) < 0.9999999) {
4934 this._x = Math.atan2(-m23, m22);
4935 this._y = Math.atan2(-m31, m11);
4938 this._y = Math.atan2(m13, m33);
4944 this._z = Math.asin(-clamp(m12, -1, 1));
4946 if (Math.abs(m12) < 0.9999999) {
4947 this._x = Math.atan2(m32, m22);
4948 this._y = Math.atan2(m13, m11);
4950 this._x = Math.atan2(-m23, m33);
4957 console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
4960 this._order = order;
4961 if (update !== false) this._onChangeCallback();
4965 _proto.setFromQuaternion = function setFromQuaternion(q, order, update) {
4966 _matrix.makeRotationFromQuaternion(q);
4968 return this.setFromRotationMatrix(_matrix, order, update);
4971 _proto.setFromVector3 = function setFromVector3(v, order) {
4972 return this.set(v.x, v.y, v.z, order || this._order);
4975 _proto.reorder = function reorder(newOrder) {
4976 // WARNING: this discards revolution information -bhouston
4977 _quaternion$1.setFromEuler(this);
4979 return this.setFromQuaternion(_quaternion$1, newOrder);
4982 _proto.equals = function equals(euler) {
4983 return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
4986 _proto.fromArray = function fromArray(array) {
4990 if (array[3] !== undefined) this._order = array[3];
4992 this._onChangeCallback();
4997 _proto.toArray = function toArray(array, offset) {
4998 if (array === void 0) {
5002 if (offset === void 0) {
5006 array[offset] = this._x;
5007 array[offset + 1] = this._y;
5008 array[offset + 2] = this._z;
5009 array[offset + 3] = this._order;
5013 _proto.toVector3 = function toVector3(optionalResult) {
5014 if (optionalResult) {
5015 return optionalResult.set(this._x, this._y, this._z);
5017 return new Vector3(this._x, this._y, this._z);
5021 _proto._onChange = function _onChange(callback) {
5022 this._onChangeCallback = callback;
5026 _proto._onChangeCallback = function _onChangeCallback() {};
5028 _createClass(Euler, [{
5030 get: function get() {
5033 set: function set(value) {
5036 this._onChangeCallback();
5040 get: function get() {
5043 set: function set(value) {
5046 this._onChangeCallback();
5050 get: function get() {
5053 set: function set(value) {
5056 this._onChangeCallback();
5060 get: function get() {
5063 set: function set(value) {
5064 this._order = value;
5066 this._onChangeCallback();
5073 Euler.DefaultOrder = 'XYZ';
5074 Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
5076 var _matrix = /*@__PURE__*/new Matrix4();
5078 var _quaternion$1 = /*@__PURE__*/new Quaternion();
5080 var Layers = /*#__PURE__*/function () {
5085 var _proto = Layers.prototype;
5087 _proto.set = function set(channel) {
5088 this.mask = 1 << channel | 0;
5091 _proto.enable = function enable(channel) {
5092 this.mask |= 1 << channel | 0;
5095 _proto.enableAll = function enableAll() {
5096 this.mask = 0xffffffff | 0;
5099 _proto.toggle = function toggle(channel) {
5100 this.mask ^= 1 << channel | 0;
5103 _proto.disable = function disable(channel) {
5104 this.mask &= ~(1 << channel | 0);
5107 _proto.disableAll = function disableAll() {
5111 _proto.test = function test(layers) {
5112 return (this.mask & layers.mask) !== 0;
5118 var _object3DId = 0;
5120 var _v1$2 = new Vector3();
5122 var _q1 = new Quaternion();
5124 var _m1$1 = new Matrix4();
5126 var _target = new Vector3();
5128 var _position = new Vector3();
5130 var _scale = new Vector3();
5132 var _quaternion$2 = new Quaternion();
5134 var _xAxis = new Vector3(1, 0, 0);
5136 var _yAxis = new Vector3(0, 1, 0);
5138 var _zAxis = new Vector3(0, 0, 1);
5143 var _removedEvent = {
5147 function Object3D() {
5148 Object.defineProperty(this, 'id', {
5149 value: _object3DId++
5151 this.uuid = MathUtils.generateUUID();
5153 this.type = 'Object3D';
5156 this.up = Object3D.DefaultUp.clone();
5157 var position = new Vector3();
5158 var rotation = new Euler();
5159 var quaternion = new Quaternion();
5160 var scale = new Vector3(1, 1, 1);
5162 function onRotationChange() {
5163 quaternion.setFromEuler(rotation, false);
5166 function onQuaternionChange() {
5167 rotation.setFromQuaternion(quaternion, undefined, false);
5170 rotation._onChange(onRotationChange);
5172 quaternion._onChange(onQuaternionChange);
5174 Object.defineProperties(this, {
5196 value: new Matrix4()
5199 value: new Matrix3()
5202 this.matrix = new Matrix4();
5203 this.matrixWorld = new Matrix4();
5204 this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
5205 this.matrixWorldNeedsUpdate = false;
5206 this.layers = new Layers();
5207 this.visible = true;
5208 this.castShadow = false;
5209 this.receiveShadow = false;
5210 this.frustumCulled = true;
5211 this.renderOrder = 0;
5212 this.animations = [];
5216 Object3D.DefaultUp = new Vector3(0, 1, 0);
5217 Object3D.DefaultMatrixAutoUpdate = true;
5218 Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
5219 constructor: Object3D,
5221 onBeforeRender: function onBeforeRender() {},
5222 onAfterRender: function onAfterRender() {},
5223 applyMatrix4: function applyMatrix4(matrix) {
5224 if (this.matrixAutoUpdate) this.updateMatrix();
5225 this.matrix.premultiply(matrix);
5226 this.matrix.decompose(this.position, this.quaternion, this.scale);
5228 applyQuaternion: function applyQuaternion(q) {
5229 this.quaternion.premultiply(q);
5232 setRotationFromAxisAngle: function setRotationFromAxisAngle(axis, angle) {
5233 // assumes axis is normalized
5234 this.quaternion.setFromAxisAngle(axis, angle);
5236 setRotationFromEuler: function setRotationFromEuler(euler) {
5237 this.quaternion.setFromEuler(euler, true);
5239 setRotationFromMatrix: function setRotationFromMatrix(m) {
5240 // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
5241 this.quaternion.setFromRotationMatrix(m);
5243 setRotationFromQuaternion: function setRotationFromQuaternion(q) {
5244 // assumes q is normalized
5245 this.quaternion.copy(q);
5247 rotateOnAxis: function rotateOnAxis(axis, angle) {
5248 // rotate object on axis in object space
5249 // axis is assumed to be normalized
5250 _q1.setFromAxisAngle(axis, angle);
5252 this.quaternion.multiply(_q1);
5255 rotateOnWorldAxis: function rotateOnWorldAxis(axis, angle) {
5256 // rotate object on axis in world space
5257 // axis is assumed to be normalized
5258 // method assumes no rotated parent
5259 _q1.setFromAxisAngle(axis, angle);
5261 this.quaternion.premultiply(_q1);
5264 rotateX: function rotateX(angle) {
5265 return this.rotateOnAxis(_xAxis, angle);
5267 rotateY: function rotateY(angle) {
5268 return this.rotateOnAxis(_yAxis, angle);
5270 rotateZ: function rotateZ(angle) {
5271 return this.rotateOnAxis(_zAxis, angle);
5273 translateOnAxis: function translateOnAxis(axis, distance) {
5274 // translate object by distance along axis in object space
5275 // axis is assumed to be normalized
5276 _v1$2.copy(axis).applyQuaternion(this.quaternion);
5278 this.position.add(_v1$2.multiplyScalar(distance));
5281 translateX: function translateX(distance) {
5282 return this.translateOnAxis(_xAxis, distance);
5284 translateY: function translateY(distance) {
5285 return this.translateOnAxis(_yAxis, distance);
5287 translateZ: function translateZ(distance) {
5288 return this.translateOnAxis(_zAxis, distance);
5290 localToWorld: function localToWorld(vector) {
5291 return vector.applyMatrix4(this.matrixWorld);
5293 worldToLocal: function worldToLocal(vector) {
5294 return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
5296 lookAt: function lookAt(x, y, z) {
5297 // This method does not support objects having non-uniformly-scaled parent(s)
5301 _target.set(x, y, z);
5304 var parent = this.parent;
5305 this.updateWorldMatrix(true, false);
5307 _position.setFromMatrixPosition(this.matrixWorld);
5309 if (this.isCamera || this.isLight) {
5310 _m1$1.lookAt(_position, _target, this.up);
5312 _m1$1.lookAt(_target, _position, this.up);
5315 this.quaternion.setFromRotationMatrix(_m1$1);
5318 _m1$1.extractRotation(parent.matrixWorld);
5320 _q1.setFromRotationMatrix(_m1$1);
5322 this.quaternion.premultiply(_q1.invert());
5325 add: function add(object) {
5326 if (arguments.length > 1) {
5327 for (var i = 0; i < arguments.length; i++) {
5328 this.add(arguments[i]);
5334 if (object === this) {
5335 console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
5339 if (object && object.isObject3D) {
5340 if (object.parent !== null) {
5341 object.parent.remove(object);
5344 object.parent = this;
5345 this.children.push(object);
5346 object.dispatchEvent(_addedEvent);
5348 console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
5353 remove: function remove(object) {
5354 if (arguments.length > 1) {
5355 for (var i = 0; i < arguments.length; i++) {
5356 this.remove(arguments[i]);
5362 var index = this.children.indexOf(object);
5365 object.parent = null;
5366 this.children.splice(index, 1);
5367 object.dispatchEvent(_removedEvent);
5372 clear: function clear() {
5373 for (var i = 0; i < this.children.length; i++) {
5374 var object = this.children[i];
5375 object.parent = null;
5376 object.dispatchEvent(_removedEvent);
5379 this.children.length = 0;
5382 attach: function attach(object) {
5383 // adds object as a child of this, while maintaining the object's world transform
5384 this.updateWorldMatrix(true, false);
5386 _m1$1.copy(this.matrixWorld).invert();
5388 if (object.parent !== null) {
5389 object.parent.updateWorldMatrix(true, false);
5391 _m1$1.multiply(object.parent.matrixWorld);
5394 object.applyMatrix4(_m1$1);
5395 object.updateWorldMatrix(false, false);
5399 getObjectById: function getObjectById(id) {
5400 return this.getObjectByProperty('id', id);
5402 getObjectByName: function getObjectByName(name) {
5403 return this.getObjectByProperty('name', name);
5405 getObjectByProperty: function getObjectByProperty(name, value) {
5406 if (this[name] === value) return this;
5408 for (var i = 0, l = this.children.length; i < l; i++) {
5409 var child = this.children[i];
5410 var object = child.getObjectByProperty(name, value);
5412 if (object !== undefined) {
5419 getWorldPosition: function getWorldPosition(target) {
5420 if (target === undefined) {
5421 console.warn('THREE.Object3D: .getWorldPosition() target is now required');
5422 target = new Vector3();
5425 this.updateWorldMatrix(true, false);
5426 return target.setFromMatrixPosition(this.matrixWorld);
5428 getWorldQuaternion: function getWorldQuaternion(target) {
5429 if (target === undefined) {
5430 console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
5431 target = new Quaternion();
5434 this.updateWorldMatrix(true, false);
5435 this.matrixWorld.decompose(_position, target, _scale);
5438 getWorldScale: function getWorldScale(target) {
5439 if (target === undefined) {
5440 console.warn('THREE.Object3D: .getWorldScale() target is now required');
5441 target = new Vector3();
5444 this.updateWorldMatrix(true, false);
5445 this.matrixWorld.decompose(_position, _quaternion$2, target);
5448 getWorldDirection: function getWorldDirection(target) {
5449 if (target === undefined) {
5450 console.warn('THREE.Object3D: .getWorldDirection() target is now required');
5451 target = new Vector3();
5454 this.updateWorldMatrix(true, false);
5455 var e = this.matrixWorld.elements;
5456 return target.set(e[8], e[9], e[10]).normalize();
5458 raycast: function raycast() {},
5459 traverse: function traverse(callback) {
5461 var children = this.children;
5463 for (var i = 0, l = children.length; i < l; i++) {
5464 children[i].traverse(callback);
5467 traverseVisible: function traverseVisible(callback) {
5468 if (this.visible === false) return;
5470 var children = this.children;
5472 for (var i = 0, l = children.length; i < l; i++) {
5473 children[i].traverseVisible(callback);
5476 traverseAncestors: function traverseAncestors(callback) {
5477 var parent = this.parent;
5479 if (parent !== null) {
5481 parent.traverseAncestors(callback);
5484 updateMatrix: function updateMatrix() {
5485 this.matrix.compose(this.position, this.quaternion, this.scale);
5486 this.matrixWorldNeedsUpdate = true;
5488 updateMatrixWorld: function updateMatrixWorld(force) {
5489 if (this.matrixAutoUpdate) this.updateMatrix();
5491 if (this.matrixWorldNeedsUpdate || force) {
5492 if (this.parent === null) {
5493 this.matrixWorld.copy(this.matrix);
5495 this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
5498 this.matrixWorldNeedsUpdate = false;
5500 } // update children
5503 var children = this.children;
5505 for (var i = 0, l = children.length; i < l; i++) {
5506 children[i].updateMatrixWorld(force);
5509 updateWorldMatrix: function updateWorldMatrix(updateParents, updateChildren) {
5510 var parent = this.parent;
5512 if (updateParents === true && parent !== null) {
5513 parent.updateWorldMatrix(true, false);
5516 if (this.matrixAutoUpdate) this.updateMatrix();
5518 if (this.parent === null) {
5519 this.matrixWorld.copy(this.matrix);
5521 this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
5522 } // update children
5525 if (updateChildren === true) {
5526 var children = this.children;
5528 for (var i = 0, l = children.length; i < l; i++) {
5529 children[i].updateWorldMatrix(false, true);
5533 toJSON: function toJSON(meta) {
5534 // meta is a string when called from JSON.stringify
5535 var isRootObject = meta === undefined || typeof meta === 'string';
5536 var output = {}; // meta is a hash used to collect geometries, materials.
5537 // not providing it implies that this is the root object
5538 // being serialized.
5541 // initialize meta obj
5554 generator: 'Object3D.toJSON'
5556 } // standard Object3D serialization
5560 object.uuid = this.uuid;
5561 object.type = this.type;
5562 if (this.name !== '') object.name = this.name;
5563 if (this.castShadow === true) object.castShadow = true;
5564 if (this.receiveShadow === true) object.receiveShadow = true;
5565 if (this.visible === false) object.visible = false;
5566 if (this.frustumCulled === false) object.frustumCulled = false;
5567 if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
5568 if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
5569 object.layers = this.layers.mask;
5570 object.matrix = this.matrix.toArray();
5571 if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
5573 if (this.isInstancedMesh) {
5574 object.type = 'InstancedMesh';
5575 object.count = this.count;
5576 object.instanceMatrix = this.instanceMatrix.toJSON();
5580 function serialize(library, element) {
5581 if (library[element.uuid] === undefined) {
5582 library[element.uuid] = element.toJSON(meta);
5585 return element.uuid;
5588 if (this.isMesh || this.isLine || this.isPoints) {
5589 object.geometry = serialize(meta.geometries, this.geometry);
5590 var parameters = this.geometry.parameters;
5592 if (parameters !== undefined && parameters.shapes !== undefined) {
5593 var shapes = parameters.shapes;
5595 if (Array.isArray(shapes)) {
5596 for (var i = 0, l = shapes.length; i < l; i++) {
5597 var shape = shapes[i];
5598 serialize(meta.shapes, shape);
5601 serialize(meta.shapes, shapes);
5606 if (this.isSkinnedMesh) {
5607 object.bindMode = this.bindMode;
5608 object.bindMatrix = this.bindMatrix.toArray();
5610 if (this.skeleton !== undefined) {
5611 serialize(meta.skeletons, this.skeleton);
5612 object.skeleton = this.skeleton.uuid;
5616 if (this.material !== undefined) {
5617 if (Array.isArray(this.material)) {
5620 for (var _i = 0, _l = this.material.length; _i < _l; _i++) {
5621 uuids.push(serialize(meta.materials, this.material[_i]));
5624 object.material = uuids;
5626 object.material = serialize(meta.materials, this.material);
5631 if (this.children.length > 0) {
5632 object.children = [];
5634 for (var _i2 = 0; _i2 < this.children.length; _i2++) {
5635 object.children.push(this.children[_i2].toJSON(meta).object);
5640 if (this.animations.length > 0) {
5641 object.animations = [];
5643 for (var _i3 = 0; _i3 < this.animations.length; _i3++) {
5644 var animation = this.animations[_i3];
5645 object.animations.push(serialize(meta.animations, animation));
5650 var geometries = extractFromCache(meta.geometries);
5651 var materials = extractFromCache(meta.materials);
5652 var textures = extractFromCache(meta.textures);
5653 var images = extractFromCache(meta.images);
5655 var _shapes = extractFromCache(meta.shapes);
5657 var skeletons = extractFromCache(meta.skeletons);
5658 var animations = extractFromCache(meta.animations);
5659 if (geometries.length > 0) output.geometries = geometries;
5660 if (materials.length > 0) output.materials = materials;
5661 if (textures.length > 0) output.textures = textures;
5662 if (images.length > 0) output.images = images;
5663 if (_shapes.length > 0) output.shapes = _shapes;
5664 if (skeletons.length > 0) output.skeletons = skeletons;
5665 if (animations.length > 0) output.animations = animations;
5668 output.object = object;
5669 return output; // extract data from the cache hash
5670 // remove metadata on each item
5671 // and return as array
5673 function extractFromCache(cache) {
5676 for (var key in cache) {
5677 var data = cache[key];
5678 delete data.metadata;
5685 clone: function clone(recursive) {
5686 return new this.constructor().copy(this, recursive);
5688 copy: function copy(source, recursive) {
5689 if (recursive === void 0) {
5693 this.name = source.name;
5694 this.up.copy(source.up);
5695 this.position.copy(source.position);
5696 this.rotation.order = source.rotation.order;
5697 this.quaternion.copy(source.quaternion);
5698 this.scale.copy(source.scale);
5699 this.matrix.copy(source.matrix);
5700 this.matrixWorld.copy(source.matrixWorld);
5701 this.matrixAutoUpdate = source.matrixAutoUpdate;
5702 this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
5703 this.layers.mask = source.layers.mask;
5704 this.visible = source.visible;
5705 this.castShadow = source.castShadow;
5706 this.receiveShadow = source.receiveShadow;
5707 this.frustumCulled = source.frustumCulled;
5708 this.renderOrder = source.renderOrder;
5709 this.userData = JSON.parse(JSON.stringify(source.userData));
5711 if (recursive === true) {
5712 for (var i = 0; i < source.children.length; i++) {
5713 var child = source.children[i];
5714 this.add(child.clone());
5722 var _vector1 = /*@__PURE__*/new Vector3();
5724 var _vector2 = /*@__PURE__*/new Vector3();
5726 var _normalMatrix = /*@__PURE__*/new Matrix3();
5728 var Plane = /*#__PURE__*/function () {
5729 function Plane(normal, constant) {
5730 Object.defineProperty(this, 'isPlane', {
5732 }); // normal is assumed to be normalized
5734 this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
5735 this.constant = constant !== undefined ? constant : 0;
5738 var _proto = Plane.prototype;
5740 _proto.set = function set(normal, constant) {
5741 this.normal.copy(normal);
5742 this.constant = constant;
5746 _proto.setComponents = function setComponents(x, y, z, w) {
5747 this.normal.set(x, y, z);
5752 _proto.setFromNormalAndCoplanarPoint = function setFromNormalAndCoplanarPoint(normal, point) {
5753 this.normal.copy(normal);
5754 this.constant = -point.dot(this.normal);
5758 _proto.setFromCoplanarPoints = function setFromCoplanarPoints(a, b, c) {
5759 var 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)?
5762 this.setFromNormalAndCoplanarPoint(normal, a);
5766 _proto.clone = function clone() {
5767 return new this.constructor().copy(this);
5770 _proto.copy = function copy(plane) {
5771 this.normal.copy(plane.normal);
5772 this.constant = plane.constant;
5776 _proto.normalize = function normalize() {
5777 // Note: will lead to a divide by zero if the plane is invalid.
5778 var inverseNormalLength = 1.0 / this.normal.length();
5779 this.normal.multiplyScalar(inverseNormalLength);
5780 this.constant *= inverseNormalLength;
5784 _proto.negate = function negate() {
5785 this.constant *= -1;
5786 this.normal.negate();
5790 _proto.distanceToPoint = function distanceToPoint(point) {
5791 return this.normal.dot(point) + this.constant;
5794 _proto.distanceToSphere = function distanceToSphere(sphere) {
5795 return this.distanceToPoint(sphere.center) - sphere.radius;
5798 _proto.projectPoint = function projectPoint(point, target) {
5799 if (target === undefined) {
5800 console.warn('THREE.Plane: .projectPoint() target is now required');
5801 target = new Vector3();
5804 return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
5807 _proto.intersectLine = function intersectLine(line, target) {
5808 if (target === undefined) {
5809 console.warn('THREE.Plane: .intersectLine() target is now required');
5810 target = new Vector3();
5813 var direction = line.delta(_vector1);
5814 var denominator = this.normal.dot(direction);
5816 if (denominator === 0) {
5817 // line is coplanar, return origin
5818 if (this.distanceToPoint(line.start) === 0) {
5819 return target.copy(line.start);
5820 } // Unsure if this is the correct method to handle this case.
5826 var t = -(line.start.dot(this.normal) + this.constant) / denominator;
5828 if (t < 0 || t > 1) {
5832 return target.copy(direction).multiplyScalar(t).add(line.start);
5835 _proto.intersectsLine = function intersectsLine(line) {
5836 // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
5837 var startSign = this.distanceToPoint(line.start);
5838 var endSign = this.distanceToPoint(line.end);
5839 return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
5842 _proto.intersectsBox = function intersectsBox(box) {
5843 return box.intersectsPlane(this);
5846 _proto.intersectsSphere = function intersectsSphere(sphere) {
5847 return sphere.intersectsPlane(this);
5850 _proto.coplanarPoint = function coplanarPoint(target) {
5851 if (target === undefined) {
5852 console.warn('THREE.Plane: .coplanarPoint() target is now required');
5853 target = new Vector3();
5856 return target.copy(this.normal).multiplyScalar(-this.constant);
5859 _proto.applyMatrix4 = function applyMatrix4(matrix, optionalNormalMatrix) {
5860 var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
5862 var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
5863 var normal = this.normal.applyMatrix3(normalMatrix).normalize();
5864 this.constant = -referencePoint.dot(normal);
5868 _proto.translate = function translate(offset) {
5869 this.constant -= offset.dot(this.normal);
5873 _proto.equals = function equals(plane) {
5874 return plane.normal.equals(this.normal) && plane.constant === this.constant;
5880 var _v0$1 = /*@__PURE__*/new Vector3();
5882 var _v1$3 = /*@__PURE__*/new Vector3();
5884 var _v2$1 = /*@__PURE__*/new Vector3();
5886 var _v3 = /*@__PURE__*/new Vector3();
5888 var _vab = /*@__PURE__*/new Vector3();
5890 var _vac = /*@__PURE__*/new Vector3();
5892 var _vbc = /*@__PURE__*/new Vector3();
5894 var _vap = /*@__PURE__*/new Vector3();
5896 var _vbp = /*@__PURE__*/new Vector3();
5898 var _vcp = /*@__PURE__*/new Vector3();
5900 var Triangle = /*#__PURE__*/function () {
5901 function Triangle(a, b, c) {
5902 this.a = a !== undefined ? a : new Vector3();
5903 this.b = b !== undefined ? b : new Vector3();
5904 this.c = c !== undefined ? c : new Vector3();
5907 Triangle.getNormal = function getNormal(a, b, c, target) {
5908 if (target === undefined) {
5909 console.warn('THREE.Triangle: .getNormal() target is now required');
5910 target = new Vector3();
5913 target.subVectors(c, b);
5915 _v0$1.subVectors(a, b);
5917 target.cross(_v0$1);
5918 var targetLengthSq = target.lengthSq();
5920 if (targetLengthSq > 0) {
5921 return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
5924 return target.set(0, 0, 0);
5925 } // static/instance method to calculate barycentric coordinates
5926 // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
5929 Triangle.getBarycoord = function getBarycoord(point, a, b, c, target) {
5930 _v0$1.subVectors(c, a);
5932 _v1$3.subVectors(b, a);
5934 _v2$1.subVectors(point, a);
5936 var dot00 = _v0$1.dot(_v0$1);
5938 var dot01 = _v0$1.dot(_v1$3);
5940 var dot02 = _v0$1.dot(_v2$1);
5942 var dot11 = _v1$3.dot(_v1$3);
5944 var dot12 = _v1$3.dot(_v2$1);
5946 var denom = dot00 * dot11 - dot01 * dot01;
5948 if (target === undefined) {
5949 console.warn('THREE.Triangle: .getBarycoord() target is now required');
5950 target = new Vector3();
5951 } // collinear or singular triangle
5955 // arbitrary location outside of triangle?
5956 // not sure if this is the best idea, maybe should be returning undefined
5957 return target.set(-2, -1, -1);
5960 var invDenom = 1 / denom;
5961 var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
5962 var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
5964 return target.set(1 - u - v, v, u);
5967 Triangle.containsPoint = function containsPoint(point, a, b, c) {
5968 this.getBarycoord(point, a, b, c, _v3);
5969 return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
5972 Triangle.getUV = function getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
5973 this.getBarycoord(point, p1, p2, p3, _v3);
5975 target.addScaledVector(uv1, _v3.x);
5976 target.addScaledVector(uv2, _v3.y);
5977 target.addScaledVector(uv3, _v3.z);
5981 Triangle.isFrontFacing = function isFrontFacing(a, b, c, direction) {
5982 _v0$1.subVectors(c, b);
5984 _v1$3.subVectors(a, b); // strictly front facing
5987 return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
5990 var _proto = Triangle.prototype;
5992 _proto.set = function set(a, b, c) {
5999 _proto.setFromPointsAndIndices = function setFromPointsAndIndices(points, i0, i1, i2) {
6000 this.a.copy(points[i0]);
6001 this.b.copy(points[i1]);
6002 this.c.copy(points[i2]);
6006 _proto.clone = function clone() {
6007 return new this.constructor().copy(this);
6010 _proto.copy = function copy(triangle) {
6011 this.a.copy(triangle.a);
6012 this.b.copy(triangle.b);
6013 this.c.copy(triangle.c);
6017 _proto.getArea = function getArea() {
6018 _v0$1.subVectors(this.c, this.b);
6020 _v1$3.subVectors(this.a, this.b);
6022 return _v0$1.cross(_v1$3).length() * 0.5;
6025 _proto.getMidpoint = function getMidpoint(target) {
6026 if (target === undefined) {
6027 console.warn('THREE.Triangle: .getMidpoint() target is now required');
6028 target = new Vector3();
6031 return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
6034 _proto.getNormal = function getNormal(target) {
6035 return Triangle.getNormal(this.a, this.b, this.c, target);
6038 _proto.getPlane = function getPlane(target) {
6039 if (target === undefined) {
6040 console.warn('THREE.Triangle: .getPlane() target is now required');
6041 target = new Plane();
6044 return target.setFromCoplanarPoints(this.a, this.b, this.c);
6047 _proto.getBarycoord = function getBarycoord(point, target) {
6048 return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
6051 _proto.getUV = function getUV(point, uv1, uv2, uv3, target) {
6052 return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
6055 _proto.containsPoint = function containsPoint(point) {
6056 return Triangle.containsPoint(point, this.a, this.b, this.c);
6059 _proto.isFrontFacing = function isFrontFacing(direction) {
6060 return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
6063 _proto.intersectsBox = function intersectsBox(box) {
6064 return box.intersectsTriangle(this);
6067 _proto.closestPointToPoint = function closestPointToPoint(p, target) {
6068 if (target === undefined) {
6069 console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
6070 target = new Vector3();
6076 var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
6077 // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
6078 // under the accompanying license; see chapter 5.1.5 for detailed explanation.
6079 // basically, we're distinguishing which of the voronoi regions of the triangle
6080 // the point lies in with the minimum amount of redundant computation.
6082 _vab.subVectors(b, a);
6084 _vac.subVectors(c, a);
6086 _vap.subVectors(p, a);
6088 var d1 = _vab.dot(_vap);
6090 var d2 = _vac.dot(_vap);
6092 if (d1 <= 0 && d2 <= 0) {
6093 // vertex region of A; barycentric coords (1, 0, 0)
6094 return target.copy(a);
6097 _vbp.subVectors(p, b);
6099 var d3 = _vab.dot(_vbp);
6101 var d4 = _vac.dot(_vbp);
6103 if (d3 >= 0 && d4 <= d3) {
6104 // vertex region of B; barycentric coords (0, 1, 0)
6105 return target.copy(b);
6108 var vc = d1 * d4 - d3 * d2;
6110 if (vc <= 0 && d1 >= 0 && d3 <= 0) {
6111 v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
6113 return target.copy(a).addScaledVector(_vab, v);
6116 _vcp.subVectors(p, c);
6118 var d5 = _vab.dot(_vcp);
6120 var d6 = _vac.dot(_vcp);
6122 if (d6 >= 0 && d5 <= d6) {
6123 // vertex region of C; barycentric coords (0, 0, 1)
6124 return target.copy(c);
6127 var vb = d5 * d2 - d1 * d6;
6129 if (vb <= 0 && d2 >= 0 && d6 <= 0) {
6130 w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
6132 return target.copy(a).addScaledVector(_vac, w);
6135 var va = d3 * d6 - d5 * d4;
6137 if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
6138 _vbc.subVectors(c, b);
6140 w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
6142 return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
6146 var denom = 1 / (va + vb + vc); // u = va * denom
6150 return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
6153 _proto.equals = function equals(triangle) {
6154 return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
6160 var _colorKeywords = {
6161 'aliceblue': 0xF0F8FF,
6162 'antiquewhite': 0xFAEBD7,
6164 'aquamarine': 0x7FFFD4,
6169 'blanchedalmond': 0xFFEBCD,
6171 'blueviolet': 0x8A2BE2,
6173 'burlywood': 0xDEB887,
6174 'cadetblue': 0x5F9EA0,
6175 'chartreuse': 0x7FFF00,
6176 'chocolate': 0xD2691E,
6178 'cornflowerblue': 0x6495ED,
6179 'cornsilk': 0xFFF8DC,
6180 'crimson': 0xDC143C,
6182 'darkblue': 0x00008B,
6183 'darkcyan': 0x008B8B,
6184 'darkgoldenrod': 0xB8860B,
6185 'darkgray': 0xA9A9A9,
6186 'darkgreen': 0x006400,
6187 'darkgrey': 0xA9A9A9,
6188 'darkkhaki': 0xBDB76B,
6189 'darkmagenta': 0x8B008B,
6190 'darkolivegreen': 0x556B2F,
6191 'darkorange': 0xFF8C00,
6192 'darkorchid': 0x9932CC,
6193 'darkred': 0x8B0000,
6194 'darksalmon': 0xE9967A,
6195 'darkseagreen': 0x8FBC8F,
6196 'darkslateblue': 0x483D8B,
6197 'darkslategray': 0x2F4F4F,
6198 'darkslategrey': 0x2F4F4F,
6199 'darkturquoise': 0x00CED1,
6200 'darkviolet': 0x9400D3,
6201 'deeppink': 0xFF1493,
6202 'deepskyblue': 0x00BFFF,
6203 'dimgray': 0x696969,
6204 'dimgrey': 0x696969,
6205 'dodgerblue': 0x1E90FF,
6206 'firebrick': 0xB22222,
6207 'floralwhite': 0xFFFAF0,
6208 'forestgreen': 0x228B22,
6209 'fuchsia': 0xFF00FF,
6210 'gainsboro': 0xDCDCDC,
6211 'ghostwhite': 0xF8F8FF,
6213 'goldenrod': 0xDAA520,
6216 'greenyellow': 0xADFF2F,
6218 'honeydew': 0xF0FFF0,
6219 'hotpink': 0xFF69B4,
6220 'indianred': 0xCD5C5C,
6224 'lavender': 0xE6E6FA,
6225 'lavenderblush': 0xFFF0F5,
6226 'lawngreen': 0x7CFC00,
6227 'lemonchiffon': 0xFFFACD,
6228 'lightblue': 0xADD8E6,
6229 'lightcoral': 0xF08080,
6230 'lightcyan': 0xE0FFFF,
6231 'lightgoldenrodyellow': 0xFAFAD2,
6232 'lightgray': 0xD3D3D3,
6233 'lightgreen': 0x90EE90,
6234 'lightgrey': 0xD3D3D3,
6235 'lightpink': 0xFFB6C1,
6236 'lightsalmon': 0xFFA07A,
6237 'lightseagreen': 0x20B2AA,
6238 'lightskyblue': 0x87CEFA,
6239 'lightslategray': 0x778899,
6240 'lightslategrey': 0x778899,
6241 'lightsteelblue': 0xB0C4DE,
6242 'lightyellow': 0xFFFFE0,
6244 'limegreen': 0x32CD32,
6246 'magenta': 0xFF00FF,
6248 'mediumaquamarine': 0x66CDAA,
6249 'mediumblue': 0x0000CD,
6250 'mediumorchid': 0xBA55D3,
6251 'mediumpurple': 0x9370DB,
6252 'mediumseagreen': 0x3CB371,
6253 'mediumslateblue': 0x7B68EE,
6254 'mediumspringgreen': 0x00FA9A,
6255 'mediumturquoise': 0x48D1CC,
6256 'mediumvioletred': 0xC71585,
6257 'midnightblue': 0x191970,
6258 'mintcream': 0xF5FFFA,
6259 'mistyrose': 0xFFE4E1,
6260 'moccasin': 0xFFE4B5,
6261 'navajowhite': 0xFFDEAD,
6263 'oldlace': 0xFDF5E6,
6265 'olivedrab': 0x6B8E23,
6267 'orangered': 0xFF4500,
6269 'palegoldenrod': 0xEEE8AA,
6270 'palegreen': 0x98FB98,
6271 'paleturquoise': 0xAFEEEE,
6272 'palevioletred': 0xDB7093,
6273 'papayawhip': 0xFFEFD5,
6274 'peachpuff': 0xFFDAB9,
6278 'powderblue': 0xB0E0E6,
6280 'rebeccapurple': 0x663399,
6282 'rosybrown': 0xBC8F8F,
6283 'royalblue': 0x4169E1,
6284 'saddlebrown': 0x8B4513,
6286 'sandybrown': 0xF4A460,
6287 'seagreen': 0x2E8B57,
6288 'seashell': 0xFFF5EE,
6291 'skyblue': 0x87CEEB,
6292 'slateblue': 0x6A5ACD,
6293 'slategray': 0x708090,
6294 'slategrey': 0x708090,
6296 'springgreen': 0x00FF7F,
6297 'steelblue': 0x4682B4,
6300 'thistle': 0xD8BFD8,
6302 'turquoise': 0x40E0D0,
6306 'whitesmoke': 0xF5F5F5,
6308 'yellowgreen': 0x9ACD32
6321 function hue2rgb(p, q, t) {
6324 if (t < 1 / 6) return p + (q - p) * 6 * t;
6325 if (t < 1 / 2) return q;
6326 if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
6330 function SRGBToLinear(c) {
6331 return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
6334 function LinearToSRGB(c) {
6335 return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
6338 var Color = /*#__PURE__*/function () {
6339 function Color(r, g, b) {
6340 Object.defineProperty(this, 'isColor', {
6344 if (g === undefined && b === undefined) {
6345 // r is THREE.Color, hex or string
6349 return this.setRGB(r, g, b);
6352 var _proto = Color.prototype;
6354 _proto.set = function set(value) {
6355 if (value && value.isColor) {
6357 } else if (typeof value === 'number') {
6359 } else if (typeof value === 'string') {
6360 this.setStyle(value);
6366 _proto.setScalar = function setScalar(scalar) {
6373 _proto.setHex = function setHex(hex) {
6374 hex = Math.floor(hex);
6375 this.r = (hex >> 16 & 255) / 255;
6376 this.g = (hex >> 8 & 255) / 255;
6377 this.b = (hex & 255) / 255;
6381 _proto.setRGB = function setRGB(r, g, b) {
6388 _proto.setHSL = function setHSL(h, s, l) {
6389 // h,s,l ranges are in 0.0 - 1.0
6390 h = MathUtils.euclideanModulo(h, 1);
6391 s = MathUtils.clamp(s, 0, 1);
6392 l = MathUtils.clamp(l, 0, 1);
6395 this.r = this.g = this.b = l;
6397 var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
6399 this.r = hue2rgb(q, p, h + 1 / 3);
6400 this.g = hue2rgb(q, p, h);
6401 this.b = hue2rgb(q, p, h - 1 / 3);
6407 _proto.setStyle = function setStyle(style) {
6408 function handleAlpha(string) {
6409 if (string === undefined) return;
6411 if (parseFloat(string) < 1) {
6412 console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
6418 if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
6422 var components = m[2];
6427 if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
6428 // rgb(255,0,0) rgba(255,0,0,0.5)
6429 this.r = Math.min(255, parseInt(color[1], 10)) / 255;
6430 this.g = Math.min(255, parseInt(color[2], 10)) / 255;
6431 this.b = Math.min(255, parseInt(color[3], 10)) / 255;
6432 handleAlpha(color[5]);
6436 if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
6437 // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
6438 this.r = Math.min(100, parseInt(color[1], 10)) / 100;
6439 this.g = Math.min(100, parseInt(color[2], 10)) / 100;
6440 this.b = Math.min(100, parseInt(color[3], 10)) / 100;
6441 handleAlpha(color[5]);
6449 if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
6450 // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
6451 var h = parseFloat(color[1]) / 360;
6452 var s = parseInt(color[2], 10) / 100;
6453 var l = parseInt(color[3], 10) / 100;
6454 handleAlpha(color[5]);
6455 return this.setHSL(h, s, l);
6460 } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
6463 var size = hex.length;
6467 this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
6468 this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
6469 this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
6471 } else if (size === 6) {
6473 this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
6474 this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
6475 this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
6480 if (style && style.length > 0) {
6481 return this.setColorName(style);
6487 _proto.setColorName = function setColorName(style) {
6489 var hex = _colorKeywords[style];
6491 if (hex !== undefined) {
6496 console.warn('THREE.Color: Unknown color ' + style);
6502 _proto.clone = function clone() {
6503 return new this.constructor(this.r, this.g, this.b);
6506 _proto.copy = function copy(color) {
6513 _proto.copyGammaToLinear = function copyGammaToLinear(color, gammaFactor) {
6514 if (gammaFactor === void 0) {
6518 this.r = Math.pow(color.r, gammaFactor);
6519 this.g = Math.pow(color.g, gammaFactor);
6520 this.b = Math.pow(color.b, gammaFactor);
6524 _proto.copyLinearToGamma = function copyLinearToGamma(color, gammaFactor) {
6525 if (gammaFactor === void 0) {
6529 var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
6530 this.r = Math.pow(color.r, safeInverse);
6531 this.g = Math.pow(color.g, safeInverse);
6532 this.b = Math.pow(color.b, safeInverse);
6536 _proto.convertGammaToLinear = function convertGammaToLinear(gammaFactor) {
6537 this.copyGammaToLinear(this, gammaFactor);
6541 _proto.convertLinearToGamma = function convertLinearToGamma(gammaFactor) {
6542 this.copyLinearToGamma(this, gammaFactor);
6546 _proto.copySRGBToLinear = function copySRGBToLinear(color) {
6547 this.r = SRGBToLinear(color.r);
6548 this.g = SRGBToLinear(color.g);
6549 this.b = SRGBToLinear(color.b);
6553 _proto.copyLinearToSRGB = function copyLinearToSRGB(color) {
6554 this.r = LinearToSRGB(color.r);
6555 this.g = LinearToSRGB(color.g);
6556 this.b = LinearToSRGB(color.b);
6560 _proto.convertSRGBToLinear = function convertSRGBToLinear() {
6561 this.copySRGBToLinear(this);
6565 _proto.convertLinearToSRGB = function convertLinearToSRGB() {
6566 this.copyLinearToSRGB(this);
6570 _proto.getHex = function getHex() {
6571 return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
6574 _proto.getHexString = function getHexString() {
6575 return ('000000' + this.getHex().toString(16)).slice(-6);
6578 _proto.getHSL = function getHSL(target) {
6579 // h,s,l ranges are in 0.0 - 1.0
6580 if (target === undefined) {
6581 console.warn('THREE.Color: .getHSL() target is now required');
6592 var max = Math.max(r, g, b);
6593 var min = Math.min(r, g, b);
6594 var hue, saturation;
6595 var lightness = (min + max) / 2.0;
6601 var delta = max - min;
6602 saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
6606 hue = (g - b) / delta + (g < b ? 6 : 0);
6610 hue = (b - r) / delta + 2;
6614 hue = (r - g) / delta + 4;
6622 target.s = saturation;
6623 target.l = lightness;
6627 _proto.getStyle = function getStyle() {
6628 return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
6631 _proto.offsetHSL = function offsetHSL(h, s, l) {
6636 this.setHSL(_hslA.h, _hslA.s, _hslA.l);
6640 _proto.add = function add(color) {
6647 _proto.addColors = function addColors(color1, color2) {
6648 this.r = color1.r + color2.r;
6649 this.g = color1.g + color2.g;
6650 this.b = color1.b + color2.b;
6654 _proto.addScalar = function addScalar(s) {
6661 _proto.sub = function sub(color) {
6662 this.r = Math.max(0, this.r - color.r);
6663 this.g = Math.max(0, this.g - color.g);
6664 this.b = Math.max(0, this.b - color.b);
6668 _proto.multiply = function multiply(color) {
6675 _proto.multiplyScalar = function multiplyScalar(s) {
6682 _proto.lerp = function lerp(color, alpha) {
6683 this.r += (color.r - this.r) * alpha;
6684 this.g += (color.g - this.g) * alpha;
6685 this.b += (color.b - this.b) * alpha;
6689 _proto.lerpHSL = function lerpHSL(color, alpha) {
6691 color.getHSL(_hslB);
6692 var h = MathUtils.lerp(_hslA.h, _hslB.h, alpha);
6693 var s = MathUtils.lerp(_hslA.s, _hslB.s, alpha);
6694 var l = MathUtils.lerp(_hslA.l, _hslB.l, alpha);
6695 this.setHSL(h, s, l);
6699 _proto.equals = function equals(c) {
6700 return c.r === this.r && c.g === this.g && c.b === this.b;
6703 _proto.fromArray = function fromArray(array, offset) {
6704 if (offset === void 0) {
6708 this.r = array[offset];
6709 this.g = array[offset + 1];
6710 this.b = array[offset + 2];
6714 _proto.toArray = function toArray(array, offset) {
6715 if (array === void 0) {
6719 if (offset === void 0) {
6723 array[offset] = this.r;
6724 array[offset + 1] = this.g;
6725 array[offset + 2] = this.b;
6729 _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index) {
6730 this.r = attribute.getX(index);
6731 this.g = attribute.getY(index);
6732 this.b = attribute.getZ(index);
6734 if (attribute.normalized === true) {
6735 // assuming Uint8Array
6744 _proto.toJSON = function toJSON() {
6745 return this.getHex();
6751 Color.NAMES = _colorKeywords;
6752 Color.prototype.r = 1;
6753 Color.prototype.g = 1;
6754 Color.prototype.b = 1;
6756 var Face3 = /*#__PURE__*/function () {
6757 function Face3(a, b, c, normal, color, materialIndex) {
6758 if (materialIndex === void 0) {
6765 this.normal = normal && normal.isVector3 ? normal : new Vector3();
6766 this.vertexNormals = Array.isArray(normal) ? normal : [];
6767 this.color = color && color.isColor ? color : new Color();
6768 this.vertexColors = Array.isArray(color) ? color : [];
6769 this.materialIndex = materialIndex;
6772 var _proto = Face3.prototype;
6774 _proto.clone = function clone() {
6775 return new this.constructor().copy(this);
6778 _proto.copy = function copy(source) {
6782 this.normal.copy(source.normal);
6783 this.color.copy(source.color);
6784 this.materialIndex = source.materialIndex;
6786 for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
6787 this.vertexNormals[i] = source.vertexNormals[i].clone();
6790 for (var _i = 0, _il = source.vertexColors.length; _i < _il; _i++) {
6791 this.vertexColors[_i] = source.vertexColors[_i].clone();
6802 function Material() {
6803 Object.defineProperty(this, 'id', {
6806 this.uuid = MathUtils.generateUUID();
6808 this.type = 'Material';
6810 this.blending = NormalBlending;
6811 this.side = FrontSide;
6812 this.flatShading = false;
6813 this.vertexColors = false;
6815 this.transparent = false;
6816 this.blendSrc = SrcAlphaFactor;
6817 this.blendDst = OneMinusSrcAlphaFactor;
6818 this.blendEquation = AddEquation;
6819 this.blendSrcAlpha = null;
6820 this.blendDstAlpha = null;
6821 this.blendEquationAlpha = null;
6822 this.depthFunc = LessEqualDepth;
6823 this.depthTest = true;
6824 this.depthWrite = true;
6825 this.stencilWriteMask = 0xff;
6826 this.stencilFunc = AlwaysStencilFunc;
6827 this.stencilRef = 0;
6828 this.stencilFuncMask = 0xff;
6829 this.stencilFail = KeepStencilOp;
6830 this.stencilZFail = KeepStencilOp;
6831 this.stencilZPass = KeepStencilOp;
6832 this.stencilWrite = false;
6833 this.clippingPlanes = null;
6834 this.clipIntersection = false;
6835 this.clipShadows = false;
6836 this.shadowSide = null;
6837 this.colorWrite = true;
6838 this.precision = null; // override the renderer's default precision for this material
6840 this.polygonOffset = false;
6841 this.polygonOffsetFactor = 0;
6842 this.polygonOffsetUnits = 0;
6843 this.dithering = false;
6845 this.premultipliedAlpha = false;
6846 this.visible = true;
6847 this.toneMapped = true;
6852 Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
6853 constructor: Material,
6855 onBeforeCompile: function onBeforeCompile()
6856 /* shaderobject, renderer */
6858 customProgramCacheKey: function customProgramCacheKey() {
6859 return this.onBeforeCompile.toString();
6861 setValues: function setValues(values) {
6862 if (values === undefined) return;
6864 for (var key in values) {
6865 var newValue = values[key];
6867 if (newValue === undefined) {
6868 console.warn("THREE.Material: '" + key + "' parameter is undefined.");
6870 } // for backward compatability if shading is set in the constructor
6873 if (key === 'shading') {
6874 console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
6875 this.flatShading = newValue === FlatShading ? true : false;
6879 var currentValue = this[key];
6881 if (currentValue === undefined) {
6882 console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
6886 if (currentValue && currentValue.isColor) {
6887 currentValue.set(newValue);
6888 } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
6889 currentValue.copy(newValue);
6891 this[key] = newValue;
6895 toJSON: function toJSON(meta) {
6896 var isRoot = meta === undefined || typeof meta === 'string';
6909 generator: 'Material.toJSON'
6911 }; // standard Material serialization
6913 data.uuid = this.uuid;
6914 data.type = this.type;
6915 if (this.name !== '') data.name = this.name;
6916 if (this.color && this.color.isColor) data.color = this.color.getHex();
6917 if (this.roughness !== undefined) data.roughness = this.roughness;
6918 if (this.metalness !== undefined) data.metalness = this.metalness;
6919 if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
6920 if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
6921 if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
6922 if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
6923 if (this.shininess !== undefined) data.shininess = this.shininess;
6924 if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
6925 if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
6927 if (this.clearcoatMap && this.clearcoatMap.isTexture) {
6928 data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
6931 if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
6932 data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
6935 if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
6936 data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
6937 data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
6940 if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
6941 if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
6942 if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
6943 if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
6945 if (this.aoMap && this.aoMap.isTexture) {
6946 data.aoMap = this.aoMap.toJSON(meta).uuid;
6947 data.aoMapIntensity = this.aoMapIntensity;
6950 if (this.bumpMap && this.bumpMap.isTexture) {
6951 data.bumpMap = this.bumpMap.toJSON(meta).uuid;
6952 data.bumpScale = this.bumpScale;
6955 if (this.normalMap && this.normalMap.isTexture) {
6956 data.normalMap = this.normalMap.toJSON(meta).uuid;
6957 data.normalMapType = this.normalMapType;
6958 data.normalScale = this.normalScale.toArray();
6961 if (this.displacementMap && this.displacementMap.isTexture) {
6962 data.displacementMap = this.displacementMap.toJSON(meta).uuid;
6963 data.displacementScale = this.displacementScale;
6964 data.displacementBias = this.displacementBias;
6967 if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
6968 if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
6969 if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
6970 if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
6972 if (this.envMap && this.envMap.isTexture) {
6973 data.envMap = this.envMap.toJSON(meta).uuid;
6974 data.reflectivity = this.reflectivity; // Scale behind envMap
6976 data.refractionRatio = this.refractionRatio;
6977 if (this.combine !== undefined) data.combine = this.combine;
6978 if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
6981 if (this.gradientMap && this.gradientMap.isTexture) {
6982 data.gradientMap = this.gradientMap.toJSON(meta).uuid;
6985 if (this.size !== undefined) data.size = this.size;
6986 if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
6987 if (this.blending !== NormalBlending) data.blending = this.blending;
6988 if (this.flatShading === true) data.flatShading = this.flatShading;
6989 if (this.side !== FrontSide) data.side = this.side;
6990 if (this.vertexColors) data.vertexColors = true;
6991 if (this.opacity < 1) data.opacity = this.opacity;
6992 if (this.transparent === true) data.transparent = this.transparent;
6993 data.depthFunc = this.depthFunc;
6994 data.depthTest = this.depthTest;
6995 data.depthWrite = this.depthWrite;
6996 data.stencilWrite = this.stencilWrite;
6997 data.stencilWriteMask = this.stencilWriteMask;
6998 data.stencilFunc = this.stencilFunc;
6999 data.stencilRef = this.stencilRef;
7000 data.stencilFuncMask = this.stencilFuncMask;
7001 data.stencilFail = this.stencilFail;
7002 data.stencilZFail = this.stencilZFail;
7003 data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
7005 if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
7006 if (this.polygonOffset === true) data.polygonOffset = true;
7007 if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
7008 if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
7009 if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
7010 if (this.dashSize !== undefined) data.dashSize = this.dashSize;
7011 if (this.gapSize !== undefined) data.gapSize = this.gapSize;
7012 if (this.scale !== undefined) data.scale = this.scale;
7013 if (this.dithering === true) data.dithering = true;
7014 if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
7015 if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
7016 if (this.wireframe === true) data.wireframe = this.wireframe;
7017 if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
7018 if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
7019 if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
7020 if (this.morphTargets === true) data.morphTargets = true;
7021 if (this.morphNormals === true) data.morphNormals = true;
7022 if (this.skinning === true) data.skinning = true;
7023 if (this.visible === false) data.visible = false;
7024 if (this.toneMapped === false) data.toneMapped = false;
7025 if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
7027 function extractFromCache(cache) {
7030 for (var key in cache) {
7031 var _data = cache[key];
7032 delete _data.metadata;
7040 var textures = extractFromCache(meta.textures);
7041 var images = extractFromCache(meta.images);
7042 if (textures.length > 0) data.textures = textures;
7043 if (images.length > 0) data.images = images;
7048 clone: function clone() {
7049 return new this.constructor().copy(this);
7051 copy: function copy(source) {
7052 this.name = source.name;
7053 this.fog = source.fog;
7054 this.blending = source.blending;
7055 this.side = source.side;
7056 this.flatShading = source.flatShading;
7057 this.vertexColors = source.vertexColors;
7058 this.opacity = source.opacity;
7059 this.transparent = source.transparent;
7060 this.blendSrc = source.blendSrc;
7061 this.blendDst = source.blendDst;
7062 this.blendEquation = source.blendEquation;
7063 this.blendSrcAlpha = source.blendSrcAlpha;
7064 this.blendDstAlpha = source.blendDstAlpha;
7065 this.blendEquationAlpha = source.blendEquationAlpha;
7066 this.depthFunc = source.depthFunc;
7067 this.depthTest = source.depthTest;
7068 this.depthWrite = source.depthWrite;
7069 this.stencilWriteMask = source.stencilWriteMask;
7070 this.stencilFunc = source.stencilFunc;
7071 this.stencilRef = source.stencilRef;
7072 this.stencilFuncMask = source.stencilFuncMask;
7073 this.stencilFail = source.stencilFail;
7074 this.stencilZFail = source.stencilZFail;
7075 this.stencilZPass = source.stencilZPass;
7076 this.stencilWrite = source.stencilWrite;
7077 var srcPlanes = source.clippingPlanes;
7078 var dstPlanes = null;
7080 if (srcPlanes !== null) {
7081 var n = srcPlanes.length;
7082 dstPlanes = new Array(n);
7084 for (var i = 0; i !== n; ++i) {
7085 dstPlanes[i] = srcPlanes[i].clone();
7089 this.clippingPlanes = dstPlanes;
7090 this.clipIntersection = source.clipIntersection;
7091 this.clipShadows = source.clipShadows;
7092 this.shadowSide = source.shadowSide;
7093 this.colorWrite = source.colorWrite;
7094 this.precision = source.precision;
7095 this.polygonOffset = source.polygonOffset;
7096 this.polygonOffsetFactor = source.polygonOffsetFactor;
7097 this.polygonOffsetUnits = source.polygonOffsetUnits;
7098 this.dithering = source.dithering;
7099 this.alphaTest = source.alphaTest;
7100 this.premultipliedAlpha = source.premultipliedAlpha;
7101 this.visible = source.visible;
7102 this.toneMapped = source.toneMapped;
7103 this.userData = JSON.parse(JSON.stringify(source.userData));
7106 dispose: function dispose() {
7107 this.dispatchEvent({
7112 Object.defineProperty(Material.prototype, 'needsUpdate', {
7113 set: function set(value) {
7114 if (value === true) this.version++;
7122 * map: new THREE.Texture( <Image> ),
7124 * lightMap: new THREE.Texture( <Image> ),
7125 * lightMapIntensity: <float>
7127 * aoMap: new THREE.Texture( <Image> ),
7128 * aoMapIntensity: <float>
7130 * specularMap: new THREE.Texture( <Image> ),
7132 * alphaMap: new THREE.Texture( <Image> ),
7134 * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
7135 * combine: THREE.Multiply,
7136 * reflectivity: <float>,
7137 * refractionRatio: <float>,
7139 * depthTest: <bool>,
7140 * depthWrite: <bool>,
7142 * wireframe: <boolean>,
7143 * wireframeLinewidth: <float>,
7146 * morphTargets: <bool>
7150 function MeshBasicMaterial(parameters) {
7151 Material.call(this);
7152 this.type = 'MeshBasicMaterial';
7153 this.color = new Color(0xffffff); // emissive
7156 this.lightMap = null;
7157 this.lightMapIntensity = 1.0;
7159 this.aoMapIntensity = 1.0;
7160 this.specularMap = null;
7161 this.alphaMap = null;
7163 this.combine = MultiplyOperation;
7164 this.reflectivity = 1;
7165 this.refractionRatio = 0.98;
7166 this.wireframe = false;
7167 this.wireframeLinewidth = 1;
7168 this.wireframeLinecap = 'round';
7169 this.wireframeLinejoin = 'round';
7170 this.skinning = false;
7171 this.morphTargets = false;
7172 this.setValues(parameters);
7175 MeshBasicMaterial.prototype = Object.create(Material.prototype);
7176 MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
7177 MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
7179 MeshBasicMaterial.prototype.copy = function (source) {
7180 Material.prototype.copy.call(this, source);
7181 this.color.copy(source.color);
7182 this.map = source.map;
7183 this.lightMap = source.lightMap;
7184 this.lightMapIntensity = source.lightMapIntensity;
7185 this.aoMap = source.aoMap;
7186 this.aoMapIntensity = source.aoMapIntensity;
7187 this.specularMap = source.specularMap;
7188 this.alphaMap = source.alphaMap;
7189 this.envMap = source.envMap;
7190 this.combine = source.combine;
7191 this.reflectivity = source.reflectivity;
7192 this.refractionRatio = source.refractionRatio;
7193 this.wireframe = source.wireframe;
7194 this.wireframeLinewidth = source.wireframeLinewidth;
7195 this.wireframeLinecap = source.wireframeLinecap;
7196 this.wireframeLinejoin = source.wireframeLinejoin;
7197 this.skinning = source.skinning;
7198 this.morphTargets = source.morphTargets;
7202 var _vector$3 = new Vector3();
7204 var _vector2$1 = new Vector2();
7206 function BufferAttribute(array, itemSize, normalized) {
7207 if (Array.isArray(array)) {
7208 throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
7213 this.itemSize = itemSize;
7214 this.count = array !== undefined ? array.length / itemSize : 0;
7215 this.normalized = normalized === true;
7216 this.usage = StaticDrawUsage;
7217 this.updateRange = {
7224 Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
7225 set: function set(value) {
7226 if (value === true) this.version++;
7229 Object.assign(BufferAttribute.prototype, {
7230 isBufferAttribute: true,
7231 onUploadCallback: function onUploadCallback() {},
7232 setUsage: function setUsage(value) {
7236 copy: function copy(source) {
7237 this.name = source.name;
7238 this.array = new source.array.constructor(source.array);
7239 this.itemSize = source.itemSize;
7240 this.count = source.count;
7241 this.normalized = source.normalized;
7242 this.usage = source.usage;
7245 copyAt: function copyAt(index1, attribute, index2) {
7246 index1 *= this.itemSize;
7247 index2 *= attribute.itemSize;
7249 for (var i = 0, l = this.itemSize; i < l; i++) {
7250 this.array[index1 + i] = attribute.array[index2 + i];
7255 copyArray: function copyArray(array) {
7256 this.array.set(array);
7259 copyColorsArray: function copyColorsArray(colors) {
7260 var array = this.array;
7263 for (var i = 0, l = colors.length; i < l; i++) {
7264 var color = colors[i];
7266 if (color === undefined) {
7267 console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
7268 color = new Color();
7271 array[offset++] = color.r;
7272 array[offset++] = color.g;
7273 array[offset++] = color.b;
7278 copyVector2sArray: function copyVector2sArray(vectors) {
7279 var array = this.array;
7282 for (var i = 0, l = vectors.length; i < l; i++) {
7283 var vector = vectors[i];
7285 if (vector === undefined) {
7286 console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
7287 vector = new Vector2();
7290 array[offset++] = vector.x;
7291 array[offset++] = vector.y;
7296 copyVector3sArray: function copyVector3sArray(vectors) {
7297 var array = this.array;
7300 for (var i = 0, l = vectors.length; i < l; i++) {
7301 var vector = vectors[i];
7303 if (vector === undefined) {
7304 console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
7305 vector = new Vector3();
7308 array[offset++] = vector.x;
7309 array[offset++] = vector.y;
7310 array[offset++] = vector.z;
7315 copyVector4sArray: function copyVector4sArray(vectors) {
7316 var array = this.array;
7319 for (var i = 0, l = vectors.length; i < l; i++) {
7320 var vector = vectors[i];
7322 if (vector === undefined) {
7323 console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
7324 vector = new Vector4();
7327 array[offset++] = vector.x;
7328 array[offset++] = vector.y;
7329 array[offset++] = vector.z;
7330 array[offset++] = vector.w;
7335 applyMatrix3: function applyMatrix3(m) {
7336 if (this.itemSize === 2) {
7337 for (var i = 0, l = this.count; i < l; i++) {
7338 _vector2$1.fromBufferAttribute(this, i);
7340 _vector2$1.applyMatrix3(m);
7342 this.setXY(i, _vector2$1.x, _vector2$1.y);
7344 } else if (this.itemSize === 3) {
7345 for (var _i = 0, _l = this.count; _i < _l; _i++) {
7346 _vector$3.fromBufferAttribute(this, _i);
7348 _vector$3.applyMatrix3(m);
7350 this.setXYZ(_i, _vector$3.x, _vector$3.y, _vector$3.z);
7356 applyMatrix4: function applyMatrix4(m) {
7357 for (var i = 0, l = this.count; i < l; i++) {
7358 _vector$3.x = this.getX(i);
7359 _vector$3.y = this.getY(i);
7360 _vector$3.z = this.getZ(i);
7362 _vector$3.applyMatrix4(m);
7364 this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
7369 applyNormalMatrix: function applyNormalMatrix(m) {
7370 for (var i = 0, l = this.count; i < l; i++) {
7371 _vector$3.x = this.getX(i);
7372 _vector$3.y = this.getY(i);
7373 _vector$3.z = this.getZ(i);
7375 _vector$3.applyNormalMatrix(m);
7377 this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
7382 transformDirection: function transformDirection(m) {
7383 for (var i = 0, l = this.count; i < l; i++) {
7384 _vector$3.x = this.getX(i);
7385 _vector$3.y = this.getY(i);
7386 _vector$3.z = this.getZ(i);
7388 _vector$3.transformDirection(m);
7390 this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
7395 set: function set(value, offset) {
7396 if (offset === void 0) {
7400 this.array.set(value, offset);
7403 getX: function getX(index) {
7404 return this.array[index * this.itemSize];
7406 setX: function setX(index, x) {
7407 this.array[index * this.itemSize] = x;
7410 getY: function getY(index) {
7411 return this.array[index * this.itemSize + 1];
7413 setY: function setY(index, y) {
7414 this.array[index * this.itemSize + 1] = y;
7417 getZ: function getZ(index) {
7418 return this.array[index * this.itemSize + 2];
7420 setZ: function setZ(index, z) {
7421 this.array[index * this.itemSize + 2] = z;
7424 getW: function getW(index) {
7425 return this.array[index * this.itemSize + 3];
7427 setW: function setW(index, w) {
7428 this.array[index * this.itemSize + 3] = w;
7431 setXY: function setXY(index, x, y) {
7432 index *= this.itemSize;
7433 this.array[index + 0] = x;
7434 this.array[index + 1] = y;
7437 setXYZ: function setXYZ(index, x, y, z) {
7438 index *= this.itemSize;
7439 this.array[index + 0] = x;
7440 this.array[index + 1] = y;
7441 this.array[index + 2] = z;
7444 setXYZW: function setXYZW(index, x, y, z, w) {
7445 index *= this.itemSize;
7446 this.array[index + 0] = x;
7447 this.array[index + 1] = y;
7448 this.array[index + 2] = z;
7449 this.array[index + 3] = w;
7452 onUpload: function onUpload(callback) {
7453 this.onUploadCallback = callback;
7456 clone: function clone() {
7457 return new this.constructor(this.array, this.itemSize).copy(this);
7459 toJSON: function toJSON() {
7461 itemSize: this.itemSize,
7462 type: this.array.constructor.name,
7463 array: Array.prototype.slice.call(this.array),
7464 normalized: this.normalized
7469 function Int8BufferAttribute(array, itemSize, normalized) {
7470 BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
7473 Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
7474 Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
7476 function Uint8BufferAttribute(array, itemSize, normalized) {
7477 BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
7480 Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
7481 Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
7483 function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
7484 BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
7487 Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
7488 Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
7490 function Int16BufferAttribute(array, itemSize, normalized) {
7491 BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
7494 Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
7495 Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
7497 function Uint16BufferAttribute(array, itemSize, normalized) {
7498 BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
7501 Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
7502 Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
7504 function Int32BufferAttribute(array, itemSize, normalized) {
7505 BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
7508 Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
7509 Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
7511 function Uint32BufferAttribute(array, itemSize, normalized) {
7512 BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
7515 Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
7516 Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
7518 function Float16BufferAttribute(array, itemSize, normalized) {
7519 BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
7522 Float16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
7523 Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
7524 Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
7526 function Float32BufferAttribute(array, itemSize, normalized) {
7527 BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
7530 Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
7531 Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
7533 function Float64BufferAttribute(array, itemSize, normalized) {
7534 BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
7537 Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
7538 Float64BufferAttribute.prototype.constructor = Float64BufferAttribute; //
7540 var DirectGeometry = /*#__PURE__*/function () {
7541 function DirectGeometry() {
7548 this.morphTargets = {};
7549 this.skinWeights = [];
7550 this.skinIndices = []; // this.lineDistances = [];
7552 this.boundingBox = null;
7553 this.boundingSphere = null; // update flags
7555 this.verticesNeedUpdate = false;
7556 this.normalsNeedUpdate = false;
7557 this.colorsNeedUpdate = false;
7558 this.uvsNeedUpdate = false;
7559 this.groupsNeedUpdate = false;
7562 var _proto = DirectGeometry.prototype;
7564 _proto.computeGroups = function computeGroups(geometry) {
7567 var materialIndex = undefined;
7568 var faces = geometry.faces;
7570 for (i = 0; i < faces.length; i++) {
7571 var face = faces[i]; // materials
7573 if (face.materialIndex !== materialIndex) {
7574 materialIndex = face.materialIndex;
7576 if (group !== undefined) {
7577 group.count = i * 3 - group.start;
7583 materialIndex: materialIndex
7588 if (group !== undefined) {
7589 group.count = i * 3 - group.start;
7593 this.groups = groups;
7596 _proto.fromGeometry = function fromGeometry(geometry) {
7597 var faces = geometry.faces;
7598 var vertices = geometry.vertices;
7599 var faceVertexUvs = geometry.faceVertexUvs;
7600 var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
7601 var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
7603 var morphTargets = geometry.morphTargets;
7604 var morphTargetsLength = morphTargets.length;
7605 var morphTargetsPosition;
7607 if (morphTargetsLength > 0) {
7608 morphTargetsPosition = [];
7610 for (var i = 0; i < morphTargetsLength; i++) {
7611 morphTargetsPosition[i] = {
7612 name: morphTargets[i].name,
7617 this.morphTargets.position = morphTargetsPosition;
7620 var morphNormals = geometry.morphNormals;
7621 var morphNormalsLength = morphNormals.length;
7622 var morphTargetsNormal;
7624 if (morphNormalsLength > 0) {
7625 morphTargetsNormal = [];
7627 for (var _i = 0; _i < morphNormalsLength; _i++) {
7628 morphTargetsNormal[_i] = {
7629 name: morphNormals[_i].name,
7634 this.morphTargets.normal = morphTargetsNormal;
7638 var skinIndices = geometry.skinIndices;
7639 var skinWeights = geometry.skinWeights;
7640 var hasSkinIndices = skinIndices.length === vertices.length;
7641 var hasSkinWeights = skinWeights.length === vertices.length; //
7643 if (vertices.length > 0 && faces.length === 0) {
7644 console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
7647 for (var _i2 = 0; _i2 < faces.length; _i2++) {
7648 var face = faces[_i2];
7649 this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
7650 var vertexNormals = face.vertexNormals;
7652 if (vertexNormals.length === 3) {
7653 this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
7655 var normal = face.normal;
7656 this.normals.push(normal, normal, normal);
7659 var vertexColors = face.vertexColors;
7661 if (vertexColors.length === 3) {
7662 this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
7664 var color = face.color;
7665 this.colors.push(color, color, color);
7668 if (hasFaceVertexUv === true) {
7669 var vertexUvs = faceVertexUvs[0][_i2];
7671 if (vertexUvs !== undefined) {
7672 this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
7674 console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', _i2);
7675 this.uvs.push(new Vector2(), new Vector2(), new Vector2());
7679 if (hasFaceVertexUv2 === true) {
7680 var _vertexUvs = faceVertexUvs[1][_i2];
7682 if (_vertexUvs !== undefined) {
7683 this.uvs2.push(_vertexUvs[0], _vertexUvs[1], _vertexUvs[2]);
7685 console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', _i2);
7686 this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
7691 for (var j = 0; j < morphTargetsLength; j++) {
7692 var morphTarget = morphTargets[j].vertices;
7693 morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
7696 for (var _j = 0; _j < morphNormalsLength; _j++) {
7697 var morphNormal = morphNormals[_j].vertexNormals[_i2];
7699 morphTargetsNormal[_j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
7703 if (hasSkinIndices) {
7704 this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
7707 if (hasSkinWeights) {
7708 this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
7712 this.computeGroups(geometry);
7713 this.verticesNeedUpdate = geometry.verticesNeedUpdate;
7714 this.normalsNeedUpdate = geometry.normalsNeedUpdate;
7715 this.colorsNeedUpdate = geometry.colorsNeedUpdate;
7716 this.uvsNeedUpdate = geometry.uvsNeedUpdate;
7717 this.groupsNeedUpdate = geometry.groupsNeedUpdate;
7719 if (geometry.boundingSphere !== null) {
7720 this.boundingSphere = geometry.boundingSphere.clone();
7723 if (geometry.boundingBox !== null) {
7724 this.boundingBox = geometry.boundingBox.clone();
7730 return DirectGeometry;
7733 function arrayMax(array) {
7734 if (array.length === 0) return -Infinity;
7737 for (var i = 1, l = array.length; i < l; ++i) {
7738 if (array[i] > max) max = array[i];
7744 var TYPED_ARRAYS = {
7745 Int8Array: Int8Array,
7746 Uint8Array: Uint8Array,
7747 // Workaround for IE11 pre KB2929437. See #11440
7748 Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
7749 Int16Array: Int16Array,
7750 Uint16Array: Uint16Array,
7751 Int32Array: Int32Array,
7752 Uint32Array: Uint32Array,
7753 Float32Array: Float32Array,
7754 Float64Array: Float64Array
7757 function getTypedArray(type, buffer) {
7758 return new TYPED_ARRAYS[type](buffer);
7761 var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
7763 var _m1$2 = new Matrix4();
7765 var _obj = new Object3D();
7767 var _offset = new Vector3();
7769 var _box$2 = new Box3();
7771 var _boxMorphTargets = new Box3();
7773 var _vector$4 = new Vector3();
7775 function BufferGeometry() {
7776 Object.defineProperty(this, 'id', {
7777 value: _bufferGeometryId += 2
7779 this.uuid = MathUtils.generateUUID();
7781 this.type = 'BufferGeometry';
7783 this.attributes = {};
7784 this.morphAttributes = {};
7785 this.morphTargetsRelative = false;
7787 this.boundingBox = null;
7788 this.boundingSphere = null;
7796 BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
7797 constructor: BufferGeometry,
7798 isBufferGeometry: true,
7799 getIndex: function getIndex() {
7802 setIndex: function setIndex(index) {
7803 if (Array.isArray(index)) {
7804 this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
7811 getAttribute: function getAttribute(name) {
7812 return this.attributes[name];
7814 setAttribute: function setAttribute(name, attribute) {
7815 this.attributes[name] = attribute;
7818 deleteAttribute: function deleteAttribute(name) {
7819 delete this.attributes[name];
7822 hasAttribute: function hasAttribute(name) {
7823 return this.attributes[name] !== undefined;
7825 addGroup: function addGroup(start, count, materialIndex) {
7826 if (materialIndex === void 0) {
7833 materialIndex: materialIndex
7836 clearGroups: function clearGroups() {
7839 setDrawRange: function setDrawRange(start, count) {
7840 this.drawRange.start = start;
7841 this.drawRange.count = count;
7843 applyMatrix4: function applyMatrix4(matrix) {
7844 var position = this.attributes.position;
7846 if (position !== undefined) {
7847 position.applyMatrix4(matrix);
7848 position.needsUpdate = true;
7851 var normal = this.attributes.normal;
7853 if (normal !== undefined) {
7854 var normalMatrix = new Matrix3().getNormalMatrix(matrix);
7855 normal.applyNormalMatrix(normalMatrix);
7856 normal.needsUpdate = true;
7859 var tangent = this.attributes.tangent;
7861 if (tangent !== undefined) {
7862 tangent.transformDirection(matrix);
7863 tangent.needsUpdate = true;
7866 if (this.boundingBox !== null) {
7867 this.computeBoundingBox();
7870 if (this.boundingSphere !== null) {
7871 this.computeBoundingSphere();
7876 rotateX: function rotateX(angle) {
7877 // rotate geometry around world x-axis
7878 _m1$2.makeRotationX(angle);
7880 this.applyMatrix4(_m1$2);
7883 rotateY: function rotateY(angle) {
7884 // rotate geometry around world y-axis
7885 _m1$2.makeRotationY(angle);
7887 this.applyMatrix4(_m1$2);
7890 rotateZ: function rotateZ(angle) {
7891 // rotate geometry around world z-axis
7892 _m1$2.makeRotationZ(angle);
7894 this.applyMatrix4(_m1$2);
7897 translate: function translate(x, y, z) {
7898 // translate geometry
7899 _m1$2.makeTranslation(x, y, z);
7901 this.applyMatrix4(_m1$2);
7904 scale: function scale(x, y, z) {
7906 _m1$2.makeScale(x, y, z);
7908 this.applyMatrix4(_m1$2);
7911 lookAt: function lookAt(vector) {
7912 _obj.lookAt(vector);
7914 _obj.updateMatrix();
7916 this.applyMatrix4(_obj.matrix);
7919 center: function center() {
7920 this.computeBoundingBox();
7921 this.boundingBox.getCenter(_offset).negate();
7922 this.translate(_offset.x, _offset.y, _offset.z);
7925 setFromObject: function setFromObject(object) {
7926 // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
7927 var geometry = object.geometry;
7929 if (object.isPoints || object.isLine) {
7930 var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
7931 var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
7932 this.setAttribute('position', positions.copyVector3sArray(geometry.vertices));
7933 this.setAttribute('color', colors.copyColorsArray(geometry.colors));
7935 if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
7936 var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
7937 this.setAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
7940 if (geometry.boundingSphere !== null) {
7941 this.boundingSphere = geometry.boundingSphere.clone();
7944 if (geometry.boundingBox !== null) {
7945 this.boundingBox = geometry.boundingBox.clone();
7947 } else if (object.isMesh) {
7948 if (geometry && geometry.isGeometry) {
7949 this.fromGeometry(geometry);
7955 setFromPoints: function setFromPoints(points) {
7958 for (var i = 0, l = points.length; i < l; i++) {
7959 var point = points[i];
7960 position.push(point.x, point.y, point.z || 0);
7963 this.setAttribute('position', new Float32BufferAttribute(position, 3));
7966 updateFromObject: function updateFromObject(object) {
7967 var geometry = object.geometry;
7969 if (object.isMesh) {
7970 var direct = geometry.__directGeometry;
7972 if (geometry.elementsNeedUpdate === true) {
7974 geometry.elementsNeedUpdate = false;
7977 if (direct === undefined) {
7978 return this.fromGeometry(geometry);
7981 direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
7982 direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
7983 direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
7984 direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
7985 direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
7986 geometry.verticesNeedUpdate = false;
7987 geometry.normalsNeedUpdate = false;
7988 geometry.colorsNeedUpdate = false;
7989 geometry.uvsNeedUpdate = false;
7990 geometry.groupsNeedUpdate = false;
7994 if (geometry.verticesNeedUpdate === true) {
7995 var attribute = this.attributes.position;
7997 if (attribute !== undefined) {
7998 attribute.copyVector3sArray(geometry.vertices);
7999 attribute.needsUpdate = true;
8002 geometry.verticesNeedUpdate = false;
8005 if (geometry.normalsNeedUpdate === true) {
8006 var _attribute = this.attributes.normal;
8008 if (_attribute !== undefined) {
8009 _attribute.copyVector3sArray(geometry.normals);
8011 _attribute.needsUpdate = true;
8014 geometry.normalsNeedUpdate = false;
8017 if (geometry.colorsNeedUpdate === true) {
8018 var _attribute2 = this.attributes.color;
8020 if (_attribute2 !== undefined) {
8021 _attribute2.copyColorsArray(geometry.colors);
8023 _attribute2.needsUpdate = true;
8026 geometry.colorsNeedUpdate = false;
8029 if (geometry.uvsNeedUpdate) {
8030 var _attribute3 = this.attributes.uv;
8032 if (_attribute3 !== undefined) {
8033 _attribute3.copyVector2sArray(geometry.uvs);
8035 _attribute3.needsUpdate = true;
8038 geometry.uvsNeedUpdate = false;
8041 if (geometry.lineDistancesNeedUpdate) {
8042 var _attribute4 = this.attributes.lineDistance;
8044 if (_attribute4 !== undefined) {
8045 _attribute4.copyArray(geometry.lineDistances);
8047 _attribute4.needsUpdate = true;
8050 geometry.lineDistancesNeedUpdate = false;
8053 if (geometry.groupsNeedUpdate) {
8054 geometry.computeGroups(object.geometry);
8055 this.groups = geometry.groups;
8056 geometry.groupsNeedUpdate = false;
8061 fromGeometry: function fromGeometry(geometry) {
8062 geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
8063 return this.fromDirectGeometry(geometry.__directGeometry);
8065 fromDirectGeometry: function fromDirectGeometry(geometry) {
8066 var positions = new Float32Array(geometry.vertices.length * 3);
8067 this.setAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
8069 if (geometry.normals.length > 0) {
8070 var normals = new Float32Array(geometry.normals.length * 3);
8071 this.setAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
8074 if (geometry.colors.length > 0) {
8075 var colors = new Float32Array(geometry.colors.length * 3);
8076 this.setAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
8079 if (geometry.uvs.length > 0) {
8080 var uvs = new Float32Array(geometry.uvs.length * 2);
8081 this.setAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
8084 if (geometry.uvs2.length > 0) {
8085 var uvs2 = new Float32Array(geometry.uvs2.length * 2);
8086 this.setAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
8090 this.groups = geometry.groups; // morphs
8092 for (var name in geometry.morphTargets) {
8094 var morphTargets = geometry.morphTargets[name];
8096 for (var i = 0, l = morphTargets.length; i < l; i++) {
8097 var morphTarget = morphTargets[i];
8098 var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
8099 attribute.name = morphTarget.name;
8100 array.push(attribute.copyVector3sArray(morphTarget.data));
8103 this.morphAttributes[name] = array;
8107 if (geometry.skinIndices.length > 0) {
8108 var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
8109 this.setAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
8112 if (geometry.skinWeights.length > 0) {
8113 var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
8114 this.setAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
8118 if (geometry.boundingSphere !== null) {
8119 this.boundingSphere = geometry.boundingSphere.clone();
8122 if (geometry.boundingBox !== null) {
8123 this.boundingBox = geometry.boundingBox.clone();
8128 computeBoundingBox: function computeBoundingBox() {
8129 if (this.boundingBox === null) {
8130 this.boundingBox = new Box3();
8133 var position = this.attributes.position;
8134 var morphAttributesPosition = this.morphAttributes.position;
8136 if (position && position.isGLBufferAttribute) {
8137 console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
8138 this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
8142 if (position !== undefined) {
8143 this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
8145 if (morphAttributesPosition) {
8146 for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
8147 var morphAttribute = morphAttributesPosition[i];
8149 _box$2.setFromBufferAttribute(morphAttribute);
8151 if (this.morphTargetsRelative) {
8152 _vector$4.addVectors(this.boundingBox.min, _box$2.min);
8154 this.boundingBox.expandByPoint(_vector$4);
8156 _vector$4.addVectors(this.boundingBox.max, _box$2.max);
8158 this.boundingBox.expandByPoint(_vector$4);
8160 this.boundingBox.expandByPoint(_box$2.min);
8161 this.boundingBox.expandByPoint(_box$2.max);
8166 this.boundingBox.makeEmpty();
8169 if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
8170 console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
8173 computeBoundingSphere: function computeBoundingSphere() {
8174 if (this.boundingSphere === null) {
8175 this.boundingSphere = new Sphere();
8178 var position = this.attributes.position;
8179 var morphAttributesPosition = this.morphAttributes.position;
8181 if (position && position.isGLBufferAttribute) {
8182 console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
8183 this.boundingSphere.set(new Vector3(), Infinity);
8188 // first, find the center of the bounding sphere
8189 var center = this.boundingSphere.center;
8191 _box$2.setFromBufferAttribute(position); // process morph attributes if present
8194 if (morphAttributesPosition) {
8195 for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
8196 var morphAttribute = morphAttributesPosition[i];
8198 _boxMorphTargets.setFromBufferAttribute(morphAttribute);
8200 if (this.morphTargetsRelative) {
8201 _vector$4.addVectors(_box$2.min, _boxMorphTargets.min);
8203 _box$2.expandByPoint(_vector$4);
8205 _vector$4.addVectors(_box$2.max, _boxMorphTargets.max);
8207 _box$2.expandByPoint(_vector$4);
8209 _box$2.expandByPoint(_boxMorphTargets.min);
8211 _box$2.expandByPoint(_boxMorphTargets.max);
8216 _box$2.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
8217 // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
8220 var maxRadiusSq = 0;
8222 for (var _i = 0, _il = position.count; _i < _il; _i++) {
8223 _vector$4.fromBufferAttribute(position, _i);
8225 maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
8226 } // process morph attributes if present
8229 if (morphAttributesPosition) {
8230 for (var _i2 = 0, _il2 = morphAttributesPosition.length; _i2 < _il2; _i2++) {
8231 var _morphAttribute = morphAttributesPosition[_i2];
8232 var morphTargetsRelative = this.morphTargetsRelative;
8234 for (var j = 0, jl = _morphAttribute.count; j < jl; j++) {
8235 _vector$4.fromBufferAttribute(_morphAttribute, j);
8237 if (morphTargetsRelative) {
8238 _offset.fromBufferAttribute(position, j);
8240 _vector$4.add(_offset);
8243 maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
8248 this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
8250 if (isNaN(this.boundingSphere.radius)) {
8251 console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
8255 computeFaceNormals: function computeFaceNormals() {// backwards compatibility
8257 computeVertexNormals: function computeVertexNormals() {
8258 var index = this.index;
8259 var positionAttribute = this.getAttribute('position');
8261 if (positionAttribute !== undefined) {
8262 var normalAttribute = this.getAttribute('normal');
8264 if (normalAttribute === undefined) {
8265 normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
8266 this.setAttribute('normal', normalAttribute);
8268 // reset existing normals to zero
8269 for (var i = 0, il = normalAttribute.count; i < il; i++) {
8270 normalAttribute.setXYZ(i, 0, 0, 0);
8274 var pA = new Vector3(),
8277 var nA = new Vector3(),
8280 var cb = new Vector3(),
8281 ab = new Vector3(); // indexed elements
8284 for (var _i3 = 0, _il3 = index.count; _i3 < _il3; _i3 += 3) {
8285 var vA = index.getX(_i3 + 0);
8286 var vB = index.getX(_i3 + 1);
8287 var vC = index.getX(_i3 + 2);
8288 pA.fromBufferAttribute(positionAttribute, vA);
8289 pB.fromBufferAttribute(positionAttribute, vB);
8290 pC.fromBufferAttribute(positionAttribute, vC);
8291 cb.subVectors(pC, pB);
8292 ab.subVectors(pA, pB);
8294 nA.fromBufferAttribute(normalAttribute, vA);
8295 nB.fromBufferAttribute(normalAttribute, vB);
8296 nC.fromBufferAttribute(normalAttribute, vC);
8300 normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
8301 normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
8302 normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
8305 // non-indexed elements (unconnected triangle soup)
8306 for (var _i4 = 0, _il4 = positionAttribute.count; _i4 < _il4; _i4 += 3) {
8307 pA.fromBufferAttribute(positionAttribute, _i4 + 0);
8308 pB.fromBufferAttribute(positionAttribute, _i4 + 1);
8309 pC.fromBufferAttribute(positionAttribute, _i4 + 2);
8310 cb.subVectors(pC, pB);
8311 ab.subVectors(pA, pB);
8313 normalAttribute.setXYZ(_i4 + 0, cb.x, cb.y, cb.z);
8314 normalAttribute.setXYZ(_i4 + 1, cb.x, cb.y, cb.z);
8315 normalAttribute.setXYZ(_i4 + 2, cb.x, cb.y, cb.z);
8319 this.normalizeNormals();
8320 normalAttribute.needsUpdate = true;
8323 merge: function merge(geometry, offset) {
8324 if (!(geometry && geometry.isBufferGeometry)) {
8325 console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
8329 if (offset === undefined) {
8331 console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
8334 var attributes = this.attributes;
8336 for (var key in attributes) {
8337 if (geometry.attributes[key] === undefined) continue;
8338 var attribute1 = attributes[key];
8339 var attributeArray1 = attribute1.array;
8340 var attribute2 = geometry.attributes[key];
8341 var attributeArray2 = attribute2.array;
8342 var attributeOffset = attribute2.itemSize * offset;
8343 var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
8345 for (var i = 0, j = attributeOffset; i < length; i++, j++) {
8346 attributeArray1[j] = attributeArray2[i];
8352 normalizeNormals: function normalizeNormals() {
8353 var normals = this.attributes.normal;
8355 for (var i = 0, il = normals.count; i < il; i++) {
8356 _vector$4.fromBufferAttribute(normals, i);
8358 _vector$4.normalize();
8360 normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
8363 toNonIndexed: function toNonIndexed() {
8364 function convertBufferAttribute(attribute, indices) {
8365 var array = attribute.array;
8366 var itemSize = attribute.itemSize;
8367 var normalized = attribute.normalized;
8368 var array2 = new array.constructor(indices.length * itemSize);
8372 for (var i = 0, l = indices.length; i < l; i++) {
8373 index = indices[i] * itemSize;
8375 for (var j = 0; j < itemSize; j++) {
8376 array2[index2++] = array[index++];
8380 return new BufferAttribute(array2, itemSize, normalized);
8384 if (this.index === null) {
8385 console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
8389 var geometry2 = new BufferGeometry();
8390 var indices = this.index.array;
8391 var attributes = this.attributes; // attributes
8393 for (var name in attributes) {
8394 var attribute = attributes[name];
8395 var newAttribute = convertBufferAttribute(attribute, indices);
8396 geometry2.setAttribute(name, newAttribute);
8397 } // morph attributes
8400 var morphAttributes = this.morphAttributes;
8402 for (var _name in morphAttributes) {
8403 var morphArray = [];
8404 var morphAttribute = morphAttributes[_name]; // morphAttribute: array of Float32BufferAttributes
8406 for (var i = 0, il = morphAttribute.length; i < il; i++) {
8407 var _attribute5 = morphAttribute[i];
8409 var _newAttribute = convertBufferAttribute(_attribute5, indices);
8411 morphArray.push(_newAttribute);
8414 geometry2.morphAttributes[_name] = morphArray;
8417 geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
8419 var groups = this.groups;
8421 for (var _i5 = 0, l = groups.length; _i5 < l; _i5++) {
8422 var group = groups[_i5];
8423 geometry2.addGroup(group.start, group.count, group.materialIndex);
8428 toJSON: function toJSON() {
8432 type: 'BufferGeometry',
8433 generator: 'BufferGeometry.toJSON'
8435 }; // standard BufferGeometry serialization
8437 data.uuid = this.uuid;
8438 data.type = this.type;
8439 if (this.name !== '') data.name = this.name;
8440 if (Object.keys(this.userData).length > 0) data.userData = this.userData;
8442 if (this.parameters !== undefined) {
8443 var parameters = this.parameters;
8445 for (var key in parameters) {
8446 if (parameters[key] !== undefined) data[key] = parameters[key];
8455 var index = this.index;
8457 if (index !== null) {
8459 type: index.array.constructor.name,
8460 array: Array.prototype.slice.call(index.array)
8464 var attributes = this.attributes;
8466 for (var _key in attributes) {
8467 var attribute = attributes[_key];
8468 var attributeData = attribute.toJSON(data.data);
8469 if (attribute.name !== '') attributeData.name = attribute.name;
8470 data.data.attributes[_key] = attributeData;
8473 var morphAttributes = {};
8474 var hasMorphAttributes = false;
8476 for (var _key2 in this.morphAttributes) {
8477 var attributeArray = this.morphAttributes[_key2];
8480 for (var i = 0, il = attributeArray.length; i < il; i++) {
8481 var _attribute6 = attributeArray[i];
8483 var _attributeData = _attribute6.toJSON(data.data);
8485 if (_attribute6.name !== '') _attributeData.name = _attribute6.name;
8486 array.push(_attributeData);
8489 if (array.length > 0) {
8490 morphAttributes[_key2] = array;
8491 hasMorphAttributes = true;
8495 if (hasMorphAttributes) {
8496 data.data.morphAttributes = morphAttributes;
8497 data.data.morphTargetsRelative = this.morphTargetsRelative;
8500 var groups = this.groups;
8502 if (groups.length > 0) {
8503 data.data.groups = JSON.parse(JSON.stringify(groups));
8506 var boundingSphere = this.boundingSphere;
8508 if (boundingSphere !== null) {
8509 data.data.boundingSphere = {
8510 center: boundingSphere.center.toArray(),
8511 radius: boundingSphere.radius
8517 clone: function clone() {
8519 // Handle primitives
8520 const parameters = this.parameters;
8521 if ( parameters !== undefined ) {
8523 for ( const key in parameters ) {
8524 values.push( parameters[ key ] );
8526 const geometry = Object.create( this.constructor.prototype );
8527 this.constructor.apply( geometry, values );
8530 return new this.constructor().copy( this );
8532 return new BufferGeometry().copy(this);
8534 copy: function copy(source) {
8537 this.attributes = {};
8538 this.morphAttributes = {};
8540 this.boundingBox = null;
8541 this.boundingSphere = null; // used for storing cloned, shared data
8543 var data = {}; // name
8545 this.name = source.name; // index
8547 var index = source.index;
8549 if (index !== null) {
8550 this.setIndex(index.clone(data));
8554 var attributes = source.attributes;
8556 for (var name in attributes) {
8557 var attribute = attributes[name];
8558 this.setAttribute(name, attribute.clone(data));
8559 } // morph attributes
8562 var morphAttributes = source.morphAttributes;
8564 for (var _name2 in morphAttributes) {
8566 var morphAttribute = morphAttributes[_name2]; // morphAttribute: array of Float32BufferAttributes
8568 for (var i = 0, l = morphAttribute.length; i < l; i++) {
8569 array.push(morphAttribute[i].clone(data));
8572 this.morphAttributes[_name2] = array;
8575 this.morphTargetsRelative = source.morphTargetsRelative; // groups
8577 var groups = source.groups;
8579 for (var _i6 = 0, _l = groups.length; _i6 < _l; _i6++) {
8580 var group = groups[_i6];
8581 this.addGroup(group.start, group.count, group.materialIndex);
8585 var boundingBox = source.boundingBox;
8587 if (boundingBox !== null) {
8588 this.boundingBox = boundingBox.clone();
8589 } // bounding sphere
8592 var boundingSphere = source.boundingSphere;
8594 if (boundingSphere !== null) {
8595 this.boundingSphere = boundingSphere.clone();
8599 this.drawRange.start = source.drawRange.start;
8600 this.drawRange.count = source.drawRange.count; // user data
8602 this.userData = source.userData;
8605 dispose: function dispose() {
8606 this.dispatchEvent({
8612 var _inverseMatrix = new Matrix4();
8614 var _ray = new Ray();
8616 var _sphere = new Sphere();
8618 var _vA = new Vector3();
8620 var _vB = new Vector3();
8622 var _vC = new Vector3();
8624 var _tempA = new Vector3();
8626 var _tempB = new Vector3();
8628 var _tempC = new Vector3();
8630 var _morphA = new Vector3();
8632 var _morphB = new Vector3();
8634 var _morphC = new Vector3();
8636 var _uvA = new Vector2();
8638 var _uvB = new Vector2();
8640 var _uvC = new Vector2();
8642 var _intersectionPoint = new Vector3();
8644 var _intersectionPointWorld = new Vector3();
8646 function Mesh(geometry, material) {
8647 Object3D.call(this);
8649 this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
8650 this.material = material !== undefined ? material : new MeshBasicMaterial();
8651 this.updateMorphTargets();
8654 Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
8657 copy: function copy(source) {
8658 Object3D.prototype.copy.call(this, source);
8660 if (source.morphTargetInfluences !== undefined) {
8661 this.morphTargetInfluences = source.morphTargetInfluences.slice();
8664 if (source.morphTargetDictionary !== undefined) {
8665 this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
8668 this.material = source.material;
8669 this.geometry = source.geometry;
8672 updateMorphTargets: function updateMorphTargets() {
8673 var geometry = this.geometry;
8675 if (geometry.isBufferGeometry) {
8676 var morphAttributes = geometry.morphAttributes;
8677 var keys = Object.keys(morphAttributes);
8679 if (keys.length > 0) {
8680 var morphAttribute = morphAttributes[keys[0]];
8682 if (morphAttribute !== undefined) {
8683 this.morphTargetInfluences = [];
8684 this.morphTargetDictionary = {};
8686 for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
8687 var name = morphAttribute[m].name || String(m);
8688 this.morphTargetInfluences.push(0);
8689 this.morphTargetDictionary[name] = m;
8694 var morphTargets = geometry.morphTargets;
8696 if (morphTargets !== undefined && morphTargets.length > 0) {
8697 console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
8701 raycast: function raycast(raycaster, intersects) {
8702 var geometry = this.geometry;
8703 var material = this.material;
8704 var matrixWorld = this.matrixWorld;
8705 if (material === undefined) return; // Checking boundingSphere distance to ray
8707 if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
8709 _sphere.copy(geometry.boundingSphere);
8711 _sphere.applyMatrix4(matrixWorld);
8713 if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
8715 _inverseMatrix.copy(matrixWorld).invert();
8717 _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
8720 if (geometry.boundingBox !== null) {
8721 if (_ray.intersectsBox(geometry.boundingBox) === false) return;
8726 if (geometry.isBufferGeometry) {
8727 var index = geometry.index;
8728 var position = geometry.attributes.position;
8729 var morphPosition = geometry.morphAttributes.position;
8730 var morphTargetsRelative = geometry.morphTargetsRelative;
8731 var uv = geometry.attributes.uv;
8732 var uv2 = geometry.attributes.uv2;
8733 var groups = geometry.groups;
8734 var drawRange = geometry.drawRange;
8736 if (index !== null) {
8737 // indexed buffer geometry
8738 if (Array.isArray(material)) {
8739 for (var i = 0, il = groups.length; i < il; i++) {
8740 var group = groups[i];
8741 var groupMaterial = material[group.materialIndex];
8742 var start = Math.max(group.start, drawRange.start);
8743 var end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
8745 for (var j = start, jl = end; j < jl; j += 3) {
8746 var a = index.getX(j);
8747 var b = index.getX(j + 1);
8748 var c = index.getX(j + 2);
8749 intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
8752 intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
8754 intersection.face.materialIndex = group.materialIndex;
8755 intersects.push(intersection);
8760 var _start = Math.max(0, drawRange.start);
8762 var _end = Math.min(index.count, drawRange.start + drawRange.count);
8764 for (var _i = _start, _il = _end; _i < _il; _i += 3) {
8765 var _a = index.getX(_i);
8767 var _b = index.getX(_i + 1);
8769 var _c = index.getX(_i + 2);
8771 intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a, _b, _c);
8774 intersection.faceIndex = Math.floor(_i / 3); // triangle number in indexed buffer semantics
8776 intersects.push(intersection);
8780 } else if (position !== undefined) {
8781 // non-indexed buffer geometry
8782 if (Array.isArray(material)) {
8783 for (var _i2 = 0, _il2 = groups.length; _i2 < _il2; _i2++) {
8784 var _group = groups[_i2];
8785 var _groupMaterial = material[_group.materialIndex];
8787 var _start2 = Math.max(_group.start, drawRange.start);
8789 var _end2 = Math.min(_group.start + _group.count, drawRange.start + drawRange.count);
8791 for (var _j = _start2, _jl = _end2; _j < _jl; _j += 3) {
8798 intersection = checkBufferGeometryIntersection(this, _groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a2, _b2, _c2);
8801 intersection.faceIndex = Math.floor(_j / 3); // triangle number in non-indexed buffer semantics
8803 intersection.face.materialIndex = _group.materialIndex;
8804 intersects.push(intersection);
8809 var _start3 = Math.max(0, drawRange.start);
8811 var _end3 = Math.min(position.count, drawRange.start + drawRange.count);
8813 for (var _i3 = _start3, _il3 = _end3; _i3 < _il3; _i3 += 3) {
8820 intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a3, _b3, _c3);
8823 intersection.faceIndex = Math.floor(_i3 / 3); // triangle number in non-indexed buffer semantics
8825 intersects.push(intersection);
8830 } else if (geometry.isGeometry) {
8831 var isMultiMaterial = Array.isArray(material);
8832 var vertices = geometry.vertices;
8833 var faces = geometry.faces;
8835 var faceVertexUvs = geometry.faceVertexUvs[0];
8836 if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
8838 for (var f = 0, fl = faces.length; f < fl; f++) {
8839 var face = faces[f];
8840 var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
8841 if (faceMaterial === undefined) continue;
8842 var fvA = vertices[face.a];
8843 var fvB = vertices[face.b];
8844 var fvC = vertices[face.c];
8845 intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
8848 if (uvs && uvs[f]) {
8851 _uvA.copy(uvs_f[0]);
8853 _uvB.copy(uvs_f[1]);
8855 _uvC.copy(uvs_f[2]);
8857 intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
8860 intersection.face = face;
8861 intersection.faceIndex = f;
8862 intersects.push(intersection);
8869 function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
8872 if (material.side === BackSide) {
8873 intersect = ray.intersectTriangle(pC, pB, pA, true, point);
8875 intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
8878 if (intersect === null) return null;
8880 _intersectionPointWorld.copy(point);
8882 _intersectionPointWorld.applyMatrix4(object.matrixWorld);
8884 var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
8885 if (distance < raycaster.near || distance > raycaster.far) return null;
8888 point: _intersectionPointWorld.clone(),
8893 function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
8894 _vA.fromBufferAttribute(position, a);
8896 _vB.fromBufferAttribute(position, b);
8898 _vC.fromBufferAttribute(position, c);
8900 var morphInfluences = object.morphTargetInfluences;
8902 if (material.morphTargets && morphPosition && morphInfluences) {
8903 _morphA.set(0, 0, 0);
8905 _morphB.set(0, 0, 0);
8907 _morphC.set(0, 0, 0);
8909 for (var i = 0, il = morphPosition.length; i < il; i++) {
8910 var influence = morphInfluences[i];
8911 var morphAttribute = morphPosition[i];
8912 if (influence === 0) continue;
8914 _tempA.fromBufferAttribute(morphAttribute, a);
8916 _tempB.fromBufferAttribute(morphAttribute, b);
8918 _tempC.fromBufferAttribute(morphAttribute, c);
8920 if (morphTargetsRelative) {
8921 _morphA.addScaledVector(_tempA, influence);
8923 _morphB.addScaledVector(_tempB, influence);
8925 _morphC.addScaledVector(_tempC, influence);
8927 _morphA.addScaledVector(_tempA.sub(_vA), influence);
8929 _morphB.addScaledVector(_tempB.sub(_vB), influence);
8931 _morphC.addScaledVector(_tempC.sub(_vC), influence);
8942 if (object.isSkinnedMesh) {
8943 object.boneTransform(a, _vA);
8944 object.boneTransform(b, _vB);
8945 object.boneTransform(c, _vC);
8948 var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
8952 _uvA.fromBufferAttribute(uv, a);
8954 _uvB.fromBufferAttribute(uv, b);
8956 _uvC.fromBufferAttribute(uv, c);
8958 intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
8962 _uvA.fromBufferAttribute(uv2, a);
8964 _uvB.fromBufferAttribute(uv2, b);
8966 _uvC.fromBufferAttribute(uv2, c);
8968 intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
8971 var face = new Face3(a, b, c);
8972 Triangle.getNormal(_vA, _vB, _vC, face.normal);
8973 intersection.face = face;
8976 return intersection;
8979 var BoxBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
8980 _inheritsLoose(BoxBufferGeometry, _BufferGeometry);
8982 function BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments) {
8985 if (width === void 0) {
8989 if (height === void 0) {
8993 if (depth === void 0) {
8997 if (widthSegments === void 0) {
9001 if (heightSegments === void 0) {
9005 if (depthSegments === void 0) {
9009 _this = _BufferGeometry.call(this) || this;
9010 _this.type = 'BoxBufferGeometry';
9011 _this.parameters = {
9015 widthSegments: widthSegments,
9016 heightSegments: heightSegments,
9017 depthSegments: depthSegments
9020 var scope = _assertThisInitialized(_this); // segments
9023 widthSegments = Math.floor(widthSegments);
9024 heightSegments = Math.floor(heightSegments);
9025 depthSegments = Math.floor(depthSegments); // buffers
9030 var uvs = []; // helper variables
9032 var numberOfVertices = 0;
9033 var groupStart = 0; // build each side of the box geometry
9035 buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
9037 buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
9039 buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
9041 buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
9043 buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
9045 buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
9048 _this.setIndex(indices);
9050 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
9052 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
9054 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
9056 function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
9057 var segmentWidth = width / gridX;
9058 var segmentHeight = height / gridY;
9059 var widthHalf = width / 2;
9060 var heightHalf = height / 2;
9061 var depthHalf = depth / 2;
9062 var gridX1 = gridX + 1;
9063 var gridY1 = gridY + 1;
9064 var vertexCounter = 0;
9066 var vector = new Vector3(); // generate vertices, normals and uvs
9068 for (var iy = 0; iy < gridY1; iy++) {
9069 var y = iy * segmentHeight - heightHalf;
9071 for (var ix = 0; ix < gridX1; ix++) {
9072 var x = ix * segmentWidth - widthHalf; // set values to correct vector component
9074 vector[u] = x * udir;
9075 vector[v] = y * vdir;
9076 vector[w] = depthHalf; // now apply vector to vertex buffer
9078 vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
9082 vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
9084 normals.push(vector.x, vector.y, vector.z); // uvs
9086 uvs.push(ix / gridX);
9087 uvs.push(1 - iy / gridY); // counters
9092 // 1. you need three indices to draw a single face
9093 // 2. a single segment consists of two faces
9094 // 3. so we need to generate six (2*3) indices per segment
9097 for (var _iy = 0; _iy < gridY; _iy++) {
9098 for (var _ix = 0; _ix < gridX; _ix++) {
9099 var a = numberOfVertices + _ix + gridX1 * _iy;
9100 var b = numberOfVertices + _ix + gridX1 * (_iy + 1);
9101 var c = numberOfVertices + (_ix + 1) + gridX1 * (_iy + 1);
9102 var d = numberOfVertices + (_ix + 1) + gridX1 * _iy; // faces
9104 indices.push(a, b, d);
9105 indices.push(b, c, d); // increase counter
9109 } // add a group to the geometry. this will ensure multi material support
9112 scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
9114 groupStart += groupCount; // update total number of vertices
9116 numberOfVertices += vertexCounter;
9122 return BoxBufferGeometry;
9128 function cloneUniforms(src) {
9131 for (var u in src) {
9134 for (var p in src[u]) {
9135 var property = src[u][p];
9137 if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
9138 dst[u][p] = property.clone();
9139 } else if (Array.isArray(property)) {
9140 dst[u][p] = property.slice();
9142 dst[u][p] = property;
9149 function mergeUniforms(uniforms) {
9152 for (var u = 0; u < uniforms.length; u++) {
9153 var tmp = cloneUniforms(uniforms[u]);
9155 for (var p in tmp) {
9163 var UniformsUtils = {
9164 clone: cloneUniforms,
9165 merge: mergeUniforms
9168 var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
9170 var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
9174 * defines: { "label" : "value" },
9175 * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
9177 * fragmentShader: <string>,
9178 * vertexShader: <string>,
9180 * wireframe: <boolean>,
9181 * wireframeLinewidth: <float>,
9186 * morphTargets: <bool>,
9187 * morphNormals: <bool>
9191 function ShaderMaterial(parameters) {
9192 Material.call(this);
9193 this.type = 'ShaderMaterial';
9196 this.vertexShader = default_vertex;
9197 this.fragmentShader = default_fragment;
9199 this.wireframe = false;
9200 this.wireframeLinewidth = 1;
9201 this.fog = false; // set to use scene fog
9203 this.lights = false; // set to use scene lights
9205 this.clipping = false; // set to use user-defined clipping planes
9207 this.skinning = false; // set to use skinning attribute streams
9209 this.morphTargets = false; // set to use morph targets
9211 this.morphNormals = false; // set to use morph normals
9215 // set to use derivatives
9217 // set to use fragment depth values
9219 // set to use draw buffers
9220 shaderTextureLOD: false // set to use shader texture LOD
9222 }; // When rendered geometry doesn't include these attributes but the material does,
9223 // use these default values in WebGL. This avoids errors when buffer data is missing.
9225 this.defaultAttributeValues = {
9230 this.index0AttributeName = undefined;
9231 this.uniformsNeedUpdate = false;
9232 this.glslVersion = null;
9234 if (parameters !== undefined) {
9235 if (parameters.attributes !== undefined) {
9236 console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
9239 this.setValues(parameters);
9243 ShaderMaterial.prototype = Object.create(Material.prototype);
9244 ShaderMaterial.prototype.constructor = ShaderMaterial;
9245 ShaderMaterial.prototype.isShaderMaterial = true;
9247 ShaderMaterial.prototype.copy = function (source) {
9248 Material.prototype.copy.call(this, source);
9249 this.fragmentShader = source.fragmentShader;
9250 this.vertexShader = source.vertexShader;
9251 this.uniforms = cloneUniforms(source.uniforms);
9252 this.defines = Object.assign({}, source.defines);
9253 this.wireframe = source.wireframe;
9254 this.wireframeLinewidth = source.wireframeLinewidth;
9255 this.lights = source.lights;
9256 this.clipping = source.clipping;
9257 this.skinning = source.skinning;
9258 this.morphTargets = source.morphTargets;
9259 this.morphNormals = source.morphNormals;
9260 this.extensions = Object.assign({}, source.extensions);
9261 this.glslVersion = source.glslVersion;
9265 ShaderMaterial.prototype.toJSON = function (meta) {
9266 var data = Material.prototype.toJSON.call(this, meta);
9267 data.glslVersion = this.glslVersion;
9270 for (var name in this.uniforms) {
9271 var uniform = this.uniforms[name];
9272 var value = uniform.value;
9274 if (value && value.isTexture) {
9275 data.uniforms[name] = {
9277 value: value.toJSON(meta).uuid
9279 } else if (value && value.isColor) {
9280 data.uniforms[name] = {
9282 value: value.getHex()
9284 } else if (value && value.isVector2) {
9285 data.uniforms[name] = {
9287 value: value.toArray()
9289 } else if (value && value.isVector3) {
9290 data.uniforms[name] = {
9292 value: value.toArray()
9294 } else if (value && value.isVector4) {
9295 data.uniforms[name] = {
9297 value: value.toArray()
9299 } else if (value && value.isMatrix3) {
9300 data.uniforms[name] = {
9302 value: value.toArray()
9304 } else if (value && value.isMatrix4) {
9305 data.uniforms[name] = {
9307 value: value.toArray()
9310 data.uniforms[name] = {
9312 }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
9316 if (Object.keys(this.defines).length > 0) data.defines = this.defines;
9317 data.vertexShader = this.vertexShader;
9318 data.fragmentShader = this.fragmentShader;
9319 var extensions = {};
9321 for (var key in this.extensions) {
9322 if (this.extensions[key] === true) extensions[key] = true;
9325 if (Object.keys(extensions).length > 0) data.extensions = extensions;
9330 Object3D.call(this);
9331 this.type = 'Camera';
9332 this.matrixWorldInverse = new Matrix4();
9333 this.projectionMatrix = new Matrix4();
9334 this.projectionMatrixInverse = new Matrix4();
9337 Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
9338 constructor: Camera,
9340 copy: function copy(source, recursive) {
9341 Object3D.prototype.copy.call(this, source, recursive);
9342 this.matrixWorldInverse.copy(source.matrixWorldInverse);
9343 this.projectionMatrix.copy(source.projectionMatrix);
9344 this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
9347 getWorldDirection: function getWorldDirection(target) {
9348 if (target === undefined) {
9349 console.warn('THREE.Camera: .getWorldDirection() target is now required');
9350 target = new Vector3();
9353 this.updateWorldMatrix(true, false);
9354 var e = this.matrixWorld.elements;
9355 return target.set(-e[8], -e[9], -e[10]).normalize();
9357 updateMatrixWorld: function updateMatrixWorld(force) {
9358 Object3D.prototype.updateMatrixWorld.call(this, force);
9359 this.matrixWorldInverse.copy(this.matrixWorld).invert();
9361 updateWorldMatrix: function updateWorldMatrix(updateParents, updateChildren) {
9362 Object3D.prototype.updateWorldMatrix.call(this, updateParents, updateChildren);
9363 this.matrixWorldInverse.copy(this.matrixWorld).invert();
9365 clone: function clone() {
9366 return new this.constructor().copy(this);
9370 function PerspectiveCamera(fov, aspect, near, far) {
9371 if (fov === void 0) {
9375 if (aspect === void 0) {
9379 if (near === void 0) {
9383 if (far === void 0) {
9388 this.type = 'PerspectiveCamera';
9394 this.aspect = aspect;
9396 this.filmGauge = 35; // width of the film (default in millimeters)
9398 this.filmOffset = 0; // horizontal film offset (same unit as gauge)
9400 this.updateProjectionMatrix();
9403 PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
9404 constructor: PerspectiveCamera,
9405 isPerspectiveCamera: true,
9406 copy: function copy(source, recursive) {
9407 Camera.prototype.copy.call(this, source, recursive);
9408 this.fov = source.fov;
9409 this.zoom = source.zoom;
9410 this.near = source.near;
9411 this.far = source.far;
9412 this.focus = source.focus;
9413 this.aspect = source.aspect;
9414 this.view = source.view === null ? null : Object.assign({}, source.view);
9415 this.filmGauge = source.filmGauge;
9416 this.filmOffset = source.filmOffset;
9421 * Sets the FOV by focal length in respect to the current .filmGauge.
9423 * The default film gauge is 35, so that the focal length can be specified for
9424 * a 35mm (full frame) camera.
9426 * Values for focal length and film gauge must have the same unit.
9428 setFocalLength: function setFocalLength(focalLength) {
9429 // see http://www.bobatkins.com/photography/technical/field_of_view.html
9430 var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
9431 this.fov = MathUtils.RAD2DEG * 2 * Math.atan(vExtentSlope);
9432 this.updateProjectionMatrix();
9436 * Calculates the focal length from the current .fov and .filmGauge.
9438 getFocalLength: function getFocalLength() {
9439 var vExtentSlope = Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov);
9440 return 0.5 * this.getFilmHeight() / vExtentSlope;
9442 getEffectiveFOV: function getEffectiveFOV() {
9443 return MathUtils.RAD2DEG * 2 * Math.atan(Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom);
9445 getFilmWidth: function getFilmWidth() {
9446 // film not completely covered in portrait format (aspect < 1)
9447 return this.filmGauge * Math.min(this.aspect, 1);
9449 getFilmHeight: function getFilmHeight() {
9450 // film not completely covered in landscape format (aspect > 1)
9451 return this.filmGauge / Math.max(this.aspect, 1);
9455 * Sets an offset in a larger frustum. This is useful for multi-window or
9456 * multi-monitor/multi-machine setups.
9458 * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
9459 * the monitors are in grid like this
9467 * then for each monitor you would call it like this
9471 * const fullWidth = w * 3;
9472 * const fullHeight = h * 2;
9475 * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
9477 * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
9479 * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
9481 * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
9483 * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
9485 * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
9487 * Note there is no reason monitors have to be the same size or in a grid.
9489 setViewOffset: function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
9490 this.aspect = fullWidth / fullHeight;
9492 if (this.view === null) {
9504 this.view.enabled = true;
9505 this.view.fullWidth = fullWidth;
9506 this.view.fullHeight = fullHeight;
9507 this.view.offsetX = x;
9508 this.view.offsetY = y;
9509 this.view.width = width;
9510 this.view.height = height;
9511 this.updateProjectionMatrix();
9513 clearViewOffset: function clearViewOffset() {
9514 if (this.view !== null) {
9515 this.view.enabled = false;
9518 this.updateProjectionMatrix();
9520 updateProjectionMatrix: function updateProjectionMatrix() {
9521 var near = this.near;
9522 var top = near * Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom;
9523 var height = 2 * top;
9524 var width = this.aspect * height;
9525 var left = -0.5 * width;
9526 var view = this.view;
9528 if (this.view !== null && this.view.enabled) {
9529 var fullWidth = view.fullWidth,
9530 fullHeight = view.fullHeight;
9531 left += view.offsetX * width / fullWidth;
9532 top -= view.offsetY * height / fullHeight;
9533 width *= view.width / fullWidth;
9534 height *= view.height / fullHeight;
9537 var skew = this.filmOffset;
9538 if (skew !== 0) left += near * skew / this.getFilmWidth();
9539 this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
9540 this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
9542 toJSON: function toJSON(meta) {
9543 var data = Object3D.prototype.toJSON.call(this, meta);
9544 data.object.fov = this.fov;
9545 data.object.zoom = this.zoom;
9546 data.object.near = this.near;
9547 data.object.far = this.far;
9548 data.object.focus = this.focus;
9549 data.object.aspect = this.aspect;
9550 if (this.view !== null) data.object.view = Object.assign({}, this.view);
9551 data.object.filmGauge = this.filmGauge;
9552 data.object.filmOffset = this.filmOffset;
9560 function CubeCamera(near, far, renderTarget) {
9561 Object3D.call(this);
9562 this.type = 'CubeCamera';
9564 if (renderTarget.isWebGLCubeRenderTarget !== true) {
9565 console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
9569 this.renderTarget = renderTarget;
9570 var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
9571 cameraPX.layers = this.layers;
9572 cameraPX.up.set(0, -1, 0);
9573 cameraPX.lookAt(new Vector3(1, 0, 0));
9575 var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
9576 cameraNX.layers = this.layers;
9577 cameraNX.up.set(0, -1, 0);
9578 cameraNX.lookAt(new Vector3(-1, 0, 0));
9580 var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
9581 cameraPY.layers = this.layers;
9582 cameraPY.up.set(0, 0, 1);
9583 cameraPY.lookAt(new Vector3(0, 1, 0));
9585 var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
9586 cameraNY.layers = this.layers;
9587 cameraNY.up.set(0, 0, -1);
9588 cameraNY.lookAt(new Vector3(0, -1, 0));
9590 var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
9591 cameraPZ.layers = this.layers;
9592 cameraPZ.up.set(0, -1, 0);
9593 cameraPZ.lookAt(new Vector3(0, 0, 1));
9595 var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
9596 cameraNZ.layers = this.layers;
9597 cameraNZ.up.set(0, -1, 0);
9598 cameraNZ.lookAt(new Vector3(0, 0, -1));
9601 this.update = function (renderer, scene) {
9602 if (this.parent === null) this.updateMatrixWorld();
9603 var currentXrEnabled = renderer.xr.enabled;
9604 var currentRenderTarget = renderer.getRenderTarget();
9605 renderer.xr.enabled = false;
9606 var generateMipmaps = renderTarget.texture.generateMipmaps;
9607 renderTarget.texture.generateMipmaps = false;
9608 renderer.setRenderTarget(renderTarget, 0);
9609 renderer.render(scene, cameraPX);
9610 renderer.setRenderTarget(renderTarget, 1);
9611 renderer.render(scene, cameraNX);
9612 renderer.setRenderTarget(renderTarget, 2);
9613 renderer.render(scene, cameraPY);
9614 renderer.setRenderTarget(renderTarget, 3);
9615 renderer.render(scene, cameraNY);
9616 renderer.setRenderTarget(renderTarget, 4);
9617 renderer.render(scene, cameraPZ);
9618 renderTarget.texture.generateMipmaps = generateMipmaps;
9619 renderer.setRenderTarget(renderTarget, 5);
9620 renderer.render(scene, cameraNZ);
9621 renderer.setRenderTarget(currentRenderTarget);
9622 renderer.xr.enabled = currentXrEnabled;
9626 CubeCamera.prototype = Object.create(Object3D.prototype);
9627 CubeCamera.prototype.constructor = CubeCamera;
9629 function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
9630 images = images !== undefined ? images : [];
9631 mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
9632 format = format !== undefined ? format : RGBFormat;
9633 Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
9634 this.flipY = false; // Why CubeTexture._needsFlipEnvMap is necessary:
9636 // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
9637 // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
9638 // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
9639 // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
9640 // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
9641 // when using WebGLCubeRenderTarget.texture as a cube texture.
9643 this._needsFlipEnvMap = true;
9646 CubeTexture.prototype = Object.create(Texture.prototype);
9647 CubeTexture.prototype.constructor = CubeTexture;
9648 CubeTexture.prototype.isCubeTexture = true;
9649 Object.defineProperty(CubeTexture.prototype, 'images', {
9650 get: function get() {
9653 set: function set(value) {
9658 function WebGLCubeRenderTarget(size, options, dummy) {
9659 if (Number.isInteger(options)) {
9660 console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
9664 WebGLRenderTarget.call(this, size, size, options);
9665 options = options || {};
9666 this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
9667 this.texture._needsFlipEnvMap = false;
9670 WebGLCubeRenderTarget.prototype = Object.create(WebGLRenderTarget.prototype);
9671 WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
9672 WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
9674 WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function (renderer, texture) {
9675 this.texture.type = texture.type;
9676 this.texture.format = RGBAFormat; // see #18859
9678 this.texture.encoding = texture.encoding;
9679 this.texture.generateMipmaps = texture.generateMipmaps;
9680 this.texture.minFilter = texture.minFilter;
9681 this.texture.magFilter = texture.magFilter;
9690 "\n\n\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t#include <begin_vertex>\n\t\t\t\t#include <project_vertex>\n\n\t\t\t}\n\t\t",
9693 "\n\n\t\t\tuniform sampler2D tEquirect;\n\n\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t}\n\t\t"
9695 var geometry = new BoxBufferGeometry(5, 5, 5);
9696 var material = new ShaderMaterial({
9697 name: 'CubemapFromEquirect',
9698 uniforms: cloneUniforms(shader.uniforms),
9699 vertexShader: shader.vertexShader,
9700 fragmentShader: shader.fragmentShader,
9702 blending: NoBlending
9704 material.uniforms.tEquirect.value = texture;
9705 var mesh = new Mesh(geometry, material);
9706 var currentMinFilter = texture.minFilter; // Avoid blurred poles
9708 if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
9709 var camera = new CubeCamera(1, 10, this);
9710 camera.update(renderer, mesh);
9711 texture.minFilter = currentMinFilter;
9712 mesh.geometry.dispose();
9713 mesh.material.dispose();
9717 WebGLCubeRenderTarget.prototype.clear = function (renderer, color, depth, stencil) {
9718 var currentRenderTarget = renderer.getRenderTarget();
9720 for (var i = 0; i < 6; i++) {
9721 renderer.setRenderTarget(this, i);
9722 renderer.clear(color, depth, stencil);
9725 renderer.setRenderTarget(currentRenderTarget);
9728 function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
9729 Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
9735 this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
9736 this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
9737 this.generateMipmaps = false;
9739 this.unpackAlignment = 1;
9740 this.needsUpdate = true;
9743 DataTexture.prototype = Object.create(Texture.prototype);
9744 DataTexture.prototype.constructor = DataTexture;
9745 DataTexture.prototype.isDataTexture = true;
9747 var _sphere$1 = /*@__PURE__*/new Sphere();
9749 var _vector$5 = /*@__PURE__*/new Vector3();
9751 var Frustum = /*#__PURE__*/function () {
9752 function Frustum(p0, p1, p2, p3, p4, p5) {
9753 this.planes = [p0 !== undefined ? p0 : new Plane(), p1 !== undefined ? p1 : new Plane(), p2 !== undefined ? p2 : new Plane(), p3 !== undefined ? p3 : new Plane(), p4 !== undefined ? p4 : new Plane(), p5 !== undefined ? p5 : new Plane()];
9756 var _proto = Frustum.prototype;
9758 _proto.set = function set(p0, p1, p2, p3, p4, p5) {
9759 var planes = this.planes;
9769 _proto.clone = function clone() {
9770 return new this.constructor().copy(this);
9773 _proto.copy = function copy(frustum) {
9774 var planes = this.planes;
9776 for (var i = 0; i < 6; i++) {
9777 planes[i].copy(frustum.planes[i]);
9783 _proto.setFromProjectionMatrix = function setFromProjectionMatrix(m) {
9784 var planes = this.planes;
9785 var me = m.elements;
9802 planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
9803 planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
9804 planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
9805 planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
9806 planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
9807 planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
9811 _proto.intersectsObject = function intersectsObject(object) {
9812 var geometry = object.geometry;
9813 if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
9815 _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
9817 return this.intersectsSphere(_sphere$1);
9820 _proto.intersectsSprite = function intersectsSprite(sprite) {
9821 _sphere$1.center.set(0, 0, 0);
9823 _sphere$1.radius = 0.7071067811865476;
9825 _sphere$1.applyMatrix4(sprite.matrixWorld);
9827 return this.intersectsSphere(_sphere$1);
9830 _proto.intersectsSphere = function intersectsSphere(sphere) {
9831 var planes = this.planes;
9832 var center = sphere.center;
9833 var negRadius = -sphere.radius;
9835 for (var i = 0; i < 6; i++) {
9836 var distance = planes[i].distanceToPoint(center);
9838 if (distance < negRadius) {
9846 _proto.intersectsBox = function intersectsBox(box) {
9847 var planes = this.planes;
9849 for (var i = 0; i < 6; i++) {
9850 var plane = planes[i]; // corner at max distance
9852 _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
9853 _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
9854 _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
9856 if (plane.distanceToPoint(_vector$5) < 0) {
9864 _proto.containsPoint = function containsPoint(point) {
9865 var planes = this.planes;
9867 for (var i = 0; i < 6; i++) {
9868 if (planes[i].distanceToPoint(point) < 0) {
9879 function WebGLAnimation() {
9881 var isAnimating = false;
9882 var animationLoop = null;
9883 var requestId = null;
9885 function onAnimationFrame(time, frame) {
9886 animationLoop(time, frame);
9887 requestId = context.requestAnimationFrame(onAnimationFrame);
9891 start: function start() {
9892 if (isAnimating === true) return;
9893 if (animationLoop === null) return;
9894 requestId = context.requestAnimationFrame(onAnimationFrame);
9897 stop: function stop() {
9898 context.cancelAnimationFrame(requestId);
9899 isAnimating = false;
9901 setAnimationLoop: function setAnimationLoop(callback) {
9902 animationLoop = callback;
9904 setContext: function setContext(value) {
9910 function WebGLAttributes(gl, capabilities) {
9911 var isWebGL2 = capabilities.isWebGL2;
9912 var buffers = new WeakMap();
9914 function createBuffer(attribute, bufferType) {
9915 var array = attribute.array;
9916 var usage = attribute.usage;
9917 var buffer = gl.createBuffer();
9918 gl.bindBuffer(bufferType, buffer);
9919 gl.bufferData(bufferType, array, usage);
9920 attribute.onUploadCallback();
9923 if (array instanceof Float32Array) {
9925 } else if (array instanceof Float64Array) {
9926 console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
9927 } else if (array instanceof Uint16Array) {
9928 if (attribute.isFloat16BufferAttribute) {
9932 console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
9937 } else if (array instanceof Int16Array) {
9939 } else if (array instanceof Uint32Array) {
9941 } else if (array instanceof Int32Array) {
9943 } else if (array instanceof Int8Array) {
9945 } else if (array instanceof Uint8Array) {
9952 bytesPerElement: array.BYTES_PER_ELEMENT,
9953 version: attribute.version
9957 function updateBuffer(buffer, attribute, bufferType) {
9958 var array = attribute.array;
9959 var updateRange = attribute.updateRange;
9960 gl.bindBuffer(bufferType, buffer);
9962 if (updateRange.count === -1) {
9963 // Not using update ranges
9964 gl.bufferSubData(bufferType, 0, array);
9967 gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
9969 gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
9972 updateRange.count = -1; // reset range
9977 function get(attribute) {
9978 if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
9979 return buffers.get(attribute);
9982 function remove(attribute) {
9983 if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
9984 var data = buffers.get(attribute);
9987 gl.deleteBuffer(data.buffer);
9988 buffers.delete(attribute);
9992 function update(attribute, bufferType) {
9993 if (attribute.isGLBufferAttribute) {
9994 var cached = buffers.get(attribute);
9996 if (!cached || cached.version < attribute.version) {
9997 buffers.set(attribute, {
9998 buffer: attribute.buffer,
9999 type: attribute.type,
10000 bytesPerElement: attribute.elementSize,
10001 version: attribute.version
10008 if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
10009 var data = buffers.get(attribute);
10011 if (data === undefined) {
10012 buffers.set(attribute, createBuffer(attribute, bufferType));
10013 } else if (data.version < attribute.version) {
10014 updateBuffer(data.buffer, attribute, bufferType);
10015 data.version = attribute.version;
10026 var PlaneBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
10027 _inheritsLoose(PlaneBufferGeometry, _BufferGeometry);
10029 function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
10032 if (width === void 0) {
10036 if (height === void 0) {
10040 if (widthSegments === void 0) {
10044 if (heightSegments === void 0) {
10045 heightSegments = 1;
10048 _this = _BufferGeometry.call(this) || this;
10049 _this.type = 'PlaneBufferGeometry';
10050 _this.parameters = {
10053 widthSegments: widthSegments,
10054 heightSegments: heightSegments
10056 var width_half = width / 2;
10057 var height_half = height / 2;
10058 var gridX = Math.floor(widthSegments);
10059 var gridY = Math.floor(heightSegments);
10060 var gridX1 = gridX + 1;
10061 var gridY1 = gridY + 1;
10062 var segment_width = width / gridX;
10063 var segment_height = height / gridY; //
10070 for (var iy = 0; iy < gridY1; iy++) {
10071 var y = iy * segment_height - height_half;
10073 for (var ix = 0; ix < gridX1; ix++) {
10074 var x = ix * segment_width - width_half;
10075 vertices.push(x, -y, 0);
10076 normals.push(0, 0, 1);
10077 uvs.push(ix / gridX);
10078 uvs.push(1 - iy / gridY);
10082 for (var _iy = 0; _iy < gridY; _iy++) {
10083 for (var _ix = 0; _ix < gridX; _ix++) {
10084 var a = _ix + gridX1 * _iy;
10085 var b = _ix + gridX1 * (_iy + 1);
10086 var c = _ix + 1 + gridX1 * (_iy + 1);
10087 var d = _ix + 1 + gridX1 * _iy;
10088 indices.push(a, b, d);
10089 indices.push(b, c, d);
10093 _this.setIndex(indices);
10095 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
10097 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
10099 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
10104 return PlaneBufferGeometry;
10107 var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
10109 var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
10111 var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
10113 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.specularRoughness );\n\t#endif\n#endif";
10115 var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
10117 var begin_vertex = "vec3 transformed = vec3( position );";
10119 var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
10121 var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\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\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.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}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
10123 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 ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
10125 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";
10127 var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
10129 var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
10131 var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
10133 var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
10135 var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
10137 var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
10139 var color_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor.xyz *= color.xyz;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
10141 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 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 max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\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 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}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\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}";
10143 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 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\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\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\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";
10145 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";
10147 var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
10149 var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
10151 var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
10153 var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
10155 var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
10157 var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\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}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
10159 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#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\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";
10161 var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\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";
10163 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";
10165 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";
10167 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";
10169 var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
10171 var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
10173 var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
10175 var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
10177 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 texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
10179 var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
10181 var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
10183 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 );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\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\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\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\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\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\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\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 );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
10185 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 GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
10187 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 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
10189 var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
10191 var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_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_Diffuse_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)";
10193 var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
10195 var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
10197 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.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\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 = sheen;\n#endif";
10199 var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_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_Diffuse_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 CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * 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}";
10201 var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef 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\tgetPointDirectLightIrradiance( 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\tgetSpotDirectLightIrradiance( 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\tgetDirectionalDirectLightIrradiance( 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 );\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 );\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";
10203 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 += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
10205 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";
10207 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";
10209 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";
10211 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";
10213 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";
10215 var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
10217 var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
10219 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";
10221 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";
10223 var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
10225 var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
10227 var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
10229 var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
10231 var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
10233 var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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;";
10235 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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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 );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
10237 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 ) {\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\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
10239 var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
10241 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 );\n\t#endif\n#endif";
10243 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";
10245 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}";
10247 var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
10249 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;";
10251 var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
10253 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";
10255 var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
10257 var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
10259 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";
10261 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";
10263 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";
10265 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}";
10267 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";
10269 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";
10271 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";
10273 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";
10275 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";
10277 var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
10279 var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
10281 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; }";
10283 var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
10285 var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
10287 var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
10289 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";
10291 var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
10293 var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
10295 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";
10297 var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
10299 var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\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";
10301 var 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}";
10303 var 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}";
10305 var 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}";
10307 var 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}";
10309 var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\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}";
10311 var 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}";
10313 var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
10315 var 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}";
10317 var 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}";
10319 var 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}";
10321 var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
10323 var 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}";
10325 var 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 <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\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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
10327 var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
10329 var 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 <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_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
10331 var 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}";
10333 var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
10335 var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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 <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#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\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\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
10337 var 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 <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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
10339 var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
10341 var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_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 <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
10343 var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
10345 var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#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\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <transmissionmap_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 <lights_physical_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#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\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 <transmissionmap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
10347 var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#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\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
10349 var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#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\n#include <packing>\n#include <uv_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}";
10351 var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#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\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 <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#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\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}";
10353 var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
10355 var 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}";
10357 var 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}";
10359 var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <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 <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
10361 var 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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
10363 var 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}";
10365 var ShaderChunk = {
10366 alphamap_fragment: alphamap_fragment,
10367 alphamap_pars_fragment: alphamap_pars_fragment,
10368 alphatest_fragment: alphatest_fragment,
10369 aomap_fragment: aomap_fragment,
10370 aomap_pars_fragment: aomap_pars_fragment,
10371 begin_vertex: begin_vertex,
10372 beginnormal_vertex: beginnormal_vertex,
10374 bumpmap_pars_fragment: bumpmap_pars_fragment,
10375 clipping_planes_fragment: clipping_planes_fragment,
10376 clipping_planes_pars_fragment: clipping_planes_pars_fragment,
10377 clipping_planes_pars_vertex: clipping_planes_pars_vertex,
10378 clipping_planes_vertex: clipping_planes_vertex,
10379 color_fragment: color_fragment,
10380 color_pars_fragment: color_pars_fragment,
10381 color_pars_vertex: color_pars_vertex,
10382 color_vertex: color_vertex,
10384 cube_uv_reflection_fragment: cube_uv_reflection_fragment,
10385 defaultnormal_vertex: defaultnormal_vertex,
10386 displacementmap_pars_vertex: displacementmap_pars_vertex,
10387 displacementmap_vertex: displacementmap_vertex,
10388 emissivemap_fragment: emissivemap_fragment,
10389 emissivemap_pars_fragment: emissivemap_pars_fragment,
10390 encodings_fragment: encodings_fragment,
10391 encodings_pars_fragment: encodings_pars_fragment,
10392 envmap_fragment: envmap_fragment,
10393 envmap_common_pars_fragment: envmap_common_pars_fragment,
10394 envmap_pars_fragment: envmap_pars_fragment,
10395 envmap_pars_vertex: envmap_pars_vertex,
10396 envmap_physical_pars_fragment: envmap_physical_pars_fragment,
10397 envmap_vertex: envmap_vertex,
10398 fog_vertex: fog_vertex,
10399 fog_pars_vertex: fog_pars_vertex,
10400 fog_fragment: fog_fragment,
10401 fog_pars_fragment: fog_pars_fragment,
10402 gradientmap_pars_fragment: gradientmap_pars_fragment,
10403 lightmap_fragment: lightmap_fragment,
10404 lightmap_pars_fragment: lightmap_pars_fragment,
10405 lights_lambert_vertex: lights_lambert_vertex,
10406 lights_pars_begin: lights_pars_begin,
10407 lights_toon_fragment: lights_toon_fragment,
10408 lights_toon_pars_fragment: lights_toon_pars_fragment,
10409 lights_phong_fragment: lights_phong_fragment,
10410 lights_phong_pars_fragment: lights_phong_pars_fragment,
10411 lights_physical_fragment: lights_physical_fragment,
10412 lights_physical_pars_fragment: lights_physical_pars_fragment,
10413 lights_fragment_begin: lights_fragment_begin,
10414 lights_fragment_maps: lights_fragment_maps,
10415 lights_fragment_end: lights_fragment_end,
10416 logdepthbuf_fragment: logdepthbuf_fragment,
10417 logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
10418 logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
10419 logdepthbuf_vertex: logdepthbuf_vertex,
10420 map_fragment: map_fragment,
10421 map_pars_fragment: map_pars_fragment,
10422 map_particle_fragment: map_particle_fragment,
10423 map_particle_pars_fragment: map_particle_pars_fragment,
10424 metalnessmap_fragment: metalnessmap_fragment,
10425 metalnessmap_pars_fragment: metalnessmap_pars_fragment,
10426 morphnormal_vertex: morphnormal_vertex,
10427 morphtarget_pars_vertex: morphtarget_pars_vertex,
10428 morphtarget_vertex: morphtarget_vertex,
10429 normal_fragment_begin: normal_fragment_begin,
10430 normal_fragment_maps: normal_fragment_maps,
10431 normalmap_pars_fragment: normalmap_pars_fragment,
10432 clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
10433 clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
10434 clearcoat_pars_fragment: clearcoat_pars_fragment,
10436 premultiplied_alpha_fragment: premultiplied_alpha_fragment,
10437 project_vertex: project_vertex,
10438 dithering_fragment: dithering_fragment,
10439 dithering_pars_fragment: dithering_pars_fragment,
10440 roughnessmap_fragment: roughnessmap_fragment,
10441 roughnessmap_pars_fragment: roughnessmap_pars_fragment,
10442 shadowmap_pars_fragment: shadowmap_pars_fragment,
10443 shadowmap_pars_vertex: shadowmap_pars_vertex,
10444 shadowmap_vertex: shadowmap_vertex,
10445 shadowmask_pars_fragment: shadowmask_pars_fragment,
10446 skinbase_vertex: skinbase_vertex,
10447 skinning_pars_vertex: skinning_pars_vertex,
10448 skinning_vertex: skinning_vertex,
10449 skinnormal_vertex: skinnormal_vertex,
10450 specularmap_fragment: specularmap_fragment,
10451 specularmap_pars_fragment: specularmap_pars_fragment,
10452 tonemapping_fragment: tonemapping_fragment,
10453 tonemapping_pars_fragment: tonemapping_pars_fragment,
10454 transmissionmap_fragment: transmissionmap_fragment,
10455 transmissionmap_pars_fragment: transmissionmap_pars_fragment,
10456 uv_pars_fragment: uv_pars_fragment,
10457 uv_pars_vertex: uv_pars_vertex,
10458 uv_vertex: uv_vertex,
10459 uv2_pars_fragment: uv2_pars_fragment,
10460 uv2_pars_vertex: uv2_pars_vertex,
10461 uv2_vertex: uv2_vertex,
10462 worldpos_vertex: worldpos_vertex,
10463 background_frag: background_frag,
10464 background_vert: background_vert,
10465 cube_frag: cube_frag,
10466 cube_vert: cube_vert,
10467 depth_frag: depth_frag,
10468 depth_vert: depth_vert,
10469 distanceRGBA_frag: distanceRGBA_frag,
10470 distanceRGBA_vert: distanceRGBA_vert,
10471 equirect_frag: equirect_frag,
10472 equirect_vert: equirect_vert,
10473 linedashed_frag: linedashed_frag,
10474 linedashed_vert: linedashed_vert,
10475 meshbasic_frag: meshbasic_frag,
10476 meshbasic_vert: meshbasic_vert,
10477 meshlambert_frag: meshlambert_frag,
10478 meshlambert_vert: meshlambert_vert,
10479 meshmatcap_frag: meshmatcap_frag,
10480 meshmatcap_vert: meshmatcap_vert,
10481 meshtoon_frag: meshtoon_frag,
10482 meshtoon_vert: meshtoon_vert,
10483 meshphong_frag: meshphong_frag,
10484 meshphong_vert: meshphong_vert,
10485 meshphysical_frag: meshphysical_frag,
10486 meshphysical_vert: meshphysical_vert,
10487 normal_frag: normal_frag,
10488 normal_vert: normal_vert,
10489 points_frag: points_frag,
10490 points_vert: points_vert,
10491 shadow_frag: shadow_frag,
10492 shadow_vert: shadow_vert,
10493 sprite_frag: sprite_frag,
10494 sprite_vert: sprite_vert
10498 * Uniforms library for shared webgl shaders
10501 var UniformsLib = {
10504 value: new Color(0xeeeeee)
10513 value: new Matrix3()
10516 value: new Matrix3()
10556 lightMapIntensity: {
10578 value: new Vector2(1, 1)
10585 displacementScale: {
10588 displacementBias: {
10618 value: new Color(0xffffff)
10622 ambientLightColor: {
10628 directionalLights: {
10635 directionalLightShadows: {
10639 shadowNormalBias: {},
10644 directionalShadowMap: {
10647 directionalShadowMatrix: {
10662 spotLightShadows: {
10666 shadowNormalBias: {},
10674 spotShadowMatrix: {
10686 pointLightShadows: {
10690 shadowNormalBias: {},
10693 shadowCameraNear: {},
10694 shadowCameraFar: {}
10700 pointShadowMatrix: {
10703 hemisphereLights: {
10711 // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
10730 value: new Color(0xeeeeee)
10748 value: new Matrix3()
10753 value: new Color(0xeeeeee)
10759 value: new Vector2(0.5, 0.5)
10771 value: new Matrix3()
10778 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
10779 vertexShader: ShaderChunk.meshbasic_vert,
10780 fragmentShader: ShaderChunk.meshbasic_frag
10783 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
10785 value: new Color(0x000000)
10788 vertexShader: ShaderChunk.meshlambert_vert,
10789 fragmentShader: ShaderChunk.meshlambert_frag
10792 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
10794 value: new Color(0x000000)
10797 value: new Color(0x111111)
10803 vertexShader: ShaderChunk.meshphong_vert,
10804 fragmentShader: ShaderChunk.meshphong_frag
10807 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, {
10809 value: new Color(0x000000)
10822 vertexShader: ShaderChunk.meshphysical_vert,
10823 fragmentShader: ShaderChunk.meshphysical_frag
10826 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
10828 value: new Color(0x000000)
10831 vertexShader: ShaderChunk.meshtoon_vert,
10832 fragmentShader: ShaderChunk.meshtoon_frag
10835 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
10840 vertexShader: ShaderChunk.meshmatcap_vert,
10841 fragmentShader: ShaderChunk.meshmatcap_frag
10844 uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
10845 vertexShader: ShaderChunk.points_vert,
10846 fragmentShader: ShaderChunk.points_frag
10849 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
10860 vertexShader: ShaderChunk.linedashed_vert,
10861 fragmentShader: ShaderChunk.linedashed_frag
10864 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
10865 vertexShader: ShaderChunk.depth_vert,
10866 fragmentShader: ShaderChunk.depth_frag
10869 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
10874 vertexShader: ShaderChunk.normal_vert,
10875 fragmentShader: ShaderChunk.normal_frag
10878 uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
10879 vertexShader: ShaderChunk.sprite_vert,
10880 fragmentShader: ShaderChunk.sprite_frag
10885 value: new Matrix3()
10891 vertexShader: ShaderChunk.background_vert,
10892 fragmentShader: ShaderChunk.background_frag
10895 /* -------------------------------------------------------------------------
10897 ------------------------------------------------------------------------- */
10899 uniforms: mergeUniforms([UniformsLib.envmap, {
10904 vertexShader: ShaderChunk.cube_vert,
10905 fragmentShader: ShaderChunk.cube_frag
10913 vertexShader: ShaderChunk.equirect_vert,
10914 fragmentShader: ShaderChunk.equirect_frag
10917 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
10918 referencePosition: {
10919 value: new Vector3()
10928 vertexShader: ShaderChunk.distanceRGBA_vert,
10929 fragmentShader: ShaderChunk.distanceRGBA_frag
10932 uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
10934 value: new Color(0x00000)
10940 vertexShader: ShaderChunk.shadow_vert,
10941 fragmentShader: ShaderChunk.shadow_frag
10944 ShaderLib.physical = {
10945 uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
10952 clearcoatRoughness: {
10955 clearcoatRoughnessMap: {
10958 clearcoatNormalScale: {
10959 value: new Vector2(1, 1)
10961 clearcoatNormalMap: {
10965 value: new Color(0x000000)
10974 vertexShader: ShaderChunk.meshphysical_vert,
10975 fragmentShader: ShaderChunk.meshphysical_frag
10978 function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
10979 var clearColor = new Color(0x000000);
10980 var clearAlpha = 0;
10983 var currentBackground = null;
10984 var currentBackgroundVersion = 0;
10985 var currentTonemapping = null;
10987 function render(renderList, scene, camera, forceClear) {
10988 var background = scene.isScene === true ? scene.background : null;
10990 if (background && background.isTexture) {
10991 background = cubemaps.get(background);
10992 } // Ignore background in AR
10993 // TODO: Reconsider this.
10996 var xr = renderer.xr;
10997 var session = xr.getSession && xr.getSession();
10999 if (session && session.environmentBlendMode === 'additive') {
11003 if (background === null) {
11004 setClear(clearColor, clearAlpha);
11005 } else if (background && background.isColor) {
11006 setClear(background, 1);
11010 if (renderer.autoClear || forceClear) {
11011 renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
11014 if (background && (background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping)) {
11015 if (boxMesh === undefined) {
11016 boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
11017 name: 'BackgroundCubeMaterial',
11018 uniforms: cloneUniforms(ShaderLib.cube.uniforms),
11019 vertexShader: ShaderLib.cube.vertexShader,
11020 fragmentShader: ShaderLib.cube.fragmentShader,
11026 boxMesh.geometry.deleteAttribute('normal');
11027 boxMesh.geometry.deleteAttribute('uv');
11029 boxMesh.onBeforeRender = function (renderer, scene, camera) {
11030 this.matrixWorld.copyPosition(camera.matrixWorld);
11031 }; // enable code injection for non-built-in material
11034 Object.defineProperty(boxMesh.material, 'envMap', {
11035 get: function get() {
11036 return this.uniforms.envMap.value;
11039 objects.update(boxMesh);
11042 if (background.isWebGLCubeRenderTarget) {
11044 background = background.texture;
11047 boxMesh.material.uniforms.envMap.value = background;
11048 boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
11050 if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
11051 boxMesh.material.needsUpdate = true;
11052 currentBackground = background;
11053 currentBackgroundVersion = background.version;
11054 currentTonemapping = renderer.toneMapping;
11055 } // push to the pre-sorted opaque render list
11058 renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
11059 } else if (background && background.isTexture) {
11060 if (planeMesh === undefined) {
11061 planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
11062 name: 'BackgroundMaterial',
11063 uniforms: cloneUniforms(ShaderLib.background.uniforms),
11064 vertexShader: ShaderLib.background.vertexShader,
11065 fragmentShader: ShaderLib.background.fragmentShader,
11071 planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
11073 Object.defineProperty(planeMesh.material, 'map', {
11074 get: function get() {
11075 return this.uniforms.t2D.value;
11078 objects.update(planeMesh);
11081 planeMesh.material.uniforms.t2D.value = background;
11083 if (background.matrixAutoUpdate === true) {
11084 background.updateMatrix();
11087 planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
11089 if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
11090 planeMesh.material.needsUpdate = true;
11091 currentBackground = background;
11092 currentBackgroundVersion = background.version;
11093 currentTonemapping = renderer.toneMapping;
11094 } // push to the pre-sorted opaque render list
11097 renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
11101 function setClear(color, alpha) {
11102 state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
11106 getClearColor: function getClearColor() {
11109 setClearColor: function setClearColor(color, alpha) {
11110 if (alpha === void 0) {
11114 clearColor.set(color);
11115 clearAlpha = alpha;
11116 setClear(clearColor, clearAlpha);
11118 getClearAlpha: function getClearAlpha() {
11121 setClearAlpha: function setClearAlpha(alpha) {
11122 clearAlpha = alpha;
11123 setClear(clearColor, clearAlpha);
11129 function WebGLBindingStates(gl, extensions, attributes, capabilities) {
11130 var maxVertexAttributes = gl.getParameter(34921);
11131 var extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
11132 var vaoAvailable = capabilities.isWebGL2 || extension !== null;
11133 var bindingStates = {};
11134 var defaultState = createBindingState(null);
11135 var currentState = defaultState;
11137 function setup(object, material, program, geometry, index) {
11138 var updateBuffers = false;
11140 if (vaoAvailable) {
11141 var state = getBindingState(geometry, program, material);
11143 if (currentState !== state) {
11144 currentState = state;
11145 bindVertexArrayObject(currentState.object);
11148 updateBuffers = needsUpdate(geometry, index);
11149 if (updateBuffers) saveCache(geometry, index);
11151 var wireframe = material.wireframe === true;
11153 if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
11154 currentState.geometry = geometry.id;
11155 currentState.program = program.id;
11156 currentState.wireframe = wireframe;
11157 updateBuffers = true;
11161 if (object.isInstancedMesh === true) {
11162 updateBuffers = true;
11165 if (index !== null) {
11166 attributes.update(index, 34963);
11169 if (updateBuffers) {
11170 setupVertexAttributes(object, material, program, geometry);
11172 if (index !== null) {
11173 gl.bindBuffer(34963, attributes.get(index).buffer);
11178 function createVertexArrayObject() {
11179 if (capabilities.isWebGL2) return gl.createVertexArray();
11180 return extension.createVertexArrayOES();
11183 function bindVertexArrayObject(vao) {
11184 if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
11185 return extension.bindVertexArrayOES(vao);
11188 function deleteVertexArrayObject(vao) {
11189 if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
11190 return extension.deleteVertexArrayOES(vao);
11193 function getBindingState(geometry, program, material) {
11194 var wireframe = material.wireframe === true;
11195 var programMap = bindingStates[geometry.id];
11197 if (programMap === undefined) {
11199 bindingStates[geometry.id] = programMap;
11202 var stateMap = programMap[program.id];
11204 if (stateMap === undefined) {
11206 programMap[program.id] = stateMap;
11209 var state = stateMap[wireframe];
11211 if (state === undefined) {
11212 state = createBindingState(createVertexArrayObject());
11213 stateMap[wireframe] = state;
11219 function createBindingState(vao) {
11220 var newAttributes = [];
11221 var enabledAttributes = [];
11222 var attributeDivisors = [];
11224 for (var i = 0; i < maxVertexAttributes; i++) {
11225 newAttributes[i] = 0;
11226 enabledAttributes[i] = 0;
11227 attributeDivisors[i] = 0;
11231 // for backward compatibility on non-VAO support browser
11235 newAttributes: newAttributes,
11236 enabledAttributes: enabledAttributes,
11237 attributeDivisors: attributeDivisors,
11244 function needsUpdate(geometry, index) {
11245 var cachedAttributes = currentState.attributes;
11246 var geometryAttributes = geometry.attributes;
11247 var attributesNum = 0;
11249 for (var key in geometryAttributes) {
11250 var cachedAttribute = cachedAttributes[key];
11251 var geometryAttribute = geometryAttributes[key];
11252 if (cachedAttribute === undefined) return true;
11253 if (cachedAttribute.attribute !== geometryAttribute) return true;
11254 if (cachedAttribute.data !== geometryAttribute.data) return true;
11258 if (currentState.attributesNum !== attributesNum) return true;
11259 if (currentState.index !== index) return true;
11263 function saveCache(geometry, index) {
11265 var attributes = geometry.attributes;
11266 var attributesNum = 0;
11268 for (var key in attributes) {
11269 var attribute = attributes[key];
11271 data.attribute = attribute;
11273 if (attribute.data) {
11274 data.data = attribute.data;
11281 currentState.attributes = cache;
11282 currentState.attributesNum = attributesNum;
11283 currentState.index = index;
11286 function initAttributes() {
11287 var newAttributes = currentState.newAttributes;
11289 for (var i = 0, il = newAttributes.length; i < il; i++) {
11290 newAttributes[i] = 0;
11294 function enableAttribute(attribute) {
11295 enableAttributeAndDivisor(attribute, 0);
11298 function enableAttributeAndDivisor(attribute, meshPerAttribute) {
11299 var newAttributes = currentState.newAttributes;
11300 var enabledAttributes = currentState.enabledAttributes;
11301 var attributeDivisors = currentState.attributeDivisors;
11302 newAttributes[attribute] = 1;
11304 if (enabledAttributes[attribute] === 0) {
11305 gl.enableVertexAttribArray(attribute);
11306 enabledAttributes[attribute] = 1;
11309 if (attributeDivisors[attribute] !== meshPerAttribute) {
11310 var _extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
11312 _extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
11314 attributeDivisors[attribute] = meshPerAttribute;
11318 function disableUnusedAttributes() {
11319 var newAttributes = currentState.newAttributes;
11320 var enabledAttributes = currentState.enabledAttributes;
11322 for (var i = 0, il = enabledAttributes.length; i < il; i++) {
11323 if (enabledAttributes[i] !== newAttributes[i]) {
11324 gl.disableVertexAttribArray(i);
11325 enabledAttributes[i] = 0;
11330 function vertexAttribPointer(index, size, type, normalized, stride, offset) {
11331 if (capabilities.isWebGL2 === true && (type === 5124 || type === 5125)) {
11332 gl.vertexAttribIPointer(index, size, type, stride, offset);
11334 gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
11338 function setupVertexAttributes(object, material, program, geometry) {
11339 if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
11340 if (extensions.get('ANGLE_instanced_arrays') === null) return;
11344 var geometryAttributes = geometry.attributes;
11345 var programAttributes = program.getAttributes();
11346 var materialDefaultAttributeValues = material.defaultAttributeValues;
11348 for (var name in programAttributes) {
11349 var programAttribute = programAttributes[name];
11351 if (programAttribute >= 0) {
11352 var geometryAttribute = geometryAttributes[name];
11354 if (geometryAttribute !== undefined) {
11355 var normalized = geometryAttribute.normalized;
11356 var size = geometryAttribute.itemSize;
11357 var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
11359 if (attribute === undefined) continue;
11360 var buffer = attribute.buffer;
11361 var type = attribute.type;
11362 var bytesPerElement = attribute.bytesPerElement;
11364 if (geometryAttribute.isInterleavedBufferAttribute) {
11365 var data = geometryAttribute.data;
11366 var stride = data.stride;
11367 var offset = geometryAttribute.offset;
11369 if (data && data.isInstancedInterleavedBuffer) {
11370 enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
11372 if (geometry._maxInstanceCount === undefined) {
11373 geometry._maxInstanceCount = data.meshPerAttribute * data.count;
11376 enableAttribute(programAttribute);
11379 gl.bindBuffer(34962, buffer);
11380 vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
11382 if (geometryAttribute.isInstancedBufferAttribute) {
11383 enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
11385 if (geometry._maxInstanceCount === undefined) {
11386 geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
11389 enableAttribute(programAttribute);
11392 gl.bindBuffer(34962, buffer);
11393 vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
11395 } else if (name === 'instanceMatrix') {
11396 var _attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
11399 if (_attribute === undefined) continue;
11400 var _buffer = _attribute.buffer;
11401 var _type = _attribute.type;
11402 enableAttributeAndDivisor(programAttribute + 0, 1);
11403 enableAttributeAndDivisor(programAttribute + 1, 1);
11404 enableAttributeAndDivisor(programAttribute + 2, 1);
11405 enableAttributeAndDivisor(programAttribute + 3, 1);
11406 gl.bindBuffer(34962, _buffer);
11407 gl.vertexAttribPointer(programAttribute + 0, 4, _type, false, 64, 0);
11408 gl.vertexAttribPointer(programAttribute + 1, 4, _type, false, 64, 16);
11409 gl.vertexAttribPointer(programAttribute + 2, 4, _type, false, 64, 32);
11410 gl.vertexAttribPointer(programAttribute + 3, 4, _type, false, 64, 48);
11411 } else if (name === 'instanceColor') {
11412 var _attribute2 = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
11415 if (_attribute2 === undefined) continue;
11416 var _buffer2 = _attribute2.buffer;
11417 var _type2 = _attribute2.type;
11418 enableAttributeAndDivisor(programAttribute, 1);
11419 gl.bindBuffer(34962, _buffer2);
11420 gl.vertexAttribPointer(programAttribute, 3, _type2, false, 12, 0);
11421 } else if (materialDefaultAttributeValues !== undefined) {
11422 var value = materialDefaultAttributeValues[name];
11424 if (value !== undefined) {
11425 switch (value.length) {
11427 gl.vertexAttrib2fv(programAttribute, value);
11431 gl.vertexAttrib3fv(programAttribute, value);
11435 gl.vertexAttrib4fv(programAttribute, value);
11439 gl.vertexAttrib1fv(programAttribute, value);
11446 disableUnusedAttributes();
11449 function dispose() {
11452 for (var geometryId in bindingStates) {
11453 var programMap = bindingStates[geometryId];
11455 for (var programId in programMap) {
11456 var stateMap = programMap[programId];
11458 for (var wireframe in stateMap) {
11459 deleteVertexArrayObject(stateMap[wireframe].object);
11460 delete stateMap[wireframe];
11463 delete programMap[programId];
11466 delete bindingStates[geometryId];
11470 function releaseStatesOfGeometry(geometry) {
11471 if (bindingStates[geometry.id] === undefined) return;
11472 var programMap = bindingStates[geometry.id];
11474 for (var programId in programMap) {
11475 var stateMap = programMap[programId];
11477 for (var wireframe in stateMap) {
11478 deleteVertexArrayObject(stateMap[wireframe].object);
11479 delete stateMap[wireframe];
11482 delete programMap[programId];
11485 delete bindingStates[geometry.id];
11488 function releaseStatesOfProgram(program) {
11489 for (var geometryId in bindingStates) {
11490 var programMap = bindingStates[geometryId];
11491 if (programMap[program.id] === undefined) continue;
11492 var stateMap = programMap[program.id];
11494 for (var wireframe in stateMap) {
11495 deleteVertexArrayObject(stateMap[wireframe].object);
11496 delete stateMap[wireframe];
11499 delete programMap[program.id];
11504 resetDefaultState();
11505 if (currentState === defaultState) return;
11506 currentState = defaultState;
11507 bindVertexArrayObject(currentState.object);
11508 } // for backward-compatilibity
11511 function resetDefaultState() {
11512 defaultState.geometry = null;
11513 defaultState.program = null;
11514 defaultState.wireframe = false;
11520 resetDefaultState: resetDefaultState,
11522 releaseStatesOfGeometry: releaseStatesOfGeometry,
11523 releaseStatesOfProgram: releaseStatesOfProgram,
11524 initAttributes: initAttributes,
11525 enableAttribute: enableAttribute,
11526 disableUnusedAttributes: disableUnusedAttributes
11530 function WebGLBufferRenderer(gl, extensions, info, capabilities) {
11531 var isWebGL2 = capabilities.isWebGL2;
11534 function setMode(value) {
11538 function render(start, count) {
11539 gl.drawArrays(mode, start, count);
11540 info.update(count, mode, 1);
11543 function renderInstances(start, count, primcount) {
11544 if (primcount === 0) return;
11545 var extension, methodName;
11549 methodName = 'drawArraysInstanced';
11551 extension = extensions.get('ANGLE_instanced_arrays');
11552 methodName = 'drawArraysInstancedANGLE';
11554 if (extension === null) {
11555 console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
11560 extension[methodName](mode, start, count, primcount);
11561 info.update(count, mode, primcount);
11565 this.setMode = setMode;
11566 this.render = render;
11567 this.renderInstances = renderInstances;
11570 function WebGLCapabilities(gl, extensions, parameters) {
11573 function getMaxAnisotropy() {
11574 if (maxAnisotropy !== undefined) return maxAnisotropy;
11575 var extension = extensions.get('EXT_texture_filter_anisotropic');
11577 if (extension !== null) {
11578 maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
11583 return maxAnisotropy;
11586 function getMaxPrecision(precision) {
11587 if (precision === 'highp') {
11588 if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
11592 precision = 'mediump';
11595 if (precision === 'mediump') {
11596 if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
11603 /* eslint-disable no-undef */
11606 var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
11607 /* eslint-enable no-undef */
11609 var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
11610 var maxPrecision = getMaxPrecision(precision);
11612 if (maxPrecision !== precision) {
11613 console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
11614 precision = maxPrecision;
11617 var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
11618 var maxTextures = gl.getParameter(34930);
11619 var maxVertexTextures = gl.getParameter(35660);
11620 var maxTextureSize = gl.getParameter(3379);
11621 var maxCubemapSize = gl.getParameter(34076);
11622 var maxAttributes = gl.getParameter(34921);
11623 var maxVertexUniforms = gl.getParameter(36347);
11624 var maxVaryings = gl.getParameter(36348);
11625 var maxFragmentUniforms = gl.getParameter(36349);
11626 var vertexTextures = maxVertexTextures > 0;
11627 var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
11628 var floatVertexTextures = vertexTextures && floatFragmentTextures;
11629 var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
11631 isWebGL2: isWebGL2,
11632 getMaxAnisotropy: getMaxAnisotropy,
11633 getMaxPrecision: getMaxPrecision,
11634 precision: precision,
11635 logarithmicDepthBuffer: logarithmicDepthBuffer,
11636 maxTextures: maxTextures,
11637 maxVertexTextures: maxVertexTextures,
11638 maxTextureSize: maxTextureSize,
11639 maxCubemapSize: maxCubemapSize,
11640 maxAttributes: maxAttributes,
11641 maxVertexUniforms: maxVertexUniforms,
11642 maxVaryings: maxVaryings,
11643 maxFragmentUniforms: maxFragmentUniforms,
11644 vertexTextures: vertexTextures,
11645 floatFragmentTextures: floatFragmentTextures,
11646 floatVertexTextures: floatVertexTextures,
11647 maxSamples: maxSamples
11651 function WebGLClipping(properties) {
11653 var globalState = null,
11654 numGlobalPlanes = 0,
11655 localClippingEnabled = false,
11656 renderingShadows = false;
11657 var plane = new Plane(),
11658 viewNormalMatrix = new Matrix3(),
11663 this.uniform = uniform;
11664 this.numPlanes = 0;
11665 this.numIntersection = 0;
11667 this.init = function (planes, enableLocalClipping, camera) {
11668 var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
11669 // run another frame in order to reset the state:
11670 numGlobalPlanes !== 0 || localClippingEnabled;
11671 localClippingEnabled = enableLocalClipping;
11672 globalState = projectPlanes(planes, camera, 0);
11673 numGlobalPlanes = planes.length;
11677 this.beginShadows = function () {
11678 renderingShadows = true;
11679 projectPlanes(null);
11682 this.endShadows = function () {
11683 renderingShadows = false;
11684 resetGlobalState();
11687 this.setState = function (material, camera, useCache) {
11688 var planes = material.clippingPlanes,
11689 clipIntersection = material.clipIntersection,
11690 clipShadows = material.clipShadows;
11691 var materialProperties = properties.get(material);
11693 if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
11694 // there's no local clipping
11695 if (renderingShadows) {
11696 // there's no global clipping
11697 projectPlanes(null);
11699 resetGlobalState();
11702 var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
11703 lGlobal = nGlobal * 4;
11704 var dstArray = materialProperties.clippingState || null;
11705 uniform.value = dstArray; // ensure unique state
11707 dstArray = projectPlanes(planes, camera, lGlobal, useCache);
11709 for (var i = 0; i !== lGlobal; ++i) {
11710 dstArray[i] = globalState[i];
11713 materialProperties.clippingState = dstArray;
11714 this.numIntersection = clipIntersection ? this.numPlanes : 0;
11715 this.numPlanes += nGlobal;
11719 function resetGlobalState() {
11720 if (uniform.value !== globalState) {
11721 uniform.value = globalState;
11722 uniform.needsUpdate = numGlobalPlanes > 0;
11725 scope.numPlanes = numGlobalPlanes;
11726 scope.numIntersection = 0;
11729 function projectPlanes(planes, camera, dstOffset, skipTransform) {
11730 var nPlanes = planes !== null ? planes.length : 0;
11731 var dstArray = null;
11733 if (nPlanes !== 0) {
11734 dstArray = uniform.value;
11736 if (skipTransform !== true || dstArray === null) {
11737 var flatSize = dstOffset + nPlanes * 4,
11738 viewMatrix = camera.matrixWorldInverse;
11739 viewNormalMatrix.getNormalMatrix(viewMatrix);
11741 if (dstArray === null || dstArray.length < flatSize) {
11742 dstArray = new Float32Array(flatSize);
11745 for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
11746 plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
11747 plane.normal.toArray(dstArray, i4);
11748 dstArray[i4 + 3] = plane.constant;
11752 uniform.value = dstArray;
11753 uniform.needsUpdate = true;
11756 scope.numPlanes = nPlanes;
11757 scope.numIntersection = 0;
11762 function WebGLCubeMaps(renderer) {
11763 var cubemaps = new WeakMap();
11765 function mapTextureMapping(texture, mapping) {
11766 if (mapping === EquirectangularReflectionMapping) {
11767 texture.mapping = CubeReflectionMapping;
11768 } else if (mapping === EquirectangularRefractionMapping) {
11769 texture.mapping = CubeRefractionMapping;
11775 function get(texture) {
11776 if (texture && texture.isTexture) {
11777 var mapping = texture.mapping;
11779 if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
11780 if (cubemaps.has(texture)) {
11781 var cubemap = cubemaps.get(texture).texture;
11782 return mapTextureMapping(cubemap, texture.mapping);
11784 var image = texture.image;
11786 if (image && image.height > 0) {
11787 var currentRenderList = renderer.getRenderList();
11788 var currentRenderTarget = renderer.getRenderTarget();
11789 var currentRenderState = renderer.getRenderState();
11790 var renderTarget = new WebGLCubeRenderTarget(image.height / 2);
11791 renderTarget.fromEquirectangularTexture(renderer, texture);
11792 cubemaps.set(texture, renderTarget);
11793 renderer.setRenderTarget(currentRenderTarget);
11794 renderer.setRenderList(currentRenderList);
11795 renderer.setRenderState(currentRenderState);
11796 texture.addEventListener('dispose', onTextureDispose);
11797 return mapTextureMapping(renderTarget.texture, texture.mapping);
11799 // image not yet ready. try the conversion next frame
11809 function onTextureDispose(event) {
11810 var texture = event.target;
11811 texture.removeEventListener('dispose', onTextureDispose);
11812 var cubemap = cubemaps.get(texture);
11814 if (cubemap !== undefined) {
11815 cubemaps.delete(texture);
11820 function dispose() {
11821 cubemaps = new WeakMap();
11830 function WebGLExtensions(gl) {
11831 var extensions = {};
11833 has: function has(name) {
11834 if (extensions[name] !== undefined) {
11835 return extensions[name] !== null;
11841 case 'WEBGL_depth_texture':
11842 extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
11845 case 'EXT_texture_filter_anisotropic':
11846 extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
11849 case 'WEBGL_compressed_texture_s3tc':
11850 extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
11853 case 'WEBGL_compressed_texture_pvrtc':
11854 extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
11858 extension = gl.getExtension(name);
11861 extensions[name] = extension;
11862 return extension !== null;
11864 get: function get(name) {
11865 if (!this.has(name)) {
11866 console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
11869 return extensions[name];
11874 function WebGLGeometries(gl, attributes, info, bindingStates) {
11875 var geometries = new WeakMap();
11876 var wireframeAttributes = new WeakMap();
11878 function onGeometryDispose(event) {
11879 var geometry = event.target;
11880 var buffergeometry = geometries.get(geometry);
11882 if (buffergeometry.index !== null) {
11883 attributes.remove(buffergeometry.index);
11886 for (var name in buffergeometry.attributes) {
11887 attributes.remove(buffergeometry.attributes[name]);
11890 geometry.removeEventListener('dispose', onGeometryDispose);
11891 geometries.delete(geometry);
11892 var attribute = wireframeAttributes.get(buffergeometry);
11895 attributes.remove(attribute);
11896 wireframeAttributes.delete(buffergeometry);
11899 bindingStates.releaseStatesOfGeometry(buffergeometry);
11901 if (geometry.isInstancedBufferGeometry === true) {
11902 delete geometry._maxInstanceCount;
11906 info.memory.geometries--;
11909 function get(object, geometry) {
11910 var buffergeometry = geometries.get(geometry);
11911 if (buffergeometry) return buffergeometry;
11912 geometry.addEventListener('dispose', onGeometryDispose);
11914 if (geometry.isBufferGeometry) {
11915 buffergeometry = geometry;
11916 } else if (geometry.isGeometry) {
11917 if (geometry._bufferGeometry === undefined) {
11918 geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
11921 buffergeometry = geometry._bufferGeometry;
11924 geometries.set(geometry, buffergeometry);
11925 info.memory.geometries++;
11926 return buffergeometry;
11929 function update(geometry) {
11930 var geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
11932 for (var name in geometryAttributes) {
11933 attributes.update(geometryAttributes[name], 34962);
11937 var morphAttributes = geometry.morphAttributes;
11939 for (var _name in morphAttributes) {
11940 var array = morphAttributes[_name];
11942 for (var i = 0, l = array.length; i < l; i++) {
11943 attributes.update(array[i], 34962);
11948 function updateWireframeAttribute(geometry) {
11950 var geometryIndex = geometry.index;
11951 var geometryPosition = geometry.attributes.position;
11954 if (geometryIndex !== null) {
11955 var array = geometryIndex.array;
11956 version = geometryIndex.version;
11958 for (var i = 0, l = array.length; i < l; i += 3) {
11959 var a = array[i + 0];
11960 var b = array[i + 1];
11961 var c = array[i + 2];
11962 indices.push(a, b, b, c, c, a);
11965 var _array = geometryPosition.array;
11966 version = geometryPosition.version;
11968 for (var _i = 0, _l = _array.length / 3 - 1; _i < _l; _i += 3) {
11975 indices.push(_a, _b, _b, _c, _c, _a);
11979 var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
11980 attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
11983 var previousAttribute = wireframeAttributes.get(geometry);
11984 if (previousAttribute) attributes.remove(previousAttribute); //
11986 wireframeAttributes.set(geometry, attribute);
11989 function getWireframeAttribute(geometry) {
11990 var currentAttribute = wireframeAttributes.get(geometry);
11992 if (currentAttribute) {
11993 var geometryIndex = geometry.index;
11995 if (geometryIndex !== null) {
11996 // if the attribute is obsolete, create a new one
11997 if (currentAttribute.version < geometryIndex.version) {
11998 updateWireframeAttribute(geometry);
12002 updateWireframeAttribute(geometry);
12005 return wireframeAttributes.get(geometry);
12011 getWireframeAttribute: getWireframeAttribute
12015 function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
12016 var isWebGL2 = capabilities.isWebGL2;
12019 function setMode(value) {
12023 var type, bytesPerElement;
12025 function setIndex(value) {
12027 bytesPerElement = value.bytesPerElement;
12030 function render(start, count) {
12031 gl.drawElements(mode, count, type, start * bytesPerElement);
12032 info.update(count, mode, 1);
12035 function renderInstances(start, count, primcount) {
12036 if (primcount === 0) return;
12037 var extension, methodName;
12041 methodName = 'drawElementsInstanced';
12043 extension = extensions.get('ANGLE_instanced_arrays');
12044 methodName = 'drawElementsInstancedANGLE';
12046 if (extension === null) {
12047 console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
12052 extension[methodName](mode, count, type, start * bytesPerElement, primcount);
12053 info.update(count, mode, primcount);
12057 this.setMode = setMode;
12058 this.setIndex = setIndex;
12059 this.render = render;
12060 this.renderInstances = renderInstances;
12063 function WebGLInfo(gl) {
12076 function update(count, mode, instanceCount) {
12081 render.triangles += instanceCount * (count / 3);
12085 render.lines += instanceCount * (count / 2);
12089 render.lines += instanceCount * (count - 1);
12093 render.lines += instanceCount * count;
12097 render.points += instanceCount * count;
12101 console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
12109 render.triangles = 0;
12124 function numericalSort(a, b) {
12125 return a[0] - b[0];
12128 function absNumericalSort(a, b) {
12129 return Math.abs(b[1]) - Math.abs(a[1]);
12132 function WebGLMorphtargets(gl) {
12133 var influencesList = {};
12134 var morphInfluences = new Float32Array(8);
12135 var workInfluences = [];
12137 for (var i = 0; i < 8; i++) {
12138 workInfluences[i] = [i, 0];
12141 function update(object, geometry, material, program) {
12142 var objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
12143 // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
12145 var length = objectInfluences === undefined ? 0 : objectInfluences.length;
12146 var influences = influencesList[geometry.id];
12148 if (influences === undefined) {
12152 for (var _i = 0; _i < length; _i++) {
12153 influences[_i] = [_i, 0];
12156 influencesList[geometry.id] = influences;
12157 } // Collect influences
12160 for (var _i2 = 0; _i2 < length; _i2++) {
12161 var influence = influences[_i2];
12162 influence[0] = _i2;
12163 influence[1] = objectInfluences[_i2];
12166 influences.sort(absNumericalSort);
12168 for (var _i3 = 0; _i3 < 8; _i3++) {
12169 if (_i3 < length && influences[_i3][1]) {
12170 workInfluences[_i3][0] = influences[_i3][0];
12171 workInfluences[_i3][1] = influences[_i3][1];
12173 workInfluences[_i3][0] = Number.MAX_SAFE_INTEGER;
12174 workInfluences[_i3][1] = 0;
12178 workInfluences.sort(numericalSort);
12179 var morphTargets = material.morphTargets && geometry.morphAttributes.position;
12180 var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
12181 var morphInfluencesSum = 0;
12183 for (var _i4 = 0; _i4 < 8; _i4++) {
12184 var _influence = workInfluences[_i4];
12185 var index = _influence[0];
12186 var value = _influence[1];
12188 if (index !== Number.MAX_SAFE_INTEGER && value) {
12189 if (morphTargets && geometry.getAttribute('morphTarget' + _i4) !== morphTargets[index]) {
12190 geometry.setAttribute('morphTarget' + _i4, morphTargets[index]);
12193 if (morphNormals && geometry.getAttribute('morphNormal' + _i4) !== morphNormals[index]) {
12194 geometry.setAttribute('morphNormal' + _i4, morphNormals[index]);
12197 morphInfluences[_i4] = value;
12198 morphInfluencesSum += value;
12200 if (morphTargets && geometry.hasAttribute('morphTarget' + _i4) === true) {
12201 geometry.deleteAttribute('morphTarget' + _i4);
12204 if (morphNormals && geometry.hasAttribute('morphNormal' + _i4) === true) {
12205 geometry.deleteAttribute('morphNormal' + _i4);
12208 morphInfluences[_i4] = 0;
12210 } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
12211 // This allows us to switch between absolute morphs and relative morphs without changing shader code
12212 // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
12215 var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
12216 program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
12217 program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
12225 function WebGLObjects(gl, geometries, attributes, info) {
12226 var updateMap = new WeakMap();
12228 function update(object) {
12229 var frame = info.render.frame;
12230 var geometry = object.geometry;
12231 var buffergeometry = geometries.get(object, geometry); // Update once per frame
12233 if (updateMap.get(buffergeometry) !== frame) {
12234 if (geometry.isGeometry) {
12235 buffergeometry.updateFromObject(object);
12238 geometries.update(buffergeometry);
12239 updateMap.set(buffergeometry, frame);
12242 if (object.isInstancedMesh) {
12243 attributes.update(object.instanceMatrix, 34962);
12245 if (object.instanceColor !== null) {
12246 attributes.update(object.instanceColor, 34962);
12250 return buffergeometry;
12253 function dispose() {
12254 updateMap = new WeakMap();
12263 function DataTexture2DArray(data, width, height, depth) {
12264 if (data === void 0) {
12268 if (width === void 0) {
12272 if (height === void 0) {
12276 if (depth === void 0) {
12280 Texture.call(this, null);
12287 this.magFilter = NearestFilter;
12288 this.minFilter = NearestFilter;
12289 this.wrapR = ClampToEdgeWrapping;
12290 this.generateMipmaps = false;
12291 this.flipY = false;
12292 this.needsUpdate = true;
12295 DataTexture2DArray.prototype = Object.create(Texture.prototype);
12296 DataTexture2DArray.prototype.constructor = DataTexture2DArray;
12297 DataTexture2DArray.prototype.isDataTexture2DArray = true;
12299 function DataTexture3D(data, width, height, depth) {
12300 if (data === void 0) {
12304 if (width === void 0) {
12308 if (height === void 0) {
12312 if (depth === void 0) {
12316 // We're going to add .setXXX() methods for setting properties later.
12317 // Users can still set in DataTexture3D directly.
12319 // const texture = new THREE.DataTexture3D( data, width, height, depth );
12320 // texture.anisotropy = 16;
12323 Texture.call(this, null);
12330 this.magFilter = NearestFilter;
12331 this.minFilter = NearestFilter;
12332 this.wrapR = ClampToEdgeWrapping;
12333 this.generateMipmaps = false;
12334 this.flipY = false;
12335 this.needsUpdate = true;
12338 DataTexture3D.prototype = Object.create(Texture.prototype);
12339 DataTexture3D.prototype.constructor = DataTexture3D;
12340 DataTexture3D.prototype.isDataTexture3D = true;
12343 * Uniforms of a program.
12344 * Those form a tree structure with a special top-level container for the root,
12345 * which you get by calling 'new WebGLUniforms( gl, program )'.
12348 * Properties of inner nodes including the top-level container:
12350 * .seq - array of nested uniforms
12351 * .map - nested uniforms by name
12354 * Methods of all nodes except the top-level container:
12356 * .setValue( gl, value, [textures] )
12358 * uploads a uniform value(s)
12359 * the 'textures' parameter is needed for sampler uniforms
12362 * Static methods of the top-level container (textures factorizations):
12364 * .upload( gl, seq, values, textures )
12366 * sets uniforms in 'seq' to 'values[id].value'
12368 * .seqWithValue( seq, values ) : filteredSeq
12370 * filters 'seq' entries with corresponding entry in values
12373 * Methods of the top-level container (textures factorizations):
12375 * .setValue( gl, name, value, textures )
12377 * sets uniform with name 'name' to 'value'
12379 * .setOptional( gl, obj, prop )
12381 * like .set for an optional property of the object
12384 var emptyTexture = new Texture();
12385 var emptyTexture2dArray = new DataTexture2DArray();
12386 var emptyTexture3d = new DataTexture3D();
12387 var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
12388 // Array Caches (provide typed arrays for temporary by size)
12390 var arrayCacheF32 = [];
12391 var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
12393 var mat4array = new Float32Array(16);
12394 var mat3array = new Float32Array(9);
12395 var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
12397 function flatten(array, nBlocks, blockSize) {
12398 var firstElem = array[0];
12399 if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
12400 // see http://jacksondunstan.com/articles/983
12402 var n = nBlocks * blockSize;
12403 var r = arrayCacheF32[n];
12405 if (r === undefined) {
12406 r = new Float32Array(n);
12407 arrayCacheF32[n] = r;
12410 if (nBlocks !== 0) {
12411 firstElem.toArray(r, 0);
12413 for (var i = 1, offset = 0; i !== nBlocks; ++i) {
12414 offset += blockSize;
12415 array[i].toArray(r, offset);
12422 function arraysEqual(a, b) {
12423 if (a.length !== b.length) return false;
12425 for (var i = 0, l = a.length; i < l; i++) {
12426 if (a[i] !== b[i]) return false;
12432 function copyArray(a, b) {
12433 for (var i = 0, l = b.length; i < l; i++) {
12436 } // Texture unit allocation
12439 function allocTexUnits(textures, n) {
12440 var r = arrayCacheI32[n];
12442 if (r === undefined) {
12443 r = new Int32Array(n);
12444 arrayCacheI32[n] = r;
12447 for (var i = 0; i !== n; ++i) {
12448 r[i] = textures.allocateTextureUnit();
12452 } // --- Setters ---
12453 // Note: Defining these methods externally, because they come in a bunch
12454 // and this way their names minify.
12458 function setValueV1f(gl, v) {
12459 var cache = this.cache;
12460 if (cache[0] === v) return;
12461 gl.uniform1f(this.addr, v);
12463 } // Single float vector (from flat array or THREE.VectorN)
12466 function setValueV2f(gl, v) {
12467 var cache = this.cache;
12469 if (v.x !== undefined) {
12470 if (cache[0] !== v.x || cache[1] !== v.y) {
12471 gl.uniform2f(this.addr, v.x, v.y);
12476 if (arraysEqual(cache, v)) return;
12477 gl.uniform2fv(this.addr, v);
12478 copyArray(cache, v);
12482 function setValueV3f(gl, v) {
12483 var cache = this.cache;
12485 if (v.x !== undefined) {
12486 if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
12487 gl.uniform3f(this.addr, v.x, v.y, v.z);
12492 } else if (v.r !== undefined) {
12493 if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
12494 gl.uniform3f(this.addr, v.r, v.g, v.b);
12500 if (arraysEqual(cache, v)) return;
12501 gl.uniform3fv(this.addr, v);
12502 copyArray(cache, v);
12506 function setValueV4f(gl, v) {
12507 var cache = this.cache;
12509 if (v.x !== undefined) {
12510 if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
12511 gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
12518 if (arraysEqual(cache, v)) return;
12519 gl.uniform4fv(this.addr, v);
12520 copyArray(cache, v);
12522 } // Single matrix (from flat array or MatrixN)
12525 function setValueM2(gl, v) {
12526 var cache = this.cache;
12527 var elements = v.elements;
12529 if (elements === undefined) {
12530 if (arraysEqual(cache, v)) return;
12531 gl.uniformMatrix2fv(this.addr, false, v);
12532 copyArray(cache, v);
12534 if (arraysEqual(cache, elements)) return;
12535 mat2array.set(elements);
12536 gl.uniformMatrix2fv(this.addr, false, mat2array);
12537 copyArray(cache, elements);
12541 function setValueM3(gl, v) {
12542 var cache = this.cache;
12543 var elements = v.elements;
12545 if (elements === undefined) {
12546 if (arraysEqual(cache, v)) return;
12547 gl.uniformMatrix3fv(this.addr, false, v);
12548 copyArray(cache, v);
12550 if (arraysEqual(cache, elements)) return;
12551 mat3array.set(elements);
12552 gl.uniformMatrix3fv(this.addr, false, mat3array);
12553 copyArray(cache, elements);
12557 function setValueM4(gl, v) {
12558 var cache = this.cache;
12559 var elements = v.elements;
12561 if (elements === undefined) {
12562 if (arraysEqual(cache, v)) return;
12563 gl.uniformMatrix4fv(this.addr, false, v);
12564 copyArray(cache, v);
12566 if (arraysEqual(cache, elements)) return;
12567 mat4array.set(elements);
12568 gl.uniformMatrix4fv(this.addr, false, mat4array);
12569 copyArray(cache, elements);
12571 } // Single texture (2D / Cube)
12574 function setValueT1(gl, v, textures) {
12575 var cache = this.cache;
12576 var unit = textures.allocateTextureUnit();
12578 if (cache[0] !== unit) {
12579 gl.uniform1i(this.addr, unit);
12583 textures.safeSetTexture2D(v || emptyTexture, unit);
12586 function setValueT2DArray1(gl, v, textures) {
12587 var cache = this.cache;
12588 var unit = textures.allocateTextureUnit();
12590 if (cache[0] !== unit) {
12591 gl.uniform1i(this.addr, unit);
12595 textures.setTexture2DArray(v || emptyTexture2dArray, unit);
12598 function setValueT3D1(gl, v, textures) {
12599 var cache = this.cache;
12600 var unit = textures.allocateTextureUnit();
12602 if (cache[0] !== unit) {
12603 gl.uniform1i(this.addr, unit);
12607 textures.setTexture3D(v || emptyTexture3d, unit);
12610 function setValueT6(gl, v, textures) {
12611 var cache = this.cache;
12612 var unit = textures.allocateTextureUnit();
12614 if (cache[0] !== unit) {
12615 gl.uniform1i(this.addr, unit);
12619 textures.safeSetTextureCube(v || emptyCubeTexture, unit);
12620 } // Integer / Boolean vectors or arrays thereof (always flat arrays)
12623 function setValueV1i(gl, v) {
12624 var cache = this.cache;
12625 if (cache[0] === v) return;
12626 gl.uniform1i(this.addr, v);
12630 function setValueV2i(gl, v) {
12631 var cache = this.cache;
12632 if (arraysEqual(cache, v)) return;
12633 gl.uniform2iv(this.addr, v);
12634 copyArray(cache, v);
12637 function setValueV3i(gl, v) {
12638 var cache = this.cache;
12639 if (arraysEqual(cache, v)) return;
12640 gl.uniform3iv(this.addr, v);
12641 copyArray(cache, v);
12644 function setValueV4i(gl, v) {
12645 var cache = this.cache;
12646 if (arraysEqual(cache, v)) return;
12647 gl.uniform4iv(this.addr, v);
12648 copyArray(cache, v);
12652 function setValueV1ui(gl, v) {
12653 var cache = this.cache;
12654 if (cache[0] === v) return;
12655 gl.uniform1ui(this.addr, v);
12657 } // Helper to pick the right setter for the singular case
12660 function getSingularSetter(type) {
12663 return setValueV1f;
12667 return setValueV2f;
12671 return setValueV3f;
12675 return setValueV4f;
12692 return setValueV1i;
12697 return setValueV2i;
12702 return setValueV3i;
12707 return setValueV4i;
12711 return setValueV1ui;
12714 case 0x8b5e: // SAMPLER_2D
12716 case 0x8d66: // SAMPLER_EXTERNAL_OES
12718 case 0x8dca: // INT_SAMPLER_2D
12720 case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
12723 // SAMPLER_2D_SHADOW
12726 case 0x8b5f: // SAMPLER_3D
12728 case 0x8dcb: // INT_SAMPLER_3D
12731 // UNSIGNED_INT_SAMPLER_3D
12732 return setValueT3D1;
12734 case 0x8b60: // SAMPLER_CUBE
12736 case 0x8dcc: // INT_SAMPLER_CUBE
12738 case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
12741 // SAMPLER_CUBE_SHADOW
12744 case 0x8dc1: // SAMPLER_2D_ARRAY
12746 case 0x8dcf: // INT_SAMPLER_2D_ARRAY
12748 case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
12751 // SAMPLER_2D_ARRAY_SHADOW
12752 return setValueT2DArray1;
12754 } // Array of scalars
12757 function setValueV1fArray(gl, v) {
12758 gl.uniform1fv(this.addr, v);
12759 } // Integer / Boolean vectors or arrays thereof (always flat arrays)
12762 function setValueV1iArray(gl, v) {
12763 gl.uniform1iv(this.addr, v);
12766 function setValueV2iArray(gl, v) {
12767 gl.uniform2iv(this.addr, v);
12770 function setValueV3iArray(gl, v) {
12771 gl.uniform3iv(this.addr, v);
12774 function setValueV4iArray(gl, v) {
12775 gl.uniform4iv(this.addr, v);
12776 } // Array of vectors (flat or from THREE classes)
12779 function setValueV2fArray(gl, v) {
12780 var data = flatten(v, this.size, 2);
12781 gl.uniform2fv(this.addr, data);
12784 function setValueV3fArray(gl, v) {
12785 var data = flatten(v, this.size, 3);
12786 gl.uniform3fv(this.addr, data);
12789 function setValueV4fArray(gl, v) {
12790 var data = flatten(v, this.size, 4);
12791 gl.uniform4fv(this.addr, data);
12792 } // Array of matrices (flat or from THREE clases)
12795 function setValueM2Array(gl, v) {
12796 var data = flatten(v, this.size, 4);
12797 gl.uniformMatrix2fv(this.addr, false, data);
12800 function setValueM3Array(gl, v) {
12801 var data = flatten(v, this.size, 9);
12802 gl.uniformMatrix3fv(this.addr, false, data);
12805 function setValueM4Array(gl, v) {
12806 var data = flatten(v, this.size, 16);
12807 gl.uniformMatrix4fv(this.addr, false, data);
12808 } // Array of textures (2D / Cube)
12811 function setValueT1Array(gl, v, textures) {
12813 var units = allocTexUnits(textures, n);
12814 gl.uniform1iv(this.addr, units);
12816 for (var i = 0; i !== n; ++i) {
12817 textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
12821 function setValueT6Array(gl, v, textures) {
12823 var units = allocTexUnits(textures, n);
12824 gl.uniform1iv(this.addr, units);
12826 for (var i = 0; i !== n; ++i) {
12827 textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
12829 } // Helper to pick the right setter for a pure (bottom-level) array
12832 function getPureArraySetter(type) {
12835 return setValueV1fArray;
12839 return setValueV2fArray;
12843 return setValueV3fArray;
12847 return setValueV4fArray;
12851 return setValueM2Array;
12855 return setValueM3Array;
12859 return setValueM4Array;
12864 return setValueV1iArray;
12869 return setValueV2iArray;
12874 return setValueV3iArray;
12879 return setValueV4iArray;
12882 case 0x8b5e: // SAMPLER_2D
12884 case 0x8d66: // SAMPLER_EXTERNAL_OES
12886 case 0x8dca: // INT_SAMPLER_2D
12888 case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
12891 // SAMPLER_2D_SHADOW
12892 return setValueT1Array;
12894 case 0x8b60: // SAMPLER_CUBE
12896 case 0x8dcc: // INT_SAMPLER_CUBE
12898 case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
12901 // SAMPLER_CUBE_SHADOW
12902 return setValueT6Array;
12904 } // --- Uniform Classes ---
12907 function SingleUniform(id, activeInfo, addr) {
12911 this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
12914 function PureArrayUniform(id, activeInfo, addr) {
12918 this.size = activeInfo.size;
12919 this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
12922 PureArrayUniform.prototype.updateCache = function (data) {
12923 var cache = this.cache;
12925 if (data instanceof Float32Array && cache.length !== data.length) {
12926 this.cache = new Float32Array(data.length);
12929 copyArray(cache, data);
12932 function StructuredUniform(id) {
12938 StructuredUniform.prototype.setValue = function (gl, value, textures) {
12939 var seq = this.seq;
12941 for (var i = 0, n = seq.length; i !== n; ++i) {
12943 u.setValue(gl, value[u.id], textures);
12945 }; // --- Top-level ---
12946 // Parser - builds up the property tree from the path strings
12949 var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
12950 // - the identifier (member name or array index)
12951 // - followed by an optional right bracket (found when array index)
12952 // - followed by an optional left bracket or dot (type of subscript)
12954 // Note: These portions can be read in a non-overlapping fashion and
12955 // allow straightforward parsing of the hierarchy that WebGL encodes
12956 // in the uniform names.
12958 function addUniform(container, uniformObject) {
12959 container.seq.push(uniformObject);
12960 container.map[uniformObject.id] = uniformObject;
12963 function parseUniform(activeInfo, addr, container) {
12964 var path = activeInfo.name,
12965 pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
12967 RePathPart.lastIndex = 0;
12970 var match = RePathPart.exec(path),
12971 matchEnd = RePathPart.lastIndex;
12973 var idIsIndex = match[2] === ']',
12974 subscript = match[3];
12975 if (idIsIndex) id = id | 0; // convert to integer
12977 if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
12978 // bare name or "pure" bottom-level array "[0]" suffix
12979 addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
12982 // step into inner node / create it in case it doesn't exist
12983 var map = container.map;
12984 var next = map[id];
12986 if (next === undefined) {
12987 next = new StructuredUniform(id);
12988 addUniform(container, next);
12994 } // Root Container
12997 function WebGLUniforms(gl, program) {
13000 var n = gl.getProgramParameter(program, 35718);
13002 for (var i = 0; i < n; ++i) {
13003 var info = gl.getActiveUniform(program, i),
13004 addr = gl.getUniformLocation(program, info.name);
13005 parseUniform(info, addr, this);
13009 WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
13010 var u = this.map[name];
13011 if (u !== undefined) u.setValue(gl, value, textures);
13014 WebGLUniforms.prototype.setOptional = function (gl, object, name) {
13015 var v = object[name];
13016 if (v !== undefined) this.setValue(gl, name, v);
13017 }; // Static interface
13020 WebGLUniforms.upload = function (gl, seq, values, textures) {
13021 for (var i = 0, n = seq.length; i !== n; ++i) {
13025 if (v.needsUpdate !== false) {
13026 // note: always updating when .needsUpdate is undefined
13027 u.setValue(gl, v.value, textures);
13032 WebGLUniforms.seqWithValue = function (seq, values) {
13035 for (var i = 0, n = seq.length; i !== n; ++i) {
13037 if (u.id in values) r.push(u);
13043 function WebGLShader(gl, type, string) {
13044 var shader = gl.createShader(type);
13045 gl.shaderSource(shader, string);
13046 gl.compileShader(shader);
13050 var programIdCount = 0;
13052 function addLineNumbers(string) {
13053 var lines = string.split('\n');
13055 for (var i = 0; i < lines.length; i++) {
13056 lines[i] = i + 1 + ': ' + lines[i];
13059 return lines.join('\n');
13062 function getEncodingComponents(encoding) {
13063 switch (encoding) {
13064 case LinearEncoding:
13065 return ['Linear', '( value )'];
13068 return ['sRGB', '( value )'];
13071 return ['RGBE', '( value )'];
13073 case RGBM7Encoding:
13074 return ['RGBM', '( value, 7.0 )'];
13076 case RGBM16Encoding:
13077 return ['RGBM', '( value, 16.0 )'];
13080 return ['RGBD', '( value, 256.0 )'];
13082 case GammaEncoding:
13083 return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
13085 case LogLuvEncoding:
13086 return ['LogLuv', '( value )'];
13089 console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
13090 return ['Linear', '( value )'];
13094 function getShaderErrors(gl, shader, type) {
13095 var status = gl.getShaderParameter(shader, 35713);
13096 var log = gl.getShaderInfoLog(shader).trim();
13097 if (status && log === '') return ''; // --enable-privileged-webgl-extension
13098 // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
13100 var source = gl.getShaderSource(shader);
13101 return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
13104 function getTexelDecodingFunction(functionName, encoding) {
13105 var components = getEncodingComponents(encoding);
13106 return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
13109 function getTexelEncodingFunction(functionName, encoding) {
13110 var components = getEncodingComponents(encoding);
13111 return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
13114 function getToneMappingFunction(functionName, toneMapping) {
13115 var toneMappingName;
13117 switch (toneMapping) {
13118 case LinearToneMapping:
13119 toneMappingName = 'Linear';
13122 case ReinhardToneMapping:
13123 toneMappingName = 'Reinhard';
13126 case CineonToneMapping:
13127 toneMappingName = 'OptimizedCineon';
13130 case ACESFilmicToneMapping:
13131 toneMappingName = 'ACESFilmic';
13134 case CustomToneMapping:
13135 toneMappingName = 'Custom';
13139 console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
13140 toneMappingName = 'Linear';
13143 return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
13146 function generateExtensions(parameters) {
13147 var 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.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
13148 return chunks.filter(filterEmptyLine).join('\n');
13151 function generateDefines(defines) {
13154 for (var name in defines) {
13155 var value = defines[name];
13156 if (value === false) continue;
13157 chunks.push('#define ' + name + ' ' + value);
13160 return chunks.join('\n');
13163 function fetchAttributeLocations(gl, program) {
13164 var attributes = {};
13165 var n = gl.getProgramParameter(program, 35721);
13167 for (var i = 0; i < n; i++) {
13168 var info = gl.getActiveAttrib(program, i);
13169 var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
13171 attributes[name] = gl.getAttribLocation(program, name);
13177 function filterEmptyLine(string) {
13178 return string !== '';
13181 function replaceLightNums(string, parameters) {
13182 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);
13185 function replaceClippingPlaneNums(string, parameters) {
13186 return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
13187 } // Resolve Includes
13190 var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
13192 function resolveIncludes(string) {
13193 return string.replace(includePattern, includeReplacer);
13196 function includeReplacer(match, include) {
13197 var string = ShaderChunk[include];
13199 if (string === undefined) {
13200 throw new Error('Can not resolve #include <' + include + '>');
13203 return resolveIncludes(string);
13207 var deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
13208 var 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;
13210 function unrollLoops(string) {
13211 return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
13214 function deprecatedLoopReplacer(match, start, end, snippet) {
13215 console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
13216 return loopReplacer(match, start, end, snippet);
13219 function loopReplacer(match, start, end, snippet) {
13222 for (var i = parseInt(start); i < parseInt(end); i++) {
13223 string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
13230 function generatePrecision(parameters) {
13231 var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
13233 if (parameters.precision === "highp") {
13234 precisionstring += "\n#define HIGH_PRECISION";
13235 } else if (parameters.precision === "mediump") {
13236 precisionstring += "\n#define MEDIUM_PRECISION";
13237 } else if (parameters.precision === "lowp") {
13238 precisionstring += "\n#define LOW_PRECISION";
13241 return precisionstring;
13244 function generateShadowMapTypeDefine(parameters) {
13245 var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
13247 if (parameters.shadowMapType === PCFShadowMap) {
13248 shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
13249 } else if (parameters.shadowMapType === PCFSoftShadowMap) {
13250 shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
13251 } else if (parameters.shadowMapType === VSMShadowMap) {
13252 shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
13255 return shadowMapTypeDefine;
13258 function generateEnvMapTypeDefine(parameters) {
13259 var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
13261 if (parameters.envMap) {
13262 switch (parameters.envMapMode) {
13263 case CubeReflectionMapping:
13264 case CubeRefractionMapping:
13265 envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
13268 case CubeUVReflectionMapping:
13269 case CubeUVRefractionMapping:
13270 envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
13275 return envMapTypeDefine;
13278 function generateEnvMapModeDefine(parameters) {
13279 var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
13281 if (parameters.envMap) {
13282 switch (parameters.envMapMode) {
13283 case CubeRefractionMapping:
13284 case CubeUVRefractionMapping:
13285 envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
13290 return envMapModeDefine;
13293 function generateEnvMapBlendingDefine(parameters) {
13294 var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
13296 if (parameters.envMap) {
13297 switch (parameters.combine) {
13298 case MultiplyOperation:
13299 envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
13303 envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
13307 envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
13312 return envMapBlendingDefine;
13315 function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
13316 var gl = renderer.getContext();
13317 var defines = parameters.defines;
13318 var vertexShader = parameters.vertexShader;
13319 var fragmentShader = parameters.fragmentShader;
13320 var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
13321 var envMapTypeDefine = generateEnvMapTypeDefine(parameters);
13322 var envMapModeDefine = generateEnvMapModeDefine(parameters);
13323 var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
13324 var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
13325 var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
13326 var customDefines = generateDefines(defines);
13327 var program = gl.createProgram();
13328 var prefixVertex, prefixFragment;
13329 var versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + "\n" : '';
13331 if (parameters.isRawShaderMaterial) {
13332 prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
13334 if (prefixVertex.length > 0) {
13335 prefixVertex += '\n';
13338 prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
13340 if (prefixFragment.length > 0) {
13341 prefixFragment += '\n';
13344 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 GAMMA_FACTOR ' + gammaFactorDefine, '#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.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', 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.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', '#ifdef USE_COLOR', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
13345 prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
13346 '#define GAMMA_FACTOR ' + gammaFactorDefine, 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.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', 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
13347 parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
13348 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.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
13351 vertexShader = resolveIncludes(vertexShader);
13352 vertexShader = replaceLightNums(vertexShader, parameters);
13353 vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
13354 fragmentShader = resolveIncludes(fragmentShader);
13355 fragmentShader = replaceLightNums(fragmentShader, parameters);
13356 fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
13357 vertexShader = unrollLoops(vertexShader);
13358 fragmentShader = unrollLoops(fragmentShader);
13360 if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
13361 // GLSL 3.0 conversion for built-in materials and ShaderMaterial
13362 versionString = '#version 300 es\n';
13363 prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
13364 prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : '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;
13367 var vertexGlsl = versionString + prefixVertex + vertexShader;
13368 var fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
13369 // console.log( '*FRAGMENT*', fragmentGlsl );
13371 var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
13372 var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
13373 gl.attachShader(program, glVertexShader);
13374 gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
13376 if (parameters.index0AttributeName !== undefined) {
13377 gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
13378 } else if (parameters.morphTargets === true) {
13379 // programs with morphTargets displace position out of attribute 0
13380 gl.bindAttribLocation(program, 0, 'position');
13383 gl.linkProgram(program); // check for link errors
13385 if (renderer.debug.checkShaderErrors) {
13386 var programLog = gl.getProgramInfoLog(program).trim();
13387 var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
13388 var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
13389 var runnable = true;
13390 var haveDiagnostics = true;
13392 if (gl.getProgramParameter(program, 35714) === false) {
13394 var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
13395 var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
13396 console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
13397 } else if (programLog !== '') {
13398 console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
13399 } else if (vertexLog === '' || fragmentLog === '') {
13400 haveDiagnostics = false;
13403 if (haveDiagnostics) {
13404 this.diagnostics = {
13405 runnable: runnable,
13406 programLog: programLog,
13409 prefix: prefixVertex
13413 prefix: prefixFragment
13418 // Crashes in iOS9 and iOS10. #18402
13419 // gl.detachShader( program, glVertexShader );
13420 // gl.detachShader( program, glFragmentShader );
13423 gl.deleteShader(glVertexShader);
13424 gl.deleteShader(glFragmentShader); // set up caching for uniform locations
13426 var cachedUniforms;
13428 this.getUniforms = function () {
13429 if (cachedUniforms === undefined) {
13430 cachedUniforms = new WebGLUniforms(gl, program);
13433 return cachedUniforms;
13434 }; // set up caching for attribute locations
13437 var cachedAttributes;
13439 this.getAttributes = function () {
13440 if (cachedAttributes === undefined) {
13441 cachedAttributes = fetchAttributeLocations(gl, program);
13444 return cachedAttributes;
13445 }; // free resource
13448 this.destroy = function () {
13449 bindingStates.releaseStatesOfProgram(this);
13450 gl.deleteProgram(program);
13451 this.program = undefined;
13455 this.name = parameters.shaderName;
13456 this.id = programIdCount++;
13457 this.cacheKey = cacheKey;
13458 this.usedTimes = 1;
13459 this.program = program;
13460 this.vertexShader = glVertexShader;
13461 this.fragmentShader = glFragmentShader;
13465 function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
13467 var isWebGL2 = capabilities.isWebGL2;
13468 var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
13469 var floatVertexTextures = capabilities.floatVertexTextures;
13470 var maxVertexUniforms = capabilities.maxVertexUniforms;
13471 var vertexTextures = capabilities.vertexTextures;
13472 var precision = capabilities.precision;
13474 MeshDepthMaterial: 'depth',
13475 MeshDistanceMaterial: 'distanceRGBA',
13476 MeshNormalMaterial: 'normal',
13477 MeshBasicMaterial: 'basic',
13478 MeshLambertMaterial: 'lambert',
13479 MeshPhongMaterial: 'phong',
13480 MeshToonMaterial: 'toon',
13481 MeshStandardMaterial: 'physical',
13482 MeshPhysicalMaterial: 'physical',
13483 MeshMatcapMaterial: 'matcap',
13484 LineBasicMaterial: 'basic',
13485 LineDashedMaterial: 'dashed',
13486 PointsMaterial: 'points',
13487 ShadowMaterial: 'shadow',
13488 SpriteMaterial: 'sprite'
13490 var parameterNames = ["precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", "instancingColor", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV", "lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap", "roughnessMap", "metalnessMap", "gradientMap", "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals", "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows", "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", "sheen", "transmissionMap"];
13492 function getMaxBones(object) {
13493 var skeleton = object.skeleton;
13494 var bones = skeleton.bones;
13496 if (floatVertexTextures) {
13499 // default for when object is not specified
13500 // ( for example when prebuilding shader to be used with multiple objects )
13502 // - leave some extra space for other uniforms
13503 // - limit here is ANGLE's 254 max uniform vectors
13504 // (up to 54 should be safe)
13505 var nVertexUniforms = maxVertexUniforms;
13506 var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
13507 var maxBones = Math.min(nVertexMatrices, bones.length);
13509 if (maxBones < bones.length) {
13510 console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
13518 function getTextureEncodingFromMap(map) {
13522 encoding = LinearEncoding;
13523 } else if (map.isTexture) {
13524 encoding = map.encoding;
13525 } else if (map.isWebGLRenderTarget) {
13526 console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
13527 encoding = map.texture.encoding;
13533 function getParameters(material, lights, shadows, scene, object) {
13534 var fog = scene.fog;
13535 var environment = material.isMeshStandardMaterial ? scene.environment : null;
13536 var envMap = cubemaps.get(material.envMap || environment);
13537 var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
13538 // (not to blow over maxLights budget)
13540 var maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
13542 if (material.precision !== null) {
13543 precision = capabilities.getMaxPrecision(material.precision);
13545 if (precision !== material.precision) {
13546 console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
13550 var vertexShader, fragmentShader;
13553 var shader = ShaderLib[shaderID];
13554 vertexShader = shader.vertexShader;
13555 fragmentShader = shader.fragmentShader;
13557 vertexShader = material.vertexShader;
13558 fragmentShader = material.fragmentShader;
13561 var currentRenderTarget = renderer.getRenderTarget();
13563 isWebGL2: isWebGL2,
13564 shaderID: shaderID,
13565 shaderName: material.type,
13566 vertexShader: vertexShader,
13567 fragmentShader: fragmentShader,
13568 defines: material.defines,
13569 isRawShaderMaterial: material.isRawShaderMaterial === true,
13570 glslVersion: material.glslVersion,
13571 precision: precision,
13572 instancing: object.isInstancedMesh === true,
13573 instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
13574 supportsVertexTextures: vertexTextures,
13575 outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
13576 map: !!material.map,
13577 mapEncoding: getTextureEncodingFromMap(material.map),
13578 matcap: !!material.matcap,
13579 matcapEncoding: getTextureEncodingFromMap(material.matcap),
13581 envMapMode: envMap && envMap.mapping,
13582 envMapEncoding: getTextureEncodingFromMap(envMap),
13583 envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
13584 lightMap: !!material.lightMap,
13585 lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
13586 aoMap: !!material.aoMap,
13587 emissiveMap: !!material.emissiveMap,
13588 emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
13589 bumpMap: !!material.bumpMap,
13590 normalMap: !!material.normalMap,
13591 objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
13592 tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
13593 clearcoatMap: !!material.clearcoatMap,
13594 clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
13595 clearcoatNormalMap: !!material.clearcoatNormalMap,
13596 displacementMap: !!material.displacementMap,
13597 roughnessMap: !!material.roughnessMap,
13598 metalnessMap: !!material.metalnessMap,
13599 specularMap: !!material.specularMap,
13600 alphaMap: !!material.alphaMap,
13601 gradientMap: !!material.gradientMap,
13602 sheen: !!material.sheen,
13603 transmissionMap: !!material.transmissionMap,
13604 combine: material.combine,
13605 vertexTangents: material.normalMap && material.vertexTangents,
13606 vertexColors: material.vertexColors,
13607 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,
13608 uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmissionMap) && !!material.displacementMap,
13610 useFog: material.fog,
13611 fogExp2: fog && fog.isFogExp2,
13612 flatShading: material.flatShading,
13613 sizeAttenuation: material.sizeAttenuation,
13614 logarithmicDepthBuffer: logarithmicDepthBuffer,
13615 skinning: material.skinning && maxBones > 0,
13616 maxBones: maxBones,
13617 useVertexTexture: floatVertexTextures,
13618 morphTargets: material.morphTargets,
13619 morphNormals: material.morphNormals,
13620 maxMorphTargets: renderer.maxMorphTargets,
13621 maxMorphNormals: renderer.maxMorphNormals,
13622 numDirLights: lights.directional.length,
13623 numPointLights: lights.point.length,
13624 numSpotLights: lights.spot.length,
13625 numRectAreaLights: lights.rectArea.length,
13626 numHemiLights: lights.hemi.length,
13627 numDirLightShadows: lights.directionalShadowMap.length,
13628 numPointLightShadows: lights.pointShadowMap.length,
13629 numSpotLightShadows: lights.spotShadowMap.length,
13630 numClippingPlanes: clipping.numPlanes,
13631 numClipIntersection: clipping.numIntersection,
13632 dithering: material.dithering,
13633 shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
13634 shadowMapType: renderer.shadowMap.type,
13635 toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
13636 physicallyCorrectLights: renderer.physicallyCorrectLights,
13637 premultipliedAlpha: material.premultipliedAlpha,
13638 alphaTest: material.alphaTest,
13639 doubleSided: material.side === DoubleSide,
13640 flipSided: material.side === BackSide,
13641 depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
13642 index0AttributeName: material.index0AttributeName,
13643 extensionDerivatives: material.extensions && material.extensions.derivatives,
13644 extensionFragDepth: material.extensions && material.extensions.fragDepth,
13645 extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
13646 extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
13647 rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
13648 rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
13649 rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
13650 customProgramCacheKey: material.customProgramCacheKey()
13655 function getProgramCacheKey(parameters) {
13658 if (parameters.shaderID) {
13659 array.push(parameters.shaderID);
13661 array.push(parameters.fragmentShader);
13662 array.push(parameters.vertexShader);
13665 if (parameters.defines !== undefined) {
13666 for (var name in parameters.defines) {
13668 array.push(parameters.defines[name]);
13672 if (parameters.isRawShaderMaterial === false) {
13673 for (var i = 0; i < parameterNames.length; i++) {
13674 array.push(parameters[parameterNames[i]]);
13677 array.push(renderer.outputEncoding);
13678 array.push(renderer.gammaFactor);
13681 array.push(parameters.customProgramCacheKey);
13682 return array.join();
13685 function getUniforms(material) {
13686 var shaderID = shaderIDs[material.type];
13690 var shader = ShaderLib[shaderID];
13691 uniforms = UniformsUtils.clone(shader.uniforms);
13693 uniforms = material.uniforms;
13699 function acquireProgram(parameters, cacheKey) {
13700 var program; // Check if code has been already compiled
13702 for (var p = 0, pl = programs.length; p < pl; p++) {
13703 var preexistingProgram = programs[p];
13705 if (preexistingProgram.cacheKey === cacheKey) {
13706 program = preexistingProgram;
13707 ++program.usedTimes;
13712 if (program === undefined) {
13713 program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
13714 programs.push(program);
13720 function releaseProgram(program) {
13721 if (--program.usedTimes === 0) {
13722 // Remove from unordered set
13723 var i = programs.indexOf(program);
13724 programs[i] = programs[programs.length - 1];
13725 programs.pop(); // Free WebGL resources
13732 getParameters: getParameters,
13733 getProgramCacheKey: getProgramCacheKey,
13734 getUniforms: getUniforms,
13735 acquireProgram: acquireProgram,
13736 releaseProgram: releaseProgram,
13737 // Exposed for resource monitoring & error feedback via renderer.info:
13742 function WebGLProperties() {
13743 var properties = new WeakMap();
13745 function get(object) {
13746 var map = properties.get(object);
13748 if (map === undefined) {
13750 properties.set(object, map);
13756 function remove(object) {
13757 properties.delete(object);
13760 function update(object, key, value) {
13761 properties.get(object)[key] = value;
13764 function dispose() {
13765 properties = new WeakMap();
13776 function painterSortStable(a, b) {
13777 if (a.groupOrder !== b.groupOrder) {
13778 return a.groupOrder - b.groupOrder;
13779 } else if (a.renderOrder !== b.renderOrder) {
13780 return a.renderOrder - b.renderOrder;
13781 } else if (a.program !== b.program) {
13782 return a.program.id - b.program.id;
13783 } else if (a.material.id !== b.material.id) {
13784 return a.material.id - b.material.id;
13785 } else if (a.z !== b.z) {
13788 return a.id - b.id;
13792 function reversePainterSortStable(a, b) {
13793 if (a.groupOrder !== b.groupOrder) {
13794 return a.groupOrder - b.groupOrder;
13795 } else if (a.renderOrder !== b.renderOrder) {
13796 return a.renderOrder - b.renderOrder;
13797 } else if (a.z !== b.z) {
13800 return a.id - b.id;
13804 function WebGLRenderList(properties) {
13805 var renderItems = [];
13806 var renderItemsIndex = 0;
13808 var transparent = [];
13809 var defaultProgram = {
13814 renderItemsIndex = 0;
13816 transparent.length = 0;
13819 function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
13820 var renderItem = renderItems[renderItemsIndex];
13821 var materialProperties = properties.get(material);
13823 if (renderItem === undefined) {
13827 geometry: geometry,
13828 material: material,
13829 program: materialProperties.program || defaultProgram,
13830 groupOrder: groupOrder,
13831 renderOrder: object.renderOrder,
13835 renderItems[renderItemsIndex] = renderItem;
13837 renderItem.id = object.id;
13838 renderItem.object = object;
13839 renderItem.geometry = geometry;
13840 renderItem.material = material;
13841 renderItem.program = materialProperties.program || defaultProgram;
13842 renderItem.groupOrder = groupOrder;
13843 renderItem.renderOrder = object.renderOrder;
13845 renderItem.group = group;
13848 renderItemsIndex++;
13852 function push(object, geometry, material, groupOrder, z, group) {
13853 var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
13854 (material.transparent === true ? transparent : opaque).push(renderItem);
13857 function unshift(object, geometry, material, groupOrder, z, group) {
13858 var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
13859 (material.transparent === true ? transparent : opaque).unshift(renderItem);
13862 function sort(customOpaqueSort, customTransparentSort) {
13863 if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
13864 if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
13867 function finish() {
13868 // Clear references from inactive renderItems in the list
13869 for (var i = renderItemsIndex, il = renderItems.length; i < il; i++) {
13870 var renderItem = renderItems[i];
13871 if (renderItem.id === null) break;
13872 renderItem.id = null;
13873 renderItem.object = null;
13874 renderItem.geometry = null;
13875 renderItem.material = null;
13876 renderItem.program = null;
13877 renderItem.group = null;
13883 transparent: transparent,
13892 function WebGLRenderLists(properties) {
13893 var lists = new WeakMap();
13895 function get(scene, camera) {
13896 var cameras = lists.get(scene);
13899 if (cameras === undefined) {
13900 list = new WebGLRenderList(properties);
13901 lists.set(scene, new WeakMap());
13902 lists.get(scene).set(camera, list);
13904 list = cameras.get(camera);
13906 if (list === undefined) {
13907 list = new WebGLRenderList(properties);
13908 cameras.set(camera, list);
13915 function dispose() {
13916 lists = new WeakMap();
13925 function UniformsCache() {
13928 get: function get(light) {
13929 if (lights[light.id] !== undefined) {
13930 return lights[light.id];
13935 switch (light.type) {
13936 case 'DirectionalLight':
13938 direction: new Vector3(),
13945 position: new Vector3(),
13946 direction: new Vector3(),
13947 color: new Color(),
13957 position: new Vector3(),
13958 color: new Color(),
13964 case 'HemisphereLight':
13966 direction: new Vector3(),
13967 skyColor: new Color(),
13968 groundColor: new Color()
13972 case 'RectAreaLight':
13974 color: new Color(),
13975 position: new Vector3(),
13976 halfWidth: new Vector3(),
13977 halfHeight: new Vector3()
13982 lights[light.id] = uniforms;
13988 function ShadowUniformsCache() {
13991 get: function get(light) {
13992 if (lights[light.id] !== undefined) {
13993 return lights[light.id];
13998 switch (light.type) {
13999 case 'DirectionalLight':
14002 shadowNormalBias: 0,
14004 shadowMapSize: new Vector2()
14011 shadowNormalBias: 0,
14013 shadowMapSize: new Vector2()
14020 shadowNormalBias: 0,
14022 shadowMapSize: new Vector2(),
14023 shadowCameraNear: 1,
14024 shadowCameraFar: 1000
14027 // TODO (abelnation): set RectAreaLight shadow uniforms
14030 lights[light.id] = uniforms;
14036 var nextVersion = 0;
14038 function shadowCastingLightsFirst(lightA, lightB) {
14039 return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
14042 function WebGLLights(extensions, capabilities) {
14043 var cache = new UniformsCache();
14044 var shadowCache = ShadowUniformsCache();
14048 directionalLength: -1,
14051 rectAreaLength: -1,
14053 numDirectionalShadows: -1,
14054 numPointShadows: -1,
14057 ambient: [0, 0, 0],
14060 directionalShadow: [],
14061 directionalShadowMap: [],
14062 directionalShadowMatrix: [],
14066 spotShadowMatrix: [],
14068 rectAreaLTC1: null,
14069 rectAreaLTC2: null,
14072 pointShadowMap: [],
14073 pointShadowMatrix: [],
14077 for (var i = 0; i < 9; i++) {
14078 state.probe.push(new Vector3());
14081 var vector3 = new Vector3();
14082 var matrix4 = new Matrix4();
14083 var matrix42 = new Matrix4();
14085 function setup(lights, shadows, camera) {
14090 for (var _i = 0; _i < 9; _i++) {
14091 state.probe[_i].set(0, 0, 0);
14094 var directionalLength = 0;
14095 var pointLength = 0;
14096 var spotLength = 0;
14097 var rectAreaLength = 0;
14098 var hemiLength = 0;
14099 var numDirectionalShadows = 0;
14100 var numPointShadows = 0;
14101 var numSpotShadows = 0;
14102 var viewMatrix = camera.matrixWorldInverse;
14103 lights.sort(shadowCastingLightsFirst);
14105 for (var _i2 = 0, l = lights.length; _i2 < l; _i2++) {
14106 var light = lights[_i2];
14107 var color = light.color;
14108 var intensity = light.intensity;
14109 var distance = light.distance;
14110 var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
14112 if (light.isAmbientLight) {
14113 r += color.r * intensity;
14114 g += color.g * intensity;
14115 b += color.b * intensity;
14116 } else if (light.isLightProbe) {
14117 for (var j = 0; j < 9; j++) {
14118 state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
14120 } else if (light.isDirectionalLight) {
14121 var uniforms = cache.get(light);
14122 uniforms.color.copy(light.color).multiplyScalar(light.intensity);
14123 uniforms.direction.setFromMatrixPosition(light.matrixWorld);
14124 vector3.setFromMatrixPosition(light.target.matrixWorld);
14125 uniforms.direction.sub(vector3);
14126 uniforms.direction.transformDirection(viewMatrix);
14128 if (light.castShadow) {
14129 var shadow = light.shadow;
14130 var shadowUniforms = shadowCache.get(light);
14131 shadowUniforms.shadowBias = shadow.bias;
14132 shadowUniforms.shadowNormalBias = shadow.normalBias;
14133 shadowUniforms.shadowRadius = shadow.radius;
14134 shadowUniforms.shadowMapSize = shadow.mapSize;
14135 state.directionalShadow[directionalLength] = shadowUniforms;
14136 state.directionalShadowMap[directionalLength] = shadowMap;
14137 state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
14138 numDirectionalShadows++;
14141 state.directional[directionalLength] = uniforms;
14142 directionalLength++;
14143 } else if (light.isSpotLight) {
14144 var _uniforms = cache.get(light);
14146 _uniforms.position.setFromMatrixPosition(light.matrixWorld);
14148 _uniforms.position.applyMatrix4(viewMatrix);
14150 _uniforms.color.copy(color).multiplyScalar(intensity);
14152 _uniforms.distance = distance;
14154 _uniforms.direction.setFromMatrixPosition(light.matrixWorld);
14156 vector3.setFromMatrixPosition(light.target.matrixWorld);
14158 _uniforms.direction.sub(vector3);
14160 _uniforms.direction.transformDirection(viewMatrix);
14162 _uniforms.coneCos = Math.cos(light.angle);
14163 _uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
14164 _uniforms.decay = light.decay;
14166 if (light.castShadow) {
14167 var _shadow = light.shadow;
14169 var _shadowUniforms = shadowCache.get(light);
14171 _shadowUniforms.shadowBias = _shadow.bias;
14172 _shadowUniforms.shadowNormalBias = _shadow.normalBias;
14173 _shadowUniforms.shadowRadius = _shadow.radius;
14174 _shadowUniforms.shadowMapSize = _shadow.mapSize;
14175 state.spotShadow[spotLength] = _shadowUniforms;
14176 state.spotShadowMap[spotLength] = shadowMap;
14177 state.spotShadowMatrix[spotLength] = light.shadow.matrix;
14181 state.spot[spotLength] = _uniforms;
14183 } else if (light.isRectAreaLight) {
14184 var _uniforms2 = cache.get(light); // (a) intensity is the total visible light emitted
14185 //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
14186 // (b) intensity is the brightness of the light
14189 _uniforms2.color.copy(color).multiplyScalar(intensity);
14191 _uniforms2.position.setFromMatrixPosition(light.matrixWorld);
14193 _uniforms2.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
14196 matrix42.identity();
14197 matrix4.copy(light.matrixWorld);
14198 matrix4.premultiply(viewMatrix);
14199 matrix42.extractRotation(matrix4);
14201 _uniforms2.halfWidth.set(light.width * 0.5, 0.0, 0.0);
14203 _uniforms2.halfHeight.set(0.0, light.height * 0.5, 0.0);
14205 _uniforms2.halfWidth.applyMatrix4(matrix42);
14207 _uniforms2.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
14208 // uniforms.distance = distance;
14211 state.rectArea[rectAreaLength] = _uniforms2;
14213 } else if (light.isPointLight) {
14214 var _uniforms3 = cache.get(light);
14216 _uniforms3.position.setFromMatrixPosition(light.matrixWorld);
14218 _uniforms3.position.applyMatrix4(viewMatrix);
14220 _uniforms3.color.copy(light.color).multiplyScalar(light.intensity);
14222 _uniforms3.distance = light.distance;
14223 _uniforms3.decay = light.decay;
14225 if (light.castShadow) {
14226 var _shadow2 = light.shadow;
14228 var _shadowUniforms2 = shadowCache.get(light);
14230 _shadowUniforms2.shadowBias = _shadow2.bias;
14231 _shadowUniforms2.shadowNormalBias = _shadow2.normalBias;
14232 _shadowUniforms2.shadowRadius = _shadow2.radius;
14233 _shadowUniforms2.shadowMapSize = _shadow2.mapSize;
14234 _shadowUniforms2.shadowCameraNear = _shadow2.camera.near;
14235 _shadowUniforms2.shadowCameraFar = _shadow2.camera.far;
14236 state.pointShadow[pointLength] = _shadowUniforms2;
14237 state.pointShadowMap[pointLength] = shadowMap;
14238 state.pointShadowMatrix[pointLength] = light.shadow.matrix;
14242 state.point[pointLength] = _uniforms3;
14244 } else if (light.isHemisphereLight) {
14245 var _uniforms4 = cache.get(light);
14247 _uniforms4.direction.setFromMatrixPosition(light.matrixWorld);
14249 _uniforms4.direction.transformDirection(viewMatrix);
14251 _uniforms4.direction.normalize();
14253 _uniforms4.skyColor.copy(light.color).multiplyScalar(intensity);
14255 _uniforms4.groundColor.copy(light.groundColor).multiplyScalar(intensity);
14257 state.hemi[hemiLength] = _uniforms4;
14262 if (rectAreaLength > 0) {
14263 if (capabilities.isWebGL2) {
14265 state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
14266 state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
14269 if (extensions.has('OES_texture_float_linear') === true) {
14270 state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
14271 state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
14272 } else if (extensions.has('OES_texture_half_float_linear') === true) {
14273 state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
14274 state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
14276 console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
14281 state.ambient[0] = r;
14282 state.ambient[1] = g;
14283 state.ambient[2] = b;
14284 var hash = state.hash;
14286 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) {
14287 state.directional.length = directionalLength;
14288 state.spot.length = spotLength;
14289 state.rectArea.length = rectAreaLength;
14290 state.point.length = pointLength;
14291 state.hemi.length = hemiLength;
14292 state.directionalShadow.length = numDirectionalShadows;
14293 state.directionalShadowMap.length = numDirectionalShadows;
14294 state.pointShadow.length = numPointShadows;
14295 state.pointShadowMap.length = numPointShadows;
14296 state.spotShadow.length = numSpotShadows;
14297 state.spotShadowMap.length = numSpotShadows;
14298 state.directionalShadowMatrix.length = numDirectionalShadows;
14299 state.pointShadowMatrix.length = numPointShadows;
14300 state.spotShadowMatrix.length = numSpotShadows;
14301 hash.directionalLength = directionalLength;
14302 hash.pointLength = pointLength;
14303 hash.spotLength = spotLength;
14304 hash.rectAreaLength = rectAreaLength;
14305 hash.hemiLength = hemiLength;
14306 hash.numDirectionalShadows = numDirectionalShadows;
14307 hash.numPointShadows = numPointShadows;
14308 hash.numSpotShadows = numSpotShadows;
14309 state.version = nextVersion++;
14319 function WebGLRenderState(extensions, capabilities) {
14320 var lights = new WebGLLights(extensions, capabilities);
14321 var lightsArray = [];
14322 var shadowsArray = [];
14325 lightsArray.length = 0;
14326 shadowsArray.length = 0;
14329 function pushLight(light) {
14330 lightsArray.push(light);
14333 function pushShadow(shadowLight) {
14334 shadowsArray.push(shadowLight);
14337 function setupLights(camera) {
14338 lights.setup(lightsArray, shadowsArray, camera);
14342 lightsArray: lightsArray,
14343 shadowsArray: shadowsArray,
14349 setupLights: setupLights,
14350 pushLight: pushLight,
14351 pushShadow: pushShadow
14355 function WebGLRenderStates(extensions, capabilities) {
14356 var renderStates = new WeakMap();
14358 function get(scene, camera) {
14361 if (renderStates.has(scene) === false) {
14362 renderState = new WebGLRenderState(extensions, capabilities);
14363 renderStates.set(scene, new WeakMap());
14364 renderStates.get(scene).set(camera, renderState);
14366 if (renderStates.get(scene).has(camera) === false) {
14367 renderState = new WebGLRenderState(extensions, capabilities);
14368 renderStates.get(scene).set(camera, renderState);
14370 renderState = renderStates.get(scene).get(camera);
14374 return renderState;
14377 function dispose() {
14378 renderStates = new WeakMap();
14390 * opacity: <float>,
14392 * map: new THREE.Texture( <Image> ),
14394 * alphaMap: new THREE.Texture( <Image> ),
14396 * displacementMap: new THREE.Texture( <Image> ),
14397 * displacementScale: <float>,
14398 * displacementBias: <float>,
14400 * wireframe: <boolean>,
14401 * wireframeLinewidth: <float>
14405 function MeshDepthMaterial(parameters) {
14406 Material.call(this);
14407 this.type = 'MeshDepthMaterial';
14408 this.depthPacking = BasicDepthPacking;
14409 this.skinning = false;
14410 this.morphTargets = false;
14412 this.alphaMap = null;
14413 this.displacementMap = null;
14414 this.displacementScale = 1;
14415 this.displacementBias = 0;
14416 this.wireframe = false;
14417 this.wireframeLinewidth = 1;
14419 this.setValues(parameters);
14422 MeshDepthMaterial.prototype = Object.create(Material.prototype);
14423 MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
14424 MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
14426 MeshDepthMaterial.prototype.copy = function (source) {
14427 Material.prototype.copy.call(this, source);
14428 this.depthPacking = source.depthPacking;
14429 this.skinning = source.skinning;
14430 this.morphTargets = source.morphTargets;
14431 this.map = source.map;
14432 this.alphaMap = source.alphaMap;
14433 this.displacementMap = source.displacementMap;
14434 this.displacementScale = source.displacementScale;
14435 this.displacementBias = source.displacementBias;
14436 this.wireframe = source.wireframe;
14437 this.wireframeLinewidth = source.wireframeLinewidth;
14444 * referencePosition: <float>,
14445 * nearDistance: <float>,
14446 * farDistance: <float>,
14448 * skinning: <bool>,
14449 * morphTargets: <bool>,
14451 * map: new THREE.Texture( <Image> ),
14453 * alphaMap: new THREE.Texture( <Image> ),
14455 * displacementMap: new THREE.Texture( <Image> ),
14456 * displacementScale: <float>,
14457 * displacementBias: <float>
14462 function MeshDistanceMaterial(parameters) {
14463 Material.call(this);
14464 this.type = 'MeshDistanceMaterial';
14465 this.referencePosition = new Vector3();
14466 this.nearDistance = 1;
14467 this.farDistance = 1000;
14468 this.skinning = false;
14469 this.morphTargets = false;
14471 this.alphaMap = null;
14472 this.displacementMap = null;
14473 this.displacementScale = 1;
14474 this.displacementBias = 0;
14476 this.setValues(parameters);
14479 MeshDistanceMaterial.prototype = Object.create(Material.prototype);
14480 MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
14481 MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
14483 MeshDistanceMaterial.prototype.copy = function (source) {
14484 Material.prototype.copy.call(this, source);
14485 this.referencePosition.copy(source.referencePosition);
14486 this.nearDistance = source.nearDistance;
14487 this.farDistance = source.farDistance;
14488 this.skinning = source.skinning;
14489 this.morphTargets = source.morphTargets;
14490 this.map = source.map;
14491 this.alphaMap = source.alphaMap;
14492 this.displacementMap = source.displacementMap;
14493 this.displacementScale = source.displacementScale;
14494 this.displacementBias = source.displacementBias;
14498 var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 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, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
14500 var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
14502 function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
14503 var _frustum = new Frustum();
14505 var _shadowMapSize = new Vector2(),
14506 _viewportSize = new Vector2(),
14507 _viewport = new Vector4(),
14508 _depthMaterials = [],
14509 _distanceMaterials = [],
14510 _materialCache = {};
14517 var shadowMaterialVertical = new ShaderMaterial({
14519 SAMPLE_RATE: 2.0 / 8.0,
14520 HALF_SAMPLE_RATE: 1.0 / 8.0
14527 value: new Vector2()
14533 vertexShader: vsm_vert,
14534 fragmentShader: vsm_frag
14536 var shadowMaterialHorizonal = shadowMaterialVertical.clone();
14537 shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
14538 var fullScreenTri = new BufferGeometry();
14539 fullScreenTri.setAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
14540 var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
14542 this.enabled = false;
14543 this.autoUpdate = true;
14544 this.needsUpdate = false;
14545 this.type = PCFShadowMap;
14547 this.render = function (lights, scene, camera) {
14548 if (scope.enabled === false) return;
14549 if (scope.autoUpdate === false && scope.needsUpdate === false) return;
14550 if (lights.length === 0) return;
14552 var currentRenderTarget = _renderer.getRenderTarget();
14554 var activeCubeFace = _renderer.getActiveCubeFace();
14556 var activeMipmapLevel = _renderer.getActiveMipmapLevel();
14558 var _state = _renderer.state; // Set GL state for depth map.
14560 _state.setBlending(NoBlending);
14562 _state.buffers.color.setClear(1, 1, 1, 1);
14564 _state.buffers.depth.setTest(true);
14566 _state.setScissorTest(false); // render depth map
14569 for (var i = 0, il = lights.length; i < il; i++) {
14570 var light = lights[i];
14571 var shadow = light.shadow;
14573 if (shadow === undefined) {
14574 console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
14578 if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
14580 _shadowMapSize.copy(shadow.mapSize);
14582 var shadowFrameExtents = shadow.getFrameExtents();
14584 _shadowMapSize.multiply(shadowFrameExtents);
14586 _viewportSize.copy(shadow.mapSize);
14588 if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
14589 if (_shadowMapSize.x > maxTextureSize) {
14590 _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
14591 _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
14592 shadow.mapSize.x = _viewportSize.x;
14595 if (_shadowMapSize.y > maxTextureSize) {
14596 _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
14597 _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
14598 shadow.mapSize.y = _viewportSize.y;
14602 if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
14604 minFilter: LinearFilter,
14605 magFilter: LinearFilter,
14608 shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
14609 shadow.map.texture.name = light.name + ".shadowMap";
14610 shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
14611 shadow.camera.updateProjectionMatrix();
14614 if (shadow.map === null) {
14616 minFilter: NearestFilter,
14617 magFilter: NearestFilter,
14620 shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, _pars);
14621 shadow.map.texture.name = light.name + ".shadowMap";
14622 shadow.camera.updateProjectionMatrix();
14625 _renderer.setRenderTarget(shadow.map);
14629 var viewportCount = shadow.getViewportCount();
14631 for (var vp = 0; vp < viewportCount; vp++) {
14632 var viewport = shadow.getViewport(vp);
14634 _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
14636 _state.viewport(_viewport);
14638 shadow.updateMatrices(light, vp);
14639 _frustum = shadow.getFrustum();
14640 renderObject(scene, camera, shadow.camera, light, this.type);
14641 } // do blur pass for VSM
14644 if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
14645 VSMPass(shadow, camera);
14648 shadow.needsUpdate = false;
14651 scope.needsUpdate = false;
14653 _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
14656 function VSMPass(shadow, camera) {
14657 var geometry = _objects.update(fullScreenMesh); // vertical pass
14660 shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
14661 shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
14662 shadowMaterialVertical.uniforms.radius.value = shadow.radius;
14664 _renderer.setRenderTarget(shadow.mapPass);
14668 _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
14671 shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
14672 shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
14673 shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
14675 _renderer.setRenderTarget(shadow.map);
14679 _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
14682 function getDepthMaterialVariant(useMorphing, useSkinning, useInstancing) {
14683 var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
14684 var material = _depthMaterials[index];
14686 if (material === undefined) {
14687 material = new MeshDepthMaterial({
14688 depthPacking: RGBADepthPacking,
14689 morphTargets: useMorphing,
14690 skinning: useSkinning
14692 _depthMaterials[index] = material;
14698 function getDistanceMaterialVariant(useMorphing, useSkinning, useInstancing) {
14699 var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
14700 var material = _distanceMaterials[index];
14702 if (material === undefined) {
14703 material = new MeshDistanceMaterial({
14704 morphTargets: useMorphing,
14705 skinning: useSkinning
14707 _distanceMaterials[index] = material;
14713 function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
14715 var getMaterialVariant = getDepthMaterialVariant;
14716 var customMaterial = object.customDepthMaterial;
14718 if (light.isPointLight === true) {
14719 getMaterialVariant = getDistanceMaterialVariant;
14720 customMaterial = object.customDistanceMaterial;
14723 if (customMaterial === undefined) {
14724 var useMorphing = false;
14726 if (material.morphTargets === true) {
14727 useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
14730 var useSkinning = false;
14732 if (object.isSkinnedMesh === true) {
14733 if (material.skinning === true) {
14734 useSkinning = true;
14736 console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
14740 var useInstancing = object.isInstancedMesh === true;
14741 result = getMaterialVariant(useMorphing, useSkinning, useInstancing);
14743 result = customMaterial;
14746 if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
14747 // in this case we need a unique material instance reflecting the
14748 // appropriate state
14749 var keyA = result.uuid,
14750 keyB = material.uuid;
14751 var materialsForVariant = _materialCache[keyA];
14753 if (materialsForVariant === undefined) {
14754 materialsForVariant = {};
14755 _materialCache[keyA] = materialsForVariant;
14758 var cachedMaterial = materialsForVariant[keyB];
14760 if (cachedMaterial === undefined) {
14761 cachedMaterial = result.clone();
14762 materialsForVariant[keyB] = cachedMaterial;
14765 result = cachedMaterial;
14768 result.visible = material.visible;
14769 result.wireframe = material.wireframe;
14771 if (type === VSMShadowMap) {
14772 result.side = material.shadowSide !== null ? material.shadowSide : material.side;
14774 result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
14777 result.clipShadows = material.clipShadows;
14778 result.clippingPlanes = material.clippingPlanes;
14779 result.clipIntersection = material.clipIntersection;
14780 result.wireframeLinewidth = material.wireframeLinewidth;
14781 result.linewidth = material.linewidth;
14783 if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
14784 result.referencePosition.setFromMatrixPosition(light.matrixWorld);
14785 result.nearDistance = shadowCameraNear;
14786 result.farDistance = shadowCameraFar;
14792 function renderObject(object, camera, shadowCamera, light, type) {
14793 if (object.visible === false) return;
14794 var visible = object.layers.test(camera.layers);
14796 if (visible && (object.isMesh || object.isLine || object.isPoints)) {
14797 if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
14798 object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
14800 var geometry = _objects.update(object);
14802 var material = object.material;
14804 if (Array.isArray(material)) {
14805 var groups = geometry.groups;
14807 for (var k = 0, kl = groups.length; k < kl; k++) {
14808 var group = groups[k];
14809 var groupMaterial = material[group.materialIndex];
14811 if (groupMaterial && groupMaterial.visible) {
14812 var depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
14814 _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
14817 } else if (material.visible) {
14818 var _depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
14820 _renderer.renderBufferDirect(shadowCamera, null, geometry, _depthMaterial, object, null);
14825 var children = object.children;
14827 for (var i = 0, l = children.length; i < l; i++) {
14828 renderObject(children[i], camera, shadowCamera, light, type);
14833 function WebGLState(gl, extensions, capabilities) {
14834 var _equationToGL, _factorToGL;
14836 var isWebGL2 = capabilities.isWebGL2;
14838 function ColorBuffer() {
14839 var locked = false;
14840 var color = new Vector4();
14841 var currentColorMask = null;
14842 var currentColorClear = new Vector4(0, 0, 0, 0);
14844 setMask: function setMask(colorMask) {
14845 if (currentColorMask !== colorMask && !locked) {
14846 gl.colorMask(colorMask, colorMask, colorMask, colorMask);
14847 currentColorMask = colorMask;
14850 setLocked: function setLocked(lock) {
14853 setClear: function setClear(r, g, b, a, premultipliedAlpha) {
14854 if (premultipliedAlpha === true) {
14860 color.set(r, g, b, a);
14862 if (currentColorClear.equals(color) === false) {
14863 gl.clearColor(r, g, b, a);
14864 currentColorClear.copy(color);
14867 reset: function reset() {
14869 currentColorMask = null;
14870 currentColorClear.set(-1, 0, 0, 0); // set to invalid state
14875 function DepthBuffer() {
14876 var locked = false;
14877 var currentDepthMask = null;
14878 var currentDepthFunc = null;
14879 var currentDepthClear = null;
14881 setTest: function setTest(depthTest) {
14888 setMask: function setMask(depthMask) {
14889 if (currentDepthMask !== depthMask && !locked) {
14890 gl.depthMask(depthMask);
14891 currentDepthMask = depthMask;
14894 setFunc: function setFunc(depthFunc) {
14895 if (currentDepthFunc !== depthFunc) {
14897 switch (depthFunc) {
14910 case LessEqualDepth:
14918 case GreaterEqualDepth:
14926 case NotEqualDepth:
14937 currentDepthFunc = depthFunc;
14940 setLocked: function setLocked(lock) {
14943 setClear: function setClear(depth) {
14944 if (currentDepthClear !== depth) {
14945 gl.clearDepth(depth);
14946 currentDepthClear = depth;
14949 reset: function reset() {
14951 currentDepthMask = null;
14952 currentDepthFunc = null;
14953 currentDepthClear = null;
14958 function StencilBuffer() {
14959 var locked = false;
14960 var currentStencilMask = null;
14961 var currentStencilFunc = null;
14962 var currentStencilRef = null;
14963 var currentStencilFuncMask = null;
14964 var currentStencilFail = null;
14965 var currentStencilZFail = null;
14966 var currentStencilZPass = null;
14967 var currentStencilClear = null;
14969 setTest: function setTest(stencilTest) {
14978 setMask: function setMask(stencilMask) {
14979 if (currentStencilMask !== stencilMask && !locked) {
14980 gl.stencilMask(stencilMask);
14981 currentStencilMask = stencilMask;
14984 setFunc: function setFunc(stencilFunc, stencilRef, stencilMask) {
14985 if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
14986 gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
14987 currentStencilFunc = stencilFunc;
14988 currentStencilRef = stencilRef;
14989 currentStencilFuncMask = stencilMask;
14992 setOp: function setOp(stencilFail, stencilZFail, stencilZPass) {
14993 if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
14994 gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
14995 currentStencilFail = stencilFail;
14996 currentStencilZFail = stencilZFail;
14997 currentStencilZPass = stencilZPass;
15000 setLocked: function setLocked(lock) {
15003 setClear: function setClear(stencil) {
15004 if (currentStencilClear !== stencil) {
15005 gl.clearStencil(stencil);
15006 currentStencilClear = stencil;
15009 reset: function reset() {
15011 currentStencilMask = null;
15012 currentStencilFunc = null;
15013 currentStencilRef = null;
15014 currentStencilFuncMask = null;
15015 currentStencilFail = null;
15016 currentStencilZFail = null;
15017 currentStencilZPass = null;
15018 currentStencilClear = null;
15024 var colorBuffer = new ColorBuffer();
15025 var depthBuffer = new DepthBuffer();
15026 var stencilBuffer = new StencilBuffer();
15027 var enabledCapabilities = {};
15028 var currentProgram = null;
15029 var currentBlendingEnabled = null;
15030 var currentBlending = null;
15031 var currentBlendEquation = null;
15032 var currentBlendSrc = null;
15033 var currentBlendDst = null;
15034 var currentBlendEquationAlpha = null;
15035 var currentBlendSrcAlpha = null;
15036 var currentBlendDstAlpha = null;
15037 var currentPremultipledAlpha = false;
15038 var currentFlipSided = null;
15039 var currentCullFace = null;
15040 var currentLineWidth = null;
15041 var currentPolygonOffsetFactor = null;
15042 var currentPolygonOffsetUnits = null;
15043 var maxTextures = gl.getParameter(35661);
15044 var lineWidthAvailable = false;
15046 var glVersion = gl.getParameter(7938);
15048 if (glVersion.indexOf('WebGL') !== -1) {
15049 version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
15050 lineWidthAvailable = version >= 1.0;
15051 } else if (glVersion.indexOf('OpenGL ES') !== -1) {
15052 version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
15053 lineWidthAvailable = version >= 2.0;
15056 var currentTextureSlot = null;
15057 var currentBoundTextures = {};
15058 var currentScissor = new Vector4();
15059 var currentViewport = new Vector4();
15061 function createTexture(type, target, count) {
15062 var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
15064 var texture = gl.createTexture();
15065 gl.bindTexture(type, texture);
15066 gl.texParameteri(type, 10241, 9728);
15067 gl.texParameteri(type, 10240, 9728);
15069 for (var i = 0; i < count; i++) {
15070 gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
15076 var emptyTextures = {};
15077 emptyTextures[3553] = createTexture(3553, 3553, 1);
15078 emptyTextures[34067] = createTexture(34067, 34069, 6); // init
15080 colorBuffer.setClear(0, 0, 0, 1);
15081 depthBuffer.setClear(1);
15082 stencilBuffer.setClear(0);
15084 depthBuffer.setFunc(LessEqualDepth);
15085 setFlipSided(false);
15086 setCullFace(CullFaceBack);
15088 setBlending(NoBlending); //
15090 function enable(id) {
15091 if (enabledCapabilities[id] !== true) {
15093 enabledCapabilities[id] = true;
15097 function disable(id) {
15098 if (enabledCapabilities[id] !== false) {
15100 enabledCapabilities[id] = false;
15104 function useProgram(program) {
15105 if (currentProgram !== program) {
15106 gl.useProgram(program);
15107 currentProgram = program;
15114 var equationToGL = (_equationToGL = {}, _equationToGL[AddEquation] = 32774, _equationToGL[SubtractEquation] = 32778, _equationToGL[ReverseSubtractEquation] = 32779, _equationToGL);
15117 equationToGL[MinEquation] = 32775;
15118 equationToGL[MaxEquation] = 32776;
15120 var extension = extensions.get('EXT_blend_minmax');
15122 if (extension !== null) {
15123 equationToGL[MinEquation] = extension.MIN_EXT;
15124 equationToGL[MaxEquation] = extension.MAX_EXT;
15128 var factorToGL = (_factorToGL = {}, _factorToGL[ZeroFactor] = 0, _factorToGL[OneFactor] = 1, _factorToGL[SrcColorFactor] = 768, _factorToGL[SrcAlphaFactor] = 770, _factorToGL[SrcAlphaSaturateFactor] = 776, _factorToGL[DstColorFactor] = 774, _factorToGL[DstAlphaFactor] = 772, _factorToGL[OneMinusSrcColorFactor] = 769, _factorToGL[OneMinusSrcAlphaFactor] = 771, _factorToGL[OneMinusDstColorFactor] = 775, _factorToGL[OneMinusDstAlphaFactor] = 773, _factorToGL);
15130 function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
15131 if (blending === NoBlending) {
15132 if (currentBlendingEnabled) {
15134 currentBlendingEnabled = false;
15140 if (!currentBlendingEnabled) {
15142 currentBlendingEnabled = true;
15145 if (blending !== CustomBlending) {
15146 if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
15147 if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
15148 gl.blendEquation(32774);
15149 currentBlendEquation = AddEquation;
15150 currentBlendEquationAlpha = AddEquation;
15153 if (premultipliedAlpha) {
15154 switch (blending) {
15155 case NormalBlending:
15156 gl.blendFuncSeparate(1, 771, 1, 771);
15159 case AdditiveBlending:
15160 gl.blendFunc(1, 1);
15163 case SubtractiveBlending:
15164 gl.blendFuncSeparate(0, 0, 769, 771);
15167 case MultiplyBlending:
15168 gl.blendFuncSeparate(0, 768, 0, 770);
15172 console.error('THREE.WebGLState: Invalid blending: ', blending);
15176 switch (blending) {
15177 case NormalBlending:
15178 gl.blendFuncSeparate(770, 771, 1, 771);
15181 case AdditiveBlending:
15182 gl.blendFunc(770, 1);
15185 case SubtractiveBlending:
15186 gl.blendFunc(0, 769);
15189 case MultiplyBlending:
15190 gl.blendFunc(0, 768);
15194 console.error('THREE.WebGLState: Invalid blending: ', blending);
15199 currentBlendSrc = null;
15200 currentBlendDst = null;
15201 currentBlendSrcAlpha = null;
15202 currentBlendDstAlpha = null;
15203 currentBlending = blending;
15204 currentPremultipledAlpha = premultipliedAlpha;
15208 } // custom blending
15211 blendEquationAlpha = blendEquationAlpha || blendEquation;
15212 blendSrcAlpha = blendSrcAlpha || blendSrc;
15213 blendDstAlpha = blendDstAlpha || blendDst;
15215 if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
15216 gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
15217 currentBlendEquation = blendEquation;
15218 currentBlendEquationAlpha = blendEquationAlpha;
15221 if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
15222 gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
15223 currentBlendSrc = blendSrc;
15224 currentBlendDst = blendDst;
15225 currentBlendSrcAlpha = blendSrcAlpha;
15226 currentBlendDstAlpha = blendDstAlpha;
15229 currentBlending = blending;
15230 currentPremultipledAlpha = null;
15233 function setMaterial(material, frontFaceCW) {
15234 material.side === DoubleSide ? disable(2884) : enable(2884);
15235 var flipSided = material.side === BackSide;
15236 if (frontFaceCW) flipSided = !flipSided;
15237 setFlipSided(flipSided);
15238 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);
15239 depthBuffer.setFunc(material.depthFunc);
15240 depthBuffer.setTest(material.depthTest);
15241 depthBuffer.setMask(material.depthWrite);
15242 colorBuffer.setMask(material.colorWrite);
15243 var stencilWrite = material.stencilWrite;
15244 stencilBuffer.setTest(stencilWrite);
15246 if (stencilWrite) {
15247 stencilBuffer.setMask(material.stencilWriteMask);
15248 stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
15249 stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
15252 setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
15256 function setFlipSided(flipSided) {
15257 if (currentFlipSided !== flipSided) {
15259 gl.frontFace(2304);
15261 gl.frontFace(2305);
15264 currentFlipSided = flipSided;
15268 function setCullFace(cullFace) {
15269 if (cullFace !== CullFaceNone) {
15272 if (cullFace !== currentCullFace) {
15273 if (cullFace === CullFaceBack) {
15275 } else if (cullFace === CullFaceFront) {
15285 currentCullFace = cullFace;
15288 function setLineWidth(width) {
15289 if (width !== currentLineWidth) {
15290 if (lineWidthAvailable) gl.lineWidth(width);
15291 currentLineWidth = width;
15295 function setPolygonOffset(polygonOffset, factor, units) {
15296 if (polygonOffset) {
15299 if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
15300 gl.polygonOffset(factor, units);
15301 currentPolygonOffsetFactor = factor;
15302 currentPolygonOffsetUnits = units;
15309 function setScissorTest(scissorTest) {
15318 function activeTexture(webglSlot) {
15319 if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
15321 if (currentTextureSlot !== webglSlot) {
15322 gl.activeTexture(webglSlot);
15323 currentTextureSlot = webglSlot;
15327 function bindTexture(webglType, webglTexture) {
15328 if (currentTextureSlot === null) {
15332 var boundTexture = currentBoundTextures[currentTextureSlot];
15334 if (boundTexture === undefined) {
15339 currentBoundTextures[currentTextureSlot] = boundTexture;
15342 if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
15343 gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
15344 boundTexture.type = webglType;
15345 boundTexture.texture = webglTexture;
15349 function unbindTexture() {
15350 var boundTexture = currentBoundTextures[currentTextureSlot];
15352 if (boundTexture !== undefined && boundTexture.type !== undefined) {
15353 gl.bindTexture(boundTexture.type, null);
15354 boundTexture.type = undefined;
15355 boundTexture.texture = undefined;
15359 function compressedTexImage2D() {
15361 gl.compressedTexImage2D.apply(gl, arguments);
15363 console.error('THREE.WebGLState:', error);
15367 function texImage2D() {
15369 gl.texImage2D.apply(gl, arguments);
15371 console.error('THREE.WebGLState:', error);
15375 function texImage3D() {
15377 gl.texImage3D.apply(gl, arguments);
15379 console.error('THREE.WebGLState:', error);
15384 function scissor(scissor) {
15385 if (currentScissor.equals(scissor) === false) {
15386 gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
15387 currentScissor.copy(scissor);
15391 function viewport(viewport) {
15392 if (currentViewport.equals(viewport) === false) {
15393 gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
15394 currentViewport.copy(viewport);
15400 enabledCapabilities = {};
15401 currentTextureSlot = null;
15402 currentBoundTextures = {};
15403 currentProgram = null;
15404 currentBlendingEnabled = null;
15405 currentBlending = null;
15406 currentBlendEquation = null;
15407 currentBlendSrc = null;
15408 currentBlendDst = null;
15409 currentBlendEquationAlpha = null;
15410 currentBlendSrcAlpha = null;
15411 currentBlendDstAlpha = null;
15412 currentPremultipledAlpha = false;
15413 currentFlipSided = null;
15414 currentCullFace = null;
15415 currentLineWidth = null;
15416 currentPolygonOffsetFactor = null;
15417 currentPolygonOffsetUnits = null;
15418 colorBuffer.reset();
15419 depthBuffer.reset();
15420 stencilBuffer.reset();
15425 color: colorBuffer,
15426 depth: depthBuffer,
15427 stencil: stencilBuffer
15431 useProgram: useProgram,
15432 setBlending: setBlending,
15433 setMaterial: setMaterial,
15434 setFlipSided: setFlipSided,
15435 setCullFace: setCullFace,
15436 setLineWidth: setLineWidth,
15437 setPolygonOffset: setPolygonOffset,
15438 setScissorTest: setScissorTest,
15439 activeTexture: activeTexture,
15440 bindTexture: bindTexture,
15441 unbindTexture: unbindTexture,
15442 compressedTexImage2D: compressedTexImage2D,
15443 texImage2D: texImage2D,
15444 texImage3D: texImage3D,
15446 viewport: viewport,
15451 function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
15452 var _wrappingToGL, _filterToGL;
15454 var isWebGL2 = capabilities.isWebGL2;
15455 var maxTextures = capabilities.maxTextures;
15456 var maxCubemapSize = capabilities.maxCubemapSize;
15457 var maxTextureSize = capabilities.maxTextureSize;
15458 var maxSamples = capabilities.maxSamples;
15460 var _videoTextures = new WeakMap();
15462 var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
15463 // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
15464 // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
15467 var useOffscreenCanvas = false;
15470 useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
15471 } catch (err) {// Ignore any errors
15474 function createCanvas(width, height) {
15475 // Use OffscreenCanvas when available. Specially needed in web workers
15476 return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
15479 function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
15480 var scale = 1; // handle case if texture exceeds max size
15482 if (image.width > maxSize || image.height > maxSize) {
15483 scale = maxSize / Math.max(image.width, image.height);
15484 } // only perform resize if necessary
15487 if (scale < 1 || needsPowerOfTwo === true) {
15488 // only perform resize for certain image types
15489 if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
15490 var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
15491 var width = floor(scale * image.width);
15492 var height = floor(scale * image.height);
15493 if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
15495 var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
15496 canvas.width = width;
15497 canvas.height = height;
15498 var context = canvas.getContext('2d');
15499 context.drawImage(image, 0, 0, width, height);
15500 console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
15503 if ('data' in image) {
15504 console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
15514 function isPowerOfTwo(image) {
15515 return MathUtils.isPowerOfTwo(image.width) && MathUtils.isPowerOfTwo(image.height);
15518 function textureNeedsPowerOfTwo(texture) {
15519 if (isWebGL2) return false;
15520 return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
15523 function textureNeedsGenerateMipmaps(texture, supportsMips) {
15524 return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
15527 function generateMipmap(target, texture, width, height) {
15528 _gl.generateMipmap(target);
15530 var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
15532 textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
15535 function getInternalFormat(internalFormatName, glFormat, glType) {
15536 if (isWebGL2 === false) return glFormat;
15538 if (internalFormatName !== null) {
15539 if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
15540 console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
15543 var internalFormat = glFormat;
15545 if (glFormat === 6403) {
15546 if (glType === 5126) internalFormat = 33326;
15547 if (glType === 5131) internalFormat = 33325;
15548 if (glType === 5121) internalFormat = 33321;
15551 if (glFormat === 6407) {
15552 if (glType === 5126) internalFormat = 34837;
15553 if (glType === 5131) internalFormat = 34843;
15554 if (glType === 5121) internalFormat = 32849;
15557 if (glFormat === 6408) {
15558 if (glType === 5126) internalFormat = 34836;
15559 if (glType === 5131) internalFormat = 34842;
15560 if (glType === 5121) internalFormat = 32856;
15563 if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
15564 extensions.get('EXT_color_buffer_float');
15567 return internalFormat;
15568 } // Fallback filters for non-power-of-2 textures
15571 function filterFallback(f) {
15572 if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
15580 function onTextureDispose(event) {
15581 var texture = event.target;
15582 texture.removeEventListener('dispose', onTextureDispose);
15583 deallocateTexture(texture);
15585 if (texture.isVideoTexture) {
15586 _videoTextures.delete(texture);
15589 info.memory.textures--;
15592 function onRenderTargetDispose(event) {
15593 var renderTarget = event.target;
15594 renderTarget.removeEventListener('dispose', onRenderTargetDispose);
15595 deallocateRenderTarget(renderTarget);
15596 info.memory.textures--;
15600 function deallocateTexture(texture) {
15601 var textureProperties = properties.get(texture);
15602 if (textureProperties.__webglInit === undefined) return;
15604 _gl.deleteTexture(textureProperties.__webglTexture);
15606 properties.remove(texture);
15609 function deallocateRenderTarget(renderTarget) {
15610 var renderTargetProperties = properties.get(renderTarget);
15611 var textureProperties = properties.get(renderTarget.texture);
15612 if (!renderTarget) return;
15614 if (textureProperties.__webglTexture !== undefined) {
15615 _gl.deleteTexture(textureProperties.__webglTexture);
15618 if (renderTarget.depthTexture) {
15619 renderTarget.depthTexture.dispose();
15622 if (renderTarget.isWebGLCubeRenderTarget) {
15623 for (var i = 0; i < 6; i++) {
15624 _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
15626 if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
15629 _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
15631 if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
15632 if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
15633 if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
15634 if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
15637 properties.remove(renderTarget.texture);
15638 properties.remove(renderTarget);
15642 var textureUnits = 0;
15644 function resetTextureUnits() {
15648 function allocateTextureUnit() {
15649 var textureUnit = textureUnits;
15651 if (textureUnit >= maxTextures) {
15652 console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
15656 return textureUnit;
15660 function setTexture2D(texture, slot) {
15661 var textureProperties = properties.get(texture);
15662 if (texture.isVideoTexture) updateVideoTexture(texture);
15664 if (texture.version > 0 && textureProperties.__version !== texture.version) {
15665 var image = texture.image;
15667 if (image === undefined) {
15668 console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
15669 } else if (image.complete === false) {
15670 console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
15672 uploadTexture(textureProperties, texture, slot);
15677 state.activeTexture(33984 + slot);
15678 state.bindTexture(3553, textureProperties.__webglTexture);
15681 function setTexture2DArray(texture, slot) {
15682 var textureProperties = properties.get(texture);
15684 if (texture.version > 0 && textureProperties.__version !== texture.version) {
15685 uploadTexture(textureProperties, texture, slot);
15689 state.activeTexture(33984 + slot);
15690 state.bindTexture(35866, textureProperties.__webglTexture);
15693 function setTexture3D(texture, slot) {
15694 var textureProperties = properties.get(texture);
15696 if (texture.version > 0 && textureProperties.__version !== texture.version) {
15697 uploadTexture(textureProperties, texture, slot);
15701 state.activeTexture(33984 + slot);
15702 state.bindTexture(32879, textureProperties.__webglTexture);
15705 function setTextureCube(texture, slot) {
15706 var textureProperties = properties.get(texture);
15708 if (texture.version > 0 && textureProperties.__version !== texture.version) {
15709 uploadCubeTexture(textureProperties, texture, slot);
15713 state.activeTexture(33984 + slot);
15714 state.bindTexture(34067, textureProperties.__webglTexture);
15717 var wrappingToGL = (_wrappingToGL = {}, _wrappingToGL[RepeatWrapping] = 10497, _wrappingToGL[ClampToEdgeWrapping] = 33071, _wrappingToGL[MirroredRepeatWrapping] = 33648, _wrappingToGL);
15718 var filterToGL = (_filterToGL = {}, _filterToGL[NearestFilter] = 9728, _filterToGL[NearestMipmapNearestFilter] = 9984, _filterToGL[NearestMipmapLinearFilter] = 9986, _filterToGL[LinearFilter] = 9729, _filterToGL[LinearMipmapNearestFilter] = 9985, _filterToGL[LinearMipmapLinearFilter] = 9987, _filterToGL);
15720 function setTextureParameters(textureType, texture, supportsMips) {
15721 if (supportsMips) {
15722 _gl.texParameteri(textureType, 10242, wrappingToGL[texture.wrapS]);
15724 _gl.texParameteri(textureType, 10243, wrappingToGL[texture.wrapT]);
15726 if (textureType === 32879 || textureType === 35866) {
15727 _gl.texParameteri(textureType, 32882, wrappingToGL[texture.wrapR]);
15730 _gl.texParameteri(textureType, 10240, filterToGL[texture.magFilter]);
15732 _gl.texParameteri(textureType, 10241, filterToGL[texture.minFilter]);
15734 _gl.texParameteri(textureType, 10242, 33071);
15736 _gl.texParameteri(textureType, 10243, 33071);
15738 if (textureType === 32879 || textureType === 35866) {
15739 _gl.texParameteri(textureType, 32882, 33071);
15742 if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
15743 console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
15746 _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
15748 _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
15750 if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
15751 console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
15755 var extension = extensions.get('EXT_texture_filter_anisotropic');
15758 if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
15759 if (texture.type === HalfFloatType && (isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
15761 if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
15762 _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
15764 properties.get(texture).__currentAnisotropy = texture.anisotropy;
15769 function initTexture(textureProperties, texture) {
15770 if (textureProperties.__webglInit === undefined) {
15771 textureProperties.__webglInit = true;
15772 texture.addEventListener('dispose', onTextureDispose);
15773 textureProperties.__webglTexture = _gl.createTexture();
15774 info.memory.textures++;
15778 function uploadTexture(textureProperties, texture, slot) {
15779 var textureType = 3553;
15780 if (texture.isDataTexture2DArray) textureType = 35866;
15781 if (texture.isDataTexture3D) textureType = 32879;
15782 initTexture(textureProperties, texture);
15783 state.activeTexture(33984 + slot);
15784 state.bindTexture(textureType, textureProperties.__webglTexture);
15786 _gl.pixelStorei(37440, texture.flipY);
15788 _gl.pixelStorei(37441, texture.premultiplyAlpha);
15790 _gl.pixelStorei(3317, texture.unpackAlignment);
15792 var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
15793 var image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
15794 var supportsMips = isPowerOfTwo(image) || isWebGL2,
15795 glFormat = utils.convert(texture.format);
15796 var glType = utils.convert(texture.type),
15797 glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
15798 setTextureParameters(textureType, texture, supportsMips);
15800 var mipmaps = texture.mipmaps;
15802 if (texture.isDepthTexture) {
15803 // populate depth texture with dummy data
15804 glInternalFormat = 6402;
15807 if (texture.type === FloatType) {
15808 glInternalFormat = 36012;
15809 } else if (texture.type === UnsignedIntType) {
15810 glInternalFormat = 33190;
15811 } else if (texture.type === UnsignedInt248Type) {
15812 glInternalFormat = 35056;
15814 glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
15817 if (texture.type === FloatType) {
15818 console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
15820 } // validation checks for WebGL 1
15823 if (texture.format === DepthFormat && glInternalFormat === 6402) {
15824 // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
15825 // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
15826 // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
15827 if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
15828 console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
15829 texture.type = UnsignedShortType;
15830 glType = utils.convert(texture.type);
15834 if (texture.format === DepthStencilFormat && glInternalFormat === 6402) {
15835 // Depth stencil textures need the DEPTH_STENCIL internal format
15836 // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
15837 glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
15838 // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
15839 // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
15841 if (texture.type !== UnsignedInt248Type) {
15842 console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
15843 texture.type = UnsignedInt248Type;
15844 glType = utils.convert(texture.type);
15849 state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
15850 } else if (texture.isDataTexture) {
15851 // use manually created mipmaps if available
15852 // if there are no manual mipmaps
15853 // set 0 level mipmap and then use GL to generate other mipmap levels
15854 if (mipmaps.length > 0 && supportsMips) {
15855 for (var i = 0, il = mipmaps.length; i < il; i++) {
15856 mipmap = mipmaps[i];
15857 state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
15860 texture.generateMipmaps = false;
15861 textureProperties.__maxMipLevel = mipmaps.length - 1;
15863 state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
15864 textureProperties.__maxMipLevel = 0;
15866 } else if (texture.isCompressedTexture) {
15867 for (var _i = 0, _il = mipmaps.length; _i < _il; _i++) {
15868 mipmap = mipmaps[_i];
15870 if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
15871 if (glFormat !== null) {
15872 state.compressedTexImage2D(3553, _i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
15874 console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
15877 state.texImage2D(3553, _i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
15881 textureProperties.__maxMipLevel = mipmaps.length - 1;
15882 } else if (texture.isDataTexture2DArray) {
15883 state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
15884 textureProperties.__maxMipLevel = 0;
15885 } else if (texture.isDataTexture3D) {
15886 state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
15887 textureProperties.__maxMipLevel = 0;
15889 // regular Texture (image, video, canvas)
15890 // use manually created mipmaps if available
15891 // if there are no manual mipmaps
15892 // set 0 level mipmap and then use GL to generate other mipmap levels
15893 if (mipmaps.length > 0 && supportsMips) {
15894 for (var _i2 = 0, _il2 = mipmaps.length; _i2 < _il2; _i2++) {
15895 mipmap = mipmaps[_i2];
15896 state.texImage2D(3553, _i2, glInternalFormat, glFormat, glType, mipmap);
15899 texture.generateMipmaps = false;
15900 textureProperties.__maxMipLevel = mipmaps.length - 1;
15902 state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
15903 textureProperties.__maxMipLevel = 0;
15907 if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
15908 generateMipmap(textureType, texture, image.width, image.height);
15911 textureProperties.__version = texture.version;
15912 if (texture.onUpdate) texture.onUpdate(texture);
15915 function uploadCubeTexture(textureProperties, texture, slot) {
15916 if (texture.image.length !== 6) return;
15917 initTexture(textureProperties, texture);
15918 state.activeTexture(33984 + slot);
15919 state.bindTexture(34067, textureProperties.__webglTexture);
15921 _gl.pixelStorei(37440, texture.flipY);
15923 var isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
15924 var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
15925 var cubeImage = [];
15927 for (var i = 0; i < 6; i++) {
15928 if (!isCompressed && !isDataTexture) {
15929 cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
15931 cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
15935 var image = cubeImage[0],
15936 supportsMips = isPowerOfTwo(image) || isWebGL2,
15937 glFormat = utils.convert(texture.format),
15938 glType = utils.convert(texture.type),
15939 glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
15940 setTextureParameters(34067, texture, supportsMips);
15943 if (isCompressed) {
15944 for (var _i3 = 0; _i3 < 6; _i3++) {
15945 mipmaps = cubeImage[_i3].mipmaps;
15947 for (var j = 0; j < mipmaps.length; j++) {
15948 var mipmap = mipmaps[j];
15950 if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
15951 if (glFormat !== null) {
15952 state.compressedTexImage2D(34069 + _i3, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
15954 console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
15957 state.texImage2D(34069 + _i3, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
15962 textureProperties.__maxMipLevel = mipmaps.length - 1;
15964 mipmaps = texture.mipmaps;
15966 for (var _i4 = 0; _i4 < 6; _i4++) {
15967 if (isDataTexture) {
15968 state.texImage2D(34069 + _i4, 0, glInternalFormat, cubeImage[_i4].width, cubeImage[_i4].height, 0, glFormat, glType, cubeImage[_i4].data);
15970 for (var _j = 0; _j < mipmaps.length; _j++) {
15971 var _mipmap = mipmaps[_j];
15972 var mipmapImage = _mipmap.image[_i4].image;
15973 state.texImage2D(34069 + _i4, _j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
15976 state.texImage2D(34069 + _i4, 0, glInternalFormat, glFormat, glType, cubeImage[_i4]);
15978 for (var _j2 = 0; _j2 < mipmaps.length; _j2++) {
15979 var _mipmap2 = mipmaps[_j2];
15980 state.texImage2D(34069 + _i4, _j2 + 1, glInternalFormat, glFormat, glType, _mipmap2.image[_i4]);
15985 textureProperties.__maxMipLevel = mipmaps.length;
15988 if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
15989 // We assume images for cube map have the same size.
15990 generateMipmap(34067, texture, image.width, image.height);
15993 textureProperties.__version = texture.version;
15994 if (texture.onUpdate) texture.onUpdate(texture);
15995 } // Render targets
15996 // Setup storage for target texture and bind it to correct framebuffer
15999 function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
16000 var glFormat = utils.convert(renderTarget.texture.format);
16001 var glType = utils.convert(renderTarget.texture.type);
16002 var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
16003 state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
16005 _gl.bindFramebuffer(36160, framebuffer);
16007 _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
16009 _gl.bindFramebuffer(36160, null);
16010 } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
16013 function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
16014 _gl.bindRenderbuffer(36161, renderbuffer);
16016 if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
16017 var glInternalFormat = 33189;
16019 if (isMultisample) {
16020 var depthTexture = renderTarget.depthTexture;
16022 if (depthTexture && depthTexture.isDepthTexture) {
16023 if (depthTexture.type === FloatType) {
16024 glInternalFormat = 36012;
16025 } else if (depthTexture.type === UnsignedIntType) {
16026 glInternalFormat = 33190;
16030 var samples = getRenderTargetSamples(renderTarget);
16032 _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
16034 _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
16037 _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
16038 } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
16039 if (isMultisample) {
16040 var _samples = getRenderTargetSamples(renderTarget);
16042 _gl.renderbufferStorageMultisample(36161, _samples, 35056, renderTarget.width, renderTarget.height);
16044 _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
16047 _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
16049 var glFormat = utils.convert(renderTarget.texture.format);
16050 var glType = utils.convert(renderTarget.texture.type);
16052 var _glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
16054 if (isMultisample) {
16055 var _samples2 = getRenderTargetSamples(renderTarget);
16057 _gl.renderbufferStorageMultisample(36161, _samples2, _glInternalFormat, renderTarget.width, renderTarget.height);
16059 _gl.renderbufferStorage(36161, _glInternalFormat, renderTarget.width, renderTarget.height);
16063 _gl.bindRenderbuffer(36161, null);
16064 } // Setup resources for a Depth Texture for a FBO (needs an extension)
16067 function setupDepthTexture(framebuffer, renderTarget) {
16068 var isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
16069 if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
16071 _gl.bindFramebuffer(36160, framebuffer);
16073 if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
16074 throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
16075 } // upload an empty depth texture with framebuffer size
16078 if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
16079 renderTarget.depthTexture.image.width = renderTarget.width;
16080 renderTarget.depthTexture.image.height = renderTarget.height;
16081 renderTarget.depthTexture.needsUpdate = true;
16084 setTexture2D(renderTarget.depthTexture, 0);
16086 var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
16088 if (renderTarget.depthTexture.format === DepthFormat) {
16089 _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
16090 } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
16091 _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
16093 throw new Error('Unknown depthTexture format');
16095 } // Setup GL resources for a non-texture depth buffer
16098 function setupDepthRenderbuffer(renderTarget) {
16099 var renderTargetProperties = properties.get(renderTarget);
16100 var isCube = renderTarget.isWebGLCubeRenderTarget === true;
16102 if (renderTarget.depthTexture) {
16103 if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
16104 setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
16107 renderTargetProperties.__webglDepthbuffer = [];
16109 for (var i = 0; i < 6; i++) {
16110 _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
16112 renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
16113 setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
16116 _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
16118 renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
16119 setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
16123 _gl.bindFramebuffer(36160, null);
16124 } // Set up GL resources for the render target
16127 function setupRenderTarget(renderTarget) {
16128 var renderTargetProperties = properties.get(renderTarget);
16129 var textureProperties = properties.get(renderTarget.texture);
16130 renderTarget.addEventListener('dispose', onRenderTargetDispose);
16131 textureProperties.__webglTexture = _gl.createTexture();
16132 info.memory.textures++;
16133 var isCube = renderTarget.isWebGLCubeRenderTarget === true;
16134 var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
16135 var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
16137 if (isWebGL2 && renderTarget.texture.format === RGBFormat && (renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType)) {
16138 renderTarget.texture.format = RGBAFormat;
16139 console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
16140 } // Setup framebuffer
16144 renderTargetProperties.__webglFramebuffer = [];
16146 for (var i = 0; i < 6; i++) {
16147 renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
16150 renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
16152 if (isMultisample) {
16154 renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
16155 renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
16157 _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
16159 var glFormat = utils.convert(renderTarget.texture.format);
16160 var glType = utils.convert(renderTarget.texture.type);
16161 var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
16162 var samples = getRenderTargetSamples(renderTarget);
16164 _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
16166 _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
16168 _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
16170 _gl.bindRenderbuffer(36161, null);
16172 if (renderTarget.depthBuffer) {
16173 renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
16174 setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
16177 _gl.bindFramebuffer(36160, null);
16179 console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
16182 } // Setup color buffer
16186 state.bindTexture(34067, textureProperties.__webglTexture);
16187 setTextureParameters(34067, renderTarget.texture, supportsMips);
16189 for (var _i5 = 0; _i5 < 6; _i5++) {
16190 setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[_i5], renderTarget, 36064, 34069 + _i5);
16193 if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
16194 generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
16197 state.bindTexture(34067, null);
16199 state.bindTexture(3553, textureProperties.__webglTexture);
16200 setTextureParameters(3553, renderTarget.texture, supportsMips);
16201 setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
16203 if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
16204 generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
16207 state.bindTexture(3553, null);
16208 } // Setup depth and stencil buffers
16211 if (renderTarget.depthBuffer) {
16212 setupDepthRenderbuffer(renderTarget);
16216 function updateRenderTargetMipmap(renderTarget) {
16217 var texture = renderTarget.texture;
16218 var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2;
16220 if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
16221 var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
16223 var webglTexture = properties.get(texture).__webglTexture;
16225 state.bindTexture(target, webglTexture);
16226 generateMipmap(target, texture, renderTarget.width, renderTarget.height);
16227 state.bindTexture(target, null);
16231 function updateMultisampleRenderTarget(renderTarget) {
16232 if (renderTarget.isWebGLMultisampleRenderTarget) {
16234 var renderTargetProperties = properties.get(renderTarget);
16236 _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
16238 _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
16240 var width = renderTarget.width;
16241 var height = renderTarget.height;
16243 if (renderTarget.depthBuffer) mask |= 256;
16244 if (renderTarget.stencilBuffer) mask |= 1024;
16246 _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
16248 _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); // see #18905
16251 console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
16256 function getRenderTargetSamples(renderTarget) {
16257 return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
16260 function updateVideoTexture(texture) {
16261 var frame = info.render.frame; // Check the last frame we updated the VideoTexture
16263 if (_videoTextures.get(texture) !== frame) {
16264 _videoTextures.set(texture, frame);
16268 } // backwards compatibility
16271 var warnedTexture2D = false;
16272 var warnedTextureCube = false;
16274 function safeSetTexture2D(texture, slot) {
16275 if (texture && texture.isWebGLRenderTarget) {
16276 if (warnedTexture2D === false) {
16277 console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
16278 warnedTexture2D = true;
16281 texture = texture.texture;
16284 setTexture2D(texture, slot);
16287 function safeSetTextureCube(texture, slot) {
16288 if (texture && texture.isWebGLCubeRenderTarget) {
16289 if (warnedTextureCube === false) {
16290 console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
16291 warnedTextureCube = true;
16294 texture = texture.texture;
16297 setTextureCube(texture, slot);
16301 this.allocateTextureUnit = allocateTextureUnit;
16302 this.resetTextureUnits = resetTextureUnits;
16303 this.setTexture2D = setTexture2D;
16304 this.setTexture2DArray = setTexture2DArray;
16305 this.setTexture3D = setTexture3D;
16306 this.setTextureCube = setTextureCube;
16307 this.setupRenderTarget = setupRenderTarget;
16308 this.updateRenderTargetMipmap = updateRenderTargetMipmap;
16309 this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
16310 this.safeSetTexture2D = safeSetTexture2D;
16311 this.safeSetTextureCube = safeSetTextureCube;
16314 function WebGLUtils(gl, extensions, capabilities) {
16315 var isWebGL2 = capabilities.isWebGL2;
16317 function convert(p) {
16319 if (p === UnsignedByteType) return 5121;
16320 if (p === UnsignedShort4444Type) return 32819;
16321 if (p === UnsignedShort5551Type) return 32820;
16322 if (p === UnsignedShort565Type) return 33635;
16323 if (p === ByteType) return 5120;
16324 if (p === ShortType) return 5122;
16325 if (p === UnsignedShortType) return 5123;
16326 if (p === IntType) return 5124;
16327 if (p === UnsignedIntType) return 5125;
16328 if (p === FloatType) return 5126;
16330 if (p === HalfFloatType) {
16331 if (isWebGL2) return 5131;
16332 extension = extensions.get('OES_texture_half_float');
16334 if (extension !== null) {
16335 return extension.HALF_FLOAT_OES;
16341 if (p === AlphaFormat) return 6406;
16342 if (p === RGBFormat) return 6407;
16343 if (p === RGBAFormat) return 6408;
16344 if (p === LuminanceFormat) return 6409;
16345 if (p === LuminanceAlphaFormat) return 6410;
16346 if (p === DepthFormat) return 6402;
16347 if (p === DepthStencilFormat) return 34041;
16348 if (p === RedFormat) return 6403; // WebGL2 formats.
16350 if (p === RedIntegerFormat) return 36244;
16351 if (p === RGFormat) return 33319;
16352 if (p === RGIntegerFormat) return 33320;
16353 if (p === RGBIntegerFormat) return 36248;
16354 if (p === RGBAIntegerFormat) return 36249;
16356 if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
16357 extension = extensions.get('WEBGL_compressed_texture_s3tc');
16359 if (extension !== null) {
16360 if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
16361 if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
16362 if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
16363 if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
16369 if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
16370 extension = extensions.get('WEBGL_compressed_texture_pvrtc');
16372 if (extension !== null) {
16373 if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
16374 if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
16375 if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
16376 if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
16382 if (p === RGB_ETC1_Format) {
16383 extension = extensions.get('WEBGL_compressed_texture_etc1');
16385 if (extension !== null) {
16386 return extension.COMPRESSED_RGB_ETC1_WEBGL;
16392 if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
16393 extension = extensions.get('WEBGL_compressed_texture_etc');
16395 if (extension !== null) {
16396 if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
16397 if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
16401 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) {
16402 extension = extensions.get('WEBGL_compressed_texture_astc');
16404 if (extension !== null) {
16412 if (p === RGBA_BPTC_Format) {
16413 extension = extensions.get('EXT_texture_compression_bptc');
16415 if (extension !== null) {
16423 if (p === UnsignedInt248Type) {
16424 if (isWebGL2) return 34042;
16425 extension = extensions.get('WEBGL_depth_texture');
16427 if (extension !== null) {
16428 return extension.UNSIGNED_INT_24_8_WEBGL;
16440 function ArrayCamera(array) {
16441 if (array === void 0) {
16445 PerspectiveCamera.call(this);
16446 this.cameras = array;
16449 ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
16450 constructor: ArrayCamera,
16451 isArrayCamera: true
16455 Object3D.call(this);
16456 this.type = 'Group';
16459 Group.prototype = Object.assign(Object.create(Object3D.prototype), {
16460 constructor: Group,
16464 function WebXRController() {
16465 this._targetRay = null;
16470 Object.assign(WebXRController.prototype, {
16471 constructor: WebXRController,
16472 getHandSpace: function getHandSpace() {
16473 if (this._hand === null) {
16474 this._hand = new Group();
16475 this._hand.matrixAutoUpdate = false;
16476 this._hand.visible = false;
16477 this._hand.joints = [];
16478 this._hand.inputState = {
16482 if (window.XRHand) {
16483 for (var i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i++) {
16484 // The transform of this joint will be updated with the joint pose on each frame
16485 var joint = new Group();
16486 joint.matrixAutoUpdate = false;
16487 joint.visible = false;
16489 this._hand.joints.push(joint); // ??
16492 this._hand.add(joint);
16499 getTargetRaySpace: function getTargetRaySpace() {
16500 if (this._targetRay === null) {
16501 this._targetRay = new Group();
16502 this._targetRay.matrixAutoUpdate = false;
16503 this._targetRay.visible = false;
16506 return this._targetRay;
16508 getGripSpace: function getGripSpace() {
16509 if (this._grip === null) {
16510 this._grip = new Group();
16511 this._grip.matrixAutoUpdate = false;
16512 this._grip.visible = false;
16517 dispatchEvent: function dispatchEvent(event) {
16518 if (this._targetRay !== null) {
16519 this._targetRay.dispatchEvent(event);
16522 if (this._grip !== null) {
16523 this._grip.dispatchEvent(event);
16526 if (this._hand !== null) {
16527 this._hand.dispatchEvent(event);
16532 disconnect: function disconnect(inputSource) {
16533 this.dispatchEvent({
16534 type: 'disconnected',
16538 if (this._targetRay !== null) {
16539 this._targetRay.visible = false;
16542 if (this._grip !== null) {
16543 this._grip.visible = false;
16546 if (this._hand !== null) {
16547 this._hand.visible = false;
16552 update: function update(inputSource, frame, referenceSpace) {
16553 var inputPose = null;
16554 var gripPose = null;
16555 var handPose = null;
16556 var targetRay = this._targetRay;
16557 var grip = this._grip;
16558 var hand = this._hand;
16560 if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
16561 if (hand && inputSource.hand) {
16564 for (var i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i++) {
16565 if (inputSource.hand[i]) {
16566 // Update the joints groups with the XRJoint poses
16567 var jointPose = frame.getJointPose(inputSource.hand[i], referenceSpace);
16568 var joint = hand.joints[i];
16570 if (jointPose !== null) {
16571 joint.matrix.fromArray(jointPose.transform.matrix);
16572 joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
16573 joint.jointRadius = jointPose.radius;
16576 joint.visible = jointPose !== null; // Custom events
16579 var indexTip = hand.joints[window.XRHand.INDEX_PHALANX_TIP];
16580 var thumbTip = hand.joints[window.XRHand.THUMB_PHALANX_TIP];
16581 var distance = indexTip.position.distanceTo(thumbTip.position);
16582 var distanceToPinch = 0.02;
16583 var threshold = 0.005;
16585 if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
16586 hand.inputState.pinching = false;
16587 this.dispatchEvent({
16589 handedness: inputSource.handedness,
16592 } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
16593 hand.inputState.pinching = true;
16594 this.dispatchEvent({
16595 type: "pinchstart",
16596 handedness: inputSource.handedness,
16603 if (targetRay !== null) {
16604 inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
16606 if (inputPose !== null) {
16607 targetRay.matrix.fromArray(inputPose.transform.matrix);
16608 targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
16612 if (grip !== null && inputSource.gripSpace) {
16613 gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
16615 if (gripPose !== null) {
16616 grip.matrix.fromArray(gripPose.transform.matrix);
16617 grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
16623 if (targetRay !== null) {
16624 targetRay.visible = inputPose !== null;
16627 if (grip !== null) {
16628 grip.visible = gripPose !== null;
16631 if (hand !== null) {
16632 hand.visible = handPose !== null;
16639 function WebXRManager(renderer, gl) {
16641 var session = null;
16642 var framebufferScaleFactor = 1.0;
16643 var referenceSpace = null;
16644 var referenceSpaceType = 'local-floor';
16646 var controllers = [];
16647 var inputSourcesMap = new Map(); //
16649 var cameraL = new PerspectiveCamera();
16650 cameraL.layers.enable(1);
16651 cameraL.viewport = new Vector4();
16652 var cameraR = new PerspectiveCamera();
16653 cameraR.layers.enable(2);
16654 cameraR.viewport = new Vector4();
16655 var cameras = [cameraL, cameraR];
16656 var cameraVR = new ArrayCamera();
16657 cameraVR.layers.enable(1);
16658 cameraVR.layers.enable(2);
16659 var _currentDepthNear = null;
16660 var _currentDepthFar = null; //
16662 this.enabled = false;
16663 this.isPresenting = false;
16665 this.getController = function (index) {
16666 var controller = controllers[index];
16668 if (controller === undefined) {
16669 controller = new WebXRController();
16670 controllers[index] = controller;
16673 return controller.getTargetRaySpace();
16676 this.getControllerGrip = function (index) {
16677 var controller = controllers[index];
16679 if (controller === undefined) {
16680 controller = new WebXRController();
16681 controllers[index] = controller;
16684 return controller.getGripSpace();
16687 this.getHand = function (index) {
16688 var controller = controllers[index];
16690 if (controller === undefined) {
16691 controller = new WebXRController();
16692 controllers[index] = controller;
16695 return controller.getHandSpace();
16699 function onSessionEvent(event) {
16700 var controller = inputSourcesMap.get(event.inputSource);
16703 controller.dispatchEvent({
16705 data: event.inputSource
16710 function onSessionEnd() {
16711 inputSourcesMap.forEach(function (controller, inputSource) {
16712 controller.disconnect(inputSource);
16714 inputSourcesMap.clear(); //
16716 renderer.setFramebuffer(null);
16717 renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
16720 scope.isPresenting = false;
16721 scope.dispatchEvent({
16726 function onRequestReferenceSpace(value) {
16727 referenceSpace = value;
16728 animation.setContext(session);
16730 scope.isPresenting = true;
16731 scope.dispatchEvent({
16732 type: 'sessionstart'
16736 this.setFramebufferScaleFactor = function (value) {
16737 framebufferScaleFactor = value;
16739 if (scope.isPresenting === true) {
16740 console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
16744 this.setReferenceSpaceType = function (value) {
16745 referenceSpaceType = value;
16747 if (scope.isPresenting === true) {
16748 console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
16752 this.getReferenceSpace = function () {
16753 return referenceSpace;
16756 this.getSession = function () {
16760 this.setSession = function (value) {
16763 if (session !== null) {
16764 session.addEventListener('select', onSessionEvent);
16765 session.addEventListener('selectstart', onSessionEvent);
16766 session.addEventListener('selectend', onSessionEvent);
16767 session.addEventListener('squeeze', onSessionEvent);
16768 session.addEventListener('squeezestart', onSessionEvent);
16769 session.addEventListener('squeezeend', onSessionEvent);
16770 session.addEventListener('end', onSessionEnd);
16771 var attributes = gl.getContextAttributes();
16773 if (attributes.xrCompatible !== true) {
16774 gl.makeXRCompatible();
16778 antialias: attributes.antialias,
16779 alpha: attributes.alpha,
16780 depth: attributes.depth,
16781 stencil: attributes.stencil,
16782 framebufferScaleFactor: framebufferScaleFactor
16783 }; // eslint-disable-next-line no-undef
16785 var baseLayer = new XRWebGLLayer(session, gl, layerInit);
16786 session.updateRenderState({
16787 baseLayer: baseLayer
16789 session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
16791 session.addEventListener('inputsourceschange', updateInputSources);
16795 function updateInputSources(event) {
16796 var inputSources = session.inputSources; // Assign inputSources to available controllers
16798 for (var i = 0; i < controllers.length; i++) {
16799 inputSourcesMap.set(inputSources[i], controllers[i]);
16800 } // Notify disconnected
16803 for (var _i = 0; _i < event.removed.length; _i++) {
16804 var inputSource = event.removed[_i];
16805 var controller = inputSourcesMap.get(inputSource);
16808 controller.dispatchEvent({
16809 type: 'disconnected',
16812 inputSourcesMap.delete(inputSource);
16814 } // Notify connected
16817 for (var _i2 = 0; _i2 < event.added.length; _i2++) {
16818 var _inputSource = event.added[_i2];
16820 var _controller = inputSourcesMap.get(_inputSource);
16823 _controller.dispatchEvent({
16832 var cameraLPos = new Vector3();
16833 var cameraRPos = new Vector3();
16835 * Assumes 2 cameras that are parallel and share an X-axis, and that
16836 * the cameras' projection and world matrices have already been set.
16837 * And that near and far planes are identical for both cameras.
16838 * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
16841 function setProjectionFromUnion(camera, cameraL, cameraR) {
16842 cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
16843 cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
16844 var ipd = cameraLPos.distanceTo(cameraRPos);
16845 var projL = cameraL.projectionMatrix.elements;
16846 var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
16847 // most likely identical top and bottom frustum extents.
16848 // Use the left camera for these values.
16850 var near = projL[14] / (projL[10] - 1);
16851 var far = projL[14] / (projL[10] + 1);
16852 var topFov = (projL[9] + 1) / projL[5];
16853 var bottomFov = (projL[9] - 1) / projL[5];
16854 var leftFov = (projL[8] - 1) / projL[0];
16855 var rightFov = (projR[8] + 1) / projR[0];
16856 var left = near * leftFov;
16857 var right = near * rightFov; // Calculate the new camera's position offset from the
16858 // left camera. xOffset should be roughly half `ipd`.
16860 var zOffset = ipd / (-leftFov + rightFov);
16861 var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
16863 cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
16864 camera.translateX(xOffset);
16865 camera.translateZ(zOffset);
16866 camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
16867 camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
16868 // the values so that the near plane's position does not change in world space,
16869 // although must now be relative to the new union camera.
16871 var near2 = near + zOffset;
16872 var far2 = far + zOffset;
16873 var left2 = left - xOffset;
16874 var right2 = right + (ipd - xOffset);
16875 var top2 = topFov * far / far2 * near2;
16876 var bottom2 = bottomFov * far / far2 * near2;
16877 camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
16880 function updateCamera(camera, parent) {
16881 if (parent === null) {
16882 camera.matrixWorld.copy(camera.matrix);
16884 camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
16887 camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
16890 this.getCamera = function (camera) {
16891 cameraVR.near = cameraR.near = cameraL.near = camera.near;
16892 cameraVR.far = cameraR.far = cameraL.far = camera.far;
16894 if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
16895 // Note that the new renderState won't apply until the next frame. See #18320
16896 session.updateRenderState({
16897 depthNear: cameraVR.near,
16898 depthFar: cameraVR.far
16900 _currentDepthNear = cameraVR.near;
16901 _currentDepthFar = cameraVR.far;
16904 var parent = camera.parent;
16905 var cameras = cameraVR.cameras;
16906 updateCamera(cameraVR, parent);
16908 for (var i = 0; i < cameras.length; i++) {
16909 updateCamera(cameras[i], parent);
16910 } // update camera and its children
16913 camera.matrixWorld.copy(cameraVR.matrixWorld);
16914 var children = camera.children;
16916 for (var _i3 = 0, l = children.length; _i3 < l; _i3++) {
16917 children[_i3].updateMatrixWorld(true);
16918 } // update projection matrix for proper view frustum culling
16921 if (cameras.length === 2) {
16922 setProjectionFromUnion(cameraVR, cameraL, cameraR);
16924 // assume single camera setup (AR)
16925 cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
16929 }; // Animation Loop
16932 var onAnimationFrameCallback = null;
16934 function onAnimationFrame(time, frame) {
16935 pose = frame.getViewerPose(referenceSpace);
16937 if (pose !== null) {
16938 var views = pose.views;
16939 var baseLayer = session.renderState.baseLayer;
16940 renderer.setFramebuffer(baseLayer.framebuffer);
16941 var cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
16943 if (views.length !== cameraVR.cameras.length) {
16944 cameraVR.cameras.length = 0;
16945 cameraVRNeedsUpdate = true;
16948 for (var i = 0; i < views.length; i++) {
16949 var view = views[i];
16950 var viewport = baseLayer.getViewport(view);
16951 var camera = cameras[i];
16952 camera.matrix.fromArray(view.transform.matrix);
16953 camera.projectionMatrix.fromArray(view.projectionMatrix);
16954 camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
16957 cameraVR.matrix.copy(camera.matrix);
16960 if (cameraVRNeedsUpdate === true) {
16961 cameraVR.cameras.push(camera);
16967 var inputSources = session.inputSources;
16969 for (var _i4 = 0; _i4 < controllers.length; _i4++) {
16970 var controller = controllers[_i4];
16971 var inputSource = inputSources[_i4];
16972 controller.update(inputSource, frame, referenceSpace);
16975 if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
16978 var animation = new WebGLAnimation();
16979 animation.setAnimationLoop(onAnimationFrame);
16981 this.setAnimationLoop = function (callback) {
16982 onAnimationFrameCallback = callback;
16985 this.dispose = function () {};
16988 Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
16990 function WebGLMaterials(properties) {
16991 function refreshFogUniforms(uniforms, fog) {
16992 uniforms.fogColor.value.copy(fog.color);
16995 uniforms.fogNear.value = fog.near;
16996 uniforms.fogFar.value = fog.far;
16997 } else if (fog.isFogExp2) {
16998 uniforms.fogDensity.value = fog.density;
17002 function refreshMaterialUniforms(uniforms, material, pixelRatio, height) {
17003 if (material.isMeshBasicMaterial) {
17004 refreshUniformsCommon(uniforms, material);
17005 } else if (material.isMeshLambertMaterial) {
17006 refreshUniformsCommon(uniforms, material);
17007 refreshUniformsLambert(uniforms, material);
17008 } else if (material.isMeshToonMaterial) {
17009 refreshUniformsCommon(uniforms, material);
17010 refreshUniformsToon(uniforms, material);
17011 } else if (material.isMeshPhongMaterial) {
17012 refreshUniformsCommon(uniforms, material);
17013 refreshUniformsPhong(uniforms, material);
17014 } else if (material.isMeshStandardMaterial) {
17015 refreshUniformsCommon(uniforms, material);
17017 if (material.isMeshPhysicalMaterial) {
17018 refreshUniformsPhysical(uniforms, material);
17020 refreshUniformsStandard(uniforms, material);
17022 } else if (material.isMeshMatcapMaterial) {
17023 refreshUniformsCommon(uniforms, material);
17024 refreshUniformsMatcap(uniforms, material);
17025 } else if (material.isMeshDepthMaterial) {
17026 refreshUniformsCommon(uniforms, material);
17027 refreshUniformsDepth(uniforms, material);
17028 } else if (material.isMeshDistanceMaterial) {
17029 refreshUniformsCommon(uniforms, material);
17030 refreshUniformsDistance(uniforms, material);
17031 } else if (material.isMeshNormalMaterial) {
17032 refreshUniformsCommon(uniforms, material);
17033 refreshUniformsNormal(uniforms, material);
17034 } else if (material.isLineBasicMaterial) {
17035 refreshUniformsLine(uniforms, material);
17037 if (material.isLineDashedMaterial) {
17038 refreshUniformsDash(uniforms, material);
17040 } else if (material.isPointsMaterial) {
17041 refreshUniformsPoints(uniforms, material, pixelRatio, height);
17042 } else if (material.isSpriteMaterial) {
17043 refreshUniformsSprites(uniforms, material);
17044 } else if (material.isShadowMaterial) {
17045 uniforms.color.value.copy(material.color);
17046 uniforms.opacity.value = material.opacity;
17047 } else if (material.isShaderMaterial) {
17048 material.uniformsNeedUpdate = false; // #15581
17052 function refreshUniformsCommon(uniforms, material) {
17053 uniforms.opacity.value = material.opacity;
17055 if (material.color) {
17056 uniforms.diffuse.value.copy(material.color);
17059 if (material.emissive) {
17060 uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
17063 if (material.map) {
17064 uniforms.map.value = material.map;
17067 if (material.alphaMap) {
17068 uniforms.alphaMap.value = material.alphaMap;
17071 if (material.specularMap) {
17072 uniforms.specularMap.value = material.specularMap;
17075 var envMap = properties.get(material).envMap;
17078 uniforms.envMap.value = envMap;
17079 uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
17080 uniforms.reflectivity.value = material.reflectivity;
17081 uniforms.refractionRatio.value = material.refractionRatio;
17083 var maxMipLevel = properties.get(envMap).__maxMipLevel;
17085 if (maxMipLevel !== undefined) {
17086 uniforms.maxMipLevel.value = maxMipLevel;
17090 if (material.lightMap) {
17091 uniforms.lightMap.value = material.lightMap;
17092 uniforms.lightMapIntensity.value = material.lightMapIntensity;
17095 if (material.aoMap) {
17096 uniforms.aoMap.value = material.aoMap;
17097 uniforms.aoMapIntensity.value = material.aoMapIntensity;
17098 } // uv repeat and offset setting priorities
17101 // 3. displacementMap map
17104 // 6. roughnessMap map
17105 // 7. metalnessMap map
17107 // 9. emissiveMap map
17108 // 10. clearcoat map
17109 // 11. clearcoat normal map
17110 // 12. clearcoat roughnessMap map
17115 if (material.map) {
17116 uvScaleMap = material.map;
17117 } else if (material.specularMap) {
17118 uvScaleMap = material.specularMap;
17119 } else if (material.displacementMap) {
17120 uvScaleMap = material.displacementMap;
17121 } else if (material.normalMap) {
17122 uvScaleMap = material.normalMap;
17123 } else if (material.bumpMap) {
17124 uvScaleMap = material.bumpMap;
17125 } else if (material.roughnessMap) {
17126 uvScaleMap = material.roughnessMap;
17127 } else if (material.metalnessMap) {
17128 uvScaleMap = material.metalnessMap;
17129 } else if (material.alphaMap) {
17130 uvScaleMap = material.alphaMap;
17131 } else if (material.emissiveMap) {
17132 uvScaleMap = material.emissiveMap;
17133 } else if (material.clearcoatMap) {
17134 uvScaleMap = material.clearcoatMap;
17135 } else if (material.clearcoatNormalMap) {
17136 uvScaleMap = material.clearcoatNormalMap;
17137 } else if (material.clearcoatRoughnessMap) {
17138 uvScaleMap = material.clearcoatRoughnessMap;
17141 if (uvScaleMap !== undefined) {
17142 // backwards compatibility
17143 if (uvScaleMap.isWebGLRenderTarget) {
17144 uvScaleMap = uvScaleMap.texture;
17147 if (uvScaleMap.matrixAutoUpdate === true) {
17148 uvScaleMap.updateMatrix();
17151 uniforms.uvTransform.value.copy(uvScaleMap.matrix);
17152 } // uv repeat and offset setting priorities for uv2
17159 if (material.aoMap) {
17160 uv2ScaleMap = material.aoMap;
17161 } else if (material.lightMap) {
17162 uv2ScaleMap = material.lightMap;
17165 if (uv2ScaleMap !== undefined) {
17166 // backwards compatibility
17167 if (uv2ScaleMap.isWebGLRenderTarget) {
17168 uv2ScaleMap = uv2ScaleMap.texture;
17171 if (uv2ScaleMap.matrixAutoUpdate === true) {
17172 uv2ScaleMap.updateMatrix();
17175 uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
17179 function refreshUniformsLine(uniforms, material) {
17180 uniforms.diffuse.value.copy(material.color);
17181 uniforms.opacity.value = material.opacity;
17184 function refreshUniformsDash(uniforms, material) {
17185 uniforms.dashSize.value = material.dashSize;
17186 uniforms.totalSize.value = material.dashSize + material.gapSize;
17187 uniforms.scale.value = material.scale;
17190 function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
17191 uniforms.diffuse.value.copy(material.color);
17192 uniforms.opacity.value = material.opacity;
17193 uniforms.size.value = material.size * pixelRatio;
17194 uniforms.scale.value = height * 0.5;
17196 if (material.map) {
17197 uniforms.map.value = material.map;
17200 if (material.alphaMap) {
17201 uniforms.alphaMap.value = material.alphaMap;
17202 } // uv repeat and offset setting priorities
17209 if (material.map) {
17210 uvScaleMap = material.map;
17211 } else if (material.alphaMap) {
17212 uvScaleMap = material.alphaMap;
17215 if (uvScaleMap !== undefined) {
17216 if (uvScaleMap.matrixAutoUpdate === true) {
17217 uvScaleMap.updateMatrix();
17220 uniforms.uvTransform.value.copy(uvScaleMap.matrix);
17224 function refreshUniformsSprites(uniforms, material) {
17225 uniforms.diffuse.value.copy(material.color);
17226 uniforms.opacity.value = material.opacity;
17227 uniforms.rotation.value = material.rotation;
17229 if (material.map) {
17230 uniforms.map.value = material.map;
17233 if (material.alphaMap) {
17234 uniforms.alphaMap.value = material.alphaMap;
17235 } // uv repeat and offset setting priorities
17242 if (material.map) {
17243 uvScaleMap = material.map;
17244 } else if (material.alphaMap) {
17245 uvScaleMap = material.alphaMap;
17248 if (uvScaleMap !== undefined) {
17249 if (uvScaleMap.matrixAutoUpdate === true) {
17250 uvScaleMap.updateMatrix();
17253 uniforms.uvTransform.value.copy(uvScaleMap.matrix);
17257 function refreshUniformsLambert(uniforms, material) {
17258 if (material.emissiveMap) {
17259 uniforms.emissiveMap.value = material.emissiveMap;
17263 function refreshUniformsPhong(uniforms, material) {
17264 uniforms.specular.value.copy(material.specular);
17265 uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
17267 if (material.emissiveMap) {
17268 uniforms.emissiveMap.value = material.emissiveMap;
17271 if (material.bumpMap) {
17272 uniforms.bumpMap.value = material.bumpMap;
17273 uniforms.bumpScale.value = material.bumpScale;
17274 if (material.side === BackSide) uniforms.bumpScale.value *= -1;
17277 if (material.normalMap) {
17278 uniforms.normalMap.value = material.normalMap;
17279 uniforms.normalScale.value.copy(material.normalScale);
17280 if (material.side === BackSide) uniforms.normalScale.value.negate();
17283 if (material.displacementMap) {
17284 uniforms.displacementMap.value = material.displacementMap;
17285 uniforms.displacementScale.value = material.displacementScale;
17286 uniforms.displacementBias.value = material.displacementBias;
17290 function refreshUniformsToon(uniforms, material) {
17291 if (material.gradientMap) {
17292 uniforms.gradientMap.value = material.gradientMap;
17295 if (material.emissiveMap) {
17296 uniforms.emissiveMap.value = material.emissiveMap;
17299 if (material.bumpMap) {
17300 uniforms.bumpMap.value = material.bumpMap;
17301 uniforms.bumpScale.value = material.bumpScale;
17302 if (material.side === BackSide) uniforms.bumpScale.value *= -1;
17305 if (material.normalMap) {
17306 uniforms.normalMap.value = material.normalMap;
17307 uniforms.normalScale.value.copy(material.normalScale);
17308 if (material.side === BackSide) uniforms.normalScale.value.negate();
17311 if (material.displacementMap) {
17312 uniforms.displacementMap.value = material.displacementMap;
17313 uniforms.displacementScale.value = material.displacementScale;
17314 uniforms.displacementBias.value = material.displacementBias;
17318 function refreshUniformsStandard(uniforms, material) {
17319 uniforms.roughness.value = material.roughness;
17320 uniforms.metalness.value = material.metalness;
17322 if (material.roughnessMap) {
17323 uniforms.roughnessMap.value = material.roughnessMap;
17326 if (material.metalnessMap) {
17327 uniforms.metalnessMap.value = material.metalnessMap;
17330 if (material.emissiveMap) {
17331 uniforms.emissiveMap.value = material.emissiveMap;
17334 if (material.bumpMap) {
17335 uniforms.bumpMap.value = material.bumpMap;
17336 uniforms.bumpScale.value = material.bumpScale;
17337 if (material.side === BackSide) uniforms.bumpScale.value *= -1;
17340 if (material.normalMap) {
17341 uniforms.normalMap.value = material.normalMap;
17342 uniforms.normalScale.value.copy(material.normalScale);
17343 if (material.side === BackSide) uniforms.normalScale.value.negate();
17346 if (material.displacementMap) {
17347 uniforms.displacementMap.value = material.displacementMap;
17348 uniforms.displacementScale.value = material.displacementScale;
17349 uniforms.displacementBias.value = material.displacementBias;
17352 var envMap = properties.get(material).envMap;
17355 //uniforms.envMap.value = material.envMap; // part of uniforms common
17356 uniforms.envMapIntensity.value = material.envMapIntensity;
17360 function refreshUniformsPhysical(uniforms, material) {
17361 refreshUniformsStandard(uniforms, material);
17362 uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
17364 uniforms.clearcoat.value = material.clearcoat;
17365 uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
17366 if (material.sheen) uniforms.sheen.value.copy(material.sheen);
17368 if (material.clearcoatMap) {
17369 uniforms.clearcoatMap.value = material.clearcoatMap;
17372 if (material.clearcoatRoughnessMap) {
17373 uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
17376 if (material.clearcoatNormalMap) {
17377 uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
17378 uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
17380 if (material.side === BackSide) {
17381 uniforms.clearcoatNormalScale.value.negate();
17385 uniforms.transmission.value = material.transmission;
17387 if (material.transmissionMap) {
17388 uniforms.transmissionMap.value = material.transmissionMap;
17392 function refreshUniformsMatcap(uniforms, material) {
17393 if (material.matcap) {
17394 uniforms.matcap.value = material.matcap;
17397 if (material.bumpMap) {
17398 uniforms.bumpMap.value = material.bumpMap;
17399 uniforms.bumpScale.value = material.bumpScale;
17400 if (material.side === BackSide) uniforms.bumpScale.value *= -1;
17403 if (material.normalMap) {
17404 uniforms.normalMap.value = material.normalMap;
17405 uniforms.normalScale.value.copy(material.normalScale);
17406 if (material.side === BackSide) uniforms.normalScale.value.negate();
17409 if (material.displacementMap) {
17410 uniforms.displacementMap.value = material.displacementMap;
17411 uniforms.displacementScale.value = material.displacementScale;
17412 uniforms.displacementBias.value = material.displacementBias;
17416 function refreshUniformsDepth(uniforms, material) {
17417 if (material.displacementMap) {
17418 uniforms.displacementMap.value = material.displacementMap;
17419 uniforms.displacementScale.value = material.displacementScale;
17420 uniforms.displacementBias.value = material.displacementBias;
17424 function refreshUniformsDistance(uniforms, material) {
17425 if (material.displacementMap) {
17426 uniforms.displacementMap.value = material.displacementMap;
17427 uniforms.displacementScale.value = material.displacementScale;
17428 uniforms.displacementBias.value = material.displacementBias;
17431 uniforms.referencePosition.value.copy(material.referencePosition);
17432 uniforms.nearDistance.value = material.nearDistance;
17433 uniforms.farDistance.value = material.farDistance;
17436 function refreshUniformsNormal(uniforms, material) {
17437 if (material.bumpMap) {
17438 uniforms.bumpMap.value = material.bumpMap;
17439 uniforms.bumpScale.value = material.bumpScale;
17440 if (material.side === BackSide) uniforms.bumpScale.value *= -1;
17443 if (material.normalMap) {
17444 uniforms.normalMap.value = material.normalMap;
17445 uniforms.normalScale.value.copy(material.normalScale);
17446 if (material.side === BackSide) uniforms.normalScale.value.negate();
17449 if (material.displacementMap) {
17450 uniforms.displacementMap.value = material.displacementMap;
17451 uniforms.displacementScale.value = material.displacementScale;
17452 uniforms.displacementBias.value = material.displacementBias;
17457 refreshFogUniforms: refreshFogUniforms,
17458 refreshMaterialUniforms: refreshMaterialUniforms
17462 function createCanvasElement() {
17463 var canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
17464 canvas.style.display = 'block';
17468 function WebGLRenderer(parameters) {
17469 parameters = parameters || {};
17471 var _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
17472 _context = parameters.context !== undefined ? parameters.context : null,
17473 _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
17474 _depth = parameters.depth !== undefined ? parameters.depth : true,
17475 _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
17476 _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
17477 _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
17478 _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
17479 _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
17480 _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
17482 var currentRenderList = null;
17483 var currentRenderState = null; // public properties
17485 this.domElement = _canvas; // Debug configuration container
17489 * Enables error checking and reporting when shader programs are being compiled
17492 checkShaderErrors: true
17495 this.autoClear = true;
17496 this.autoClearColor = true;
17497 this.autoClearDepth = true;
17498 this.autoClearStencil = true; // scene graph
17500 this.sortObjects = true; // user-defined clipping
17502 this.clippingPlanes = [];
17503 this.localClippingEnabled = false; // physically based shading
17505 this.gammaFactor = 2.0; // for backwards compatibility
17507 this.outputEncoding = LinearEncoding; // physical lights
17509 this.physicallyCorrectLights = false; // tone mapping
17511 this.toneMapping = NoToneMapping;
17512 this.toneMappingExposure = 1.0; // morphs
17514 this.maxMorphTargets = 8;
17515 this.maxMorphNormals = 4; // internal properties
17519 var _isContextLost = false; // internal state cache
17521 var _framebuffer = null;
17522 var _currentActiveCubeFace = 0;
17523 var _currentActiveMipmapLevel = 0;
17524 var _currentRenderTarget = null;
17525 var _currentFramebuffer = null;
17527 var _currentMaterialId = -1;
17529 var _currentCamera = null;
17530 var _currentArrayCamera = null;
17532 var _currentViewport = new Vector4();
17534 var _currentScissor = new Vector4();
17536 var _currentScissorTest = null; //
17538 var _width = _canvas.width;
17539 var _height = _canvas.height;
17540 var _pixelRatio = 1;
17541 var _opaqueSort = null;
17542 var _transparentSort = null;
17544 var _viewport = new Vector4(0, 0, _width, _height);
17546 var _scissor = new Vector4(0, 0, _width, _height);
17548 var _scissorTest = false; // frustum
17550 var _frustum = new Frustum(); // clipping
17553 var _clippingEnabled = false;
17554 var _localClippingEnabled = false; // camera matrices cache
17556 var _projScreenMatrix = new Matrix4();
17558 var _vector3 = new Vector3();
17560 var _emptyScene = {
17564 overrideMaterial: null,
17568 function getTargetPixelRatio() {
17569 return _currentRenderTarget === null ? _pixelRatio : 1;
17573 var _gl = _context;
17575 function getContext(contextNames, contextAttributes) {
17576 for (var i = 0; i < contextNames.length; i++) {
17577 var contextName = contextNames[i];
17579 var context = _canvas.getContext(contextName, contextAttributes);
17581 if (context !== null) return context;
17588 var contextAttributes = {
17592 antialias: _antialias,
17593 premultipliedAlpha: _premultipliedAlpha,
17594 preserveDrawingBuffer: _preserveDrawingBuffer,
17595 powerPreference: _powerPreference,
17596 failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
17597 }; // event listeners must be registered before WebGL context is created, see #12753
17599 _canvas.addEventListener('webglcontextlost', onContextLost, false);
17601 _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
17603 if (_gl === null) {
17604 var contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
17606 if (_this.isWebGL1Renderer === true) {
17607 contextNames.shift();
17610 _gl = getContext(contextNames, contextAttributes);
17612 if (_gl === null) {
17613 if (getContext(contextNames)) {
17614 throw new Error('Error creating WebGL context with your selected attributes.');
17616 throw new Error('Error creating WebGL context.');
17619 } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
17622 if (_gl.getShaderPrecisionFormat === undefined) {
17623 _gl.getShaderPrecisionFormat = function () {
17632 console.error('THREE.WebGLRenderer: ' + error.message);
17636 var extensions, capabilities, state, info;
17637 var properties, textures, cubemaps, attributes, geometries, objects;
17638 var programCache, materials, renderLists, renderStates, clipping;
17639 var background, morphtargets, bufferRenderer, indexedBufferRenderer;
17640 var utils, bindingStates;
17642 function initGLContext() {
17643 extensions = new WebGLExtensions(_gl);
17644 capabilities = new WebGLCapabilities(_gl, extensions, parameters);
17646 if (capabilities.isWebGL2 === false) {
17647 extensions.get('WEBGL_depth_texture');
17648 extensions.get('OES_texture_float');
17649 extensions.get('OES_texture_half_float');
17650 extensions.get('OES_texture_half_float_linear');
17651 extensions.get('OES_standard_derivatives');
17652 extensions.get('OES_element_index_uint');
17653 extensions.get('OES_vertex_array_object');
17654 extensions.get('ANGLE_instanced_arrays');
17657 extensions.get('OES_texture_float_linear');
17658 utils = new WebGLUtils(_gl, extensions, capabilities);
17659 state = new WebGLState(_gl, extensions, capabilities);
17660 state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
17661 state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
17662 info = new WebGLInfo(_gl);
17663 properties = new WebGLProperties();
17664 textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
17665 cubemaps = new WebGLCubeMaps(_this);
17666 attributes = new WebGLAttributes(_gl, capabilities);
17667 bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
17668 geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
17669 objects = new WebGLObjects(_gl, geometries, attributes, info);
17670 morphtargets = new WebGLMorphtargets(_gl);
17671 clipping = new WebGLClipping(properties);
17672 programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
17673 materials = new WebGLMaterials(properties);
17674 renderLists = new WebGLRenderLists(properties);
17675 renderStates = new WebGLRenderStates(extensions, capabilities);
17676 background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
17677 bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
17678 indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
17679 info.programs = programCache.programs;
17680 _this.capabilities = capabilities;
17681 _this.extensions = extensions;
17682 _this.properties = properties;
17683 _this.renderLists = renderLists;
17684 _this.state = state;
17688 initGLContext(); // xr
17690 var xr = new WebXRManager(_this, _gl);
17691 this.xr = xr; // shadow map
17693 var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
17694 this.shadowMap = shadowMap; // API
17696 this.getContext = function () {
17700 this.getContextAttributes = function () {
17701 return _gl.getContextAttributes();
17704 this.forceContextLoss = function () {
17705 var extension = extensions.get('WEBGL_lose_context');
17706 if (extension) extension.loseContext();
17709 this.forceContextRestore = function () {
17710 var extension = extensions.get('WEBGL_lose_context');
17711 if (extension) extension.restoreContext();
17714 this.getPixelRatio = function () {
17715 return _pixelRatio;
17718 this.setPixelRatio = function (value) {
17719 if (value === undefined) return;
17720 _pixelRatio = value;
17721 this.setSize(_width, _height, false);
17724 this.getSize = function (target) {
17725 if (target === undefined) {
17726 console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
17727 target = new Vector2();
17730 return target.set(_width, _height);
17733 this.setSize = function (width, height, updateStyle) {
17734 if (xr.isPresenting) {
17735 console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
17741 _canvas.width = Math.floor(width * _pixelRatio);
17742 _canvas.height = Math.floor(height * _pixelRatio);
17744 if (updateStyle !== false) {
17745 _canvas.style.width = width + 'px';
17746 _canvas.style.height = height + 'px';
17749 this.setViewport(0, 0, width, height);
17752 this.getDrawingBufferSize = function (target) {
17753 if (target === undefined) {
17754 console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
17755 target = new Vector2();
17758 return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
17761 this.setDrawingBufferSize = function (width, height, pixelRatio) {
17764 _pixelRatio = pixelRatio;
17765 _canvas.width = Math.floor(width * pixelRatio);
17766 _canvas.height = Math.floor(height * pixelRatio);
17767 this.setViewport(0, 0, width, height);
17770 this.getCurrentViewport = function (target) {
17771 if (target === undefined) {
17772 console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
17773 target = new Vector4();
17776 return target.copy(_currentViewport);
17779 this.getViewport = function (target) {
17780 return target.copy(_viewport);
17783 this.setViewport = function (x, y, width, height) {
17785 _viewport.set(x.x, x.y, x.z, x.w);
17787 _viewport.set(x, y, width, height);
17790 state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
17793 this.getScissor = function (target) {
17794 return target.copy(_scissor);
17797 this.setScissor = function (x, y, width, height) {
17799 _scissor.set(x.x, x.y, x.z, x.w);
17801 _scissor.set(x, y, width, height);
17804 state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
17807 this.getScissorTest = function () {
17808 return _scissorTest;
17811 this.setScissorTest = function (boolean) {
17812 state.setScissorTest(_scissorTest = boolean);
17815 this.setOpaqueSort = function (method) {
17816 _opaqueSort = method;
17819 this.setTransparentSort = function (method) {
17820 _transparentSort = method;
17824 this.getClearColor = function () {
17825 return background.getClearColor();
17828 this.setClearColor = function () {
17829 background.setClearColor.apply(background, arguments);
17832 this.getClearAlpha = function () {
17833 return background.getClearAlpha();
17836 this.setClearAlpha = function () {
17837 background.setClearAlpha.apply(background, arguments);
17840 this.clear = function (color, depth, stencil) {
17842 if (color === undefined || color) bits |= 16384;
17843 if (depth === undefined || depth) bits |= 256;
17844 if (stencil === undefined || stencil) bits |= 1024;
17849 this.clearColor = function () {
17850 this.clear(true, false, false);
17853 this.clearDepth = function () {
17854 this.clear(false, true, false);
17857 this.clearStencil = function () {
17858 this.clear(false, false, true);
17862 this.dispose = function () {
17863 _canvas.removeEventListener('webglcontextlost', onContextLost, false);
17865 _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
17867 renderLists.dispose();
17868 renderStates.dispose();
17869 properties.dispose();
17870 cubemaps.dispose();
17872 bindingStates.dispose();
17878 function onContextLost(event) {
17879 event.preventDefault();
17880 console.log('THREE.WebGLRenderer: Context Lost.');
17881 _isContextLost = true;
17884 function onContextRestore()
17887 console.log('THREE.WebGLRenderer: Context Restored.');
17888 _isContextLost = false;
17892 function onMaterialDispose(event) {
17893 var material = event.target;
17894 material.removeEventListener('dispose', onMaterialDispose);
17895 deallocateMaterial(material);
17896 } // Buffer deallocation
17899 function deallocateMaterial(material) {
17900 releaseMaterialProgramReference(material);
17901 properties.remove(material);
17904 function releaseMaterialProgramReference(material) {
17905 var programInfo = properties.get(material).program;
17907 if (programInfo !== undefined) {
17908 programCache.releaseProgram(programInfo);
17910 } // Buffer rendering
17913 function renderObjectImmediate(object, program) {
17914 object.render(function (object) {
17915 _this.renderBufferImmediate(object, program);
17919 this.renderBufferImmediate = function (object, program) {
17920 bindingStates.initAttributes();
17921 var buffers = properties.get(object);
17922 if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
17923 if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
17924 if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
17925 if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
17926 var programAttributes = program.getAttributes();
17928 if (object.hasPositions) {
17929 _gl.bindBuffer(34962, buffers.position);
17931 _gl.bufferData(34962, object.positionArray, 35048);
17933 bindingStates.enableAttribute(programAttributes.position);
17935 _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
17938 if (object.hasNormals) {
17939 _gl.bindBuffer(34962, buffers.normal);
17941 _gl.bufferData(34962, object.normalArray, 35048);
17943 bindingStates.enableAttribute(programAttributes.normal);
17945 _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
17948 if (object.hasUvs) {
17949 _gl.bindBuffer(34962, buffers.uv);
17951 _gl.bufferData(34962, object.uvArray, 35048);
17953 bindingStates.enableAttribute(programAttributes.uv);
17955 _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
17958 if (object.hasColors) {
17959 _gl.bindBuffer(34962, buffers.color);
17961 _gl.bufferData(34962, object.colorArray, 35048);
17963 bindingStates.enableAttribute(programAttributes.color);
17965 _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
17968 bindingStates.disableUnusedAttributes();
17970 _gl.drawArrays(4, 0, object.count);
17975 this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
17976 if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
17978 var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
17979 var program = setProgram(camera, scene, material, object);
17980 state.setMaterial(material, frontFaceCW); //
17982 var index = geometry.index;
17983 var position = geometry.attributes.position; //
17985 if (index === null) {
17986 if (position === undefined || position.count === 0) return;
17987 } else if (index.count === 0) {
17992 var rangeFactor = 1;
17994 if (material.wireframe === true) {
17995 index = geometries.getWireframeAttribute(geometry);
17999 if (material.morphTargets || material.morphNormals) {
18000 morphtargets.update(object, geometry, material, program);
18003 bindingStates.setup(object, material, program, geometry, index);
18005 var renderer = bufferRenderer;
18007 if (index !== null) {
18008 attribute = attributes.get(index);
18009 renderer = indexedBufferRenderer;
18010 renderer.setIndex(attribute);
18014 var dataCount = index !== null ? index.count : position.count;
18015 var rangeStart = geometry.drawRange.start * rangeFactor;
18016 var rangeCount = geometry.drawRange.count * rangeFactor;
18017 var groupStart = group !== null ? group.start * rangeFactor : 0;
18018 var groupCount = group !== null ? group.count * rangeFactor : Infinity;
18019 var drawStart = Math.max(rangeStart, groupStart);
18020 var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
18021 var drawCount = Math.max(0, drawEnd - drawStart + 1);
18022 if (drawCount === 0) return; //
18024 if (object.isMesh) {
18025 if (material.wireframe === true) {
18026 state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
18027 renderer.setMode(1);
18029 renderer.setMode(4);
18031 } else if (object.isLine) {
18032 var lineWidth = material.linewidth;
18033 if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
18035 state.setLineWidth(lineWidth * getTargetPixelRatio());
18037 if (object.isLineSegments) {
18038 renderer.setMode(1);
18039 } else if (object.isLineLoop) {
18040 renderer.setMode(2);
18042 renderer.setMode(3);
18044 } else if (object.isPoints) {
18045 renderer.setMode(0);
18046 } else if (object.isSprite) {
18047 renderer.setMode(4);
18050 if (object.isInstancedMesh) {
18051 renderer.renderInstances(drawStart, drawCount, object.count);
18052 } else if (geometry.isInstancedBufferGeometry) {
18053 var instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
18054 renderer.renderInstances(drawStart, drawCount, instanceCount);
18056 renderer.render(drawStart, drawCount);
18061 this.compile = function (scene, camera) {
18062 currentRenderState = renderStates.get(scene, camera);
18063 currentRenderState.init();
18064 scene.traverseVisible(function (object) {
18065 if (object.isLight && object.layers.test(camera.layers)) {
18066 currentRenderState.pushLight(object);
18068 if (object.castShadow) {
18069 currentRenderState.pushShadow(object);
18073 currentRenderState.setupLights(camera);
18074 var compiled = new WeakMap();
18075 scene.traverse(function (object) {
18076 var material = object.material;
18079 if (Array.isArray(material)) {
18080 for (var i = 0; i < material.length; i++) {
18081 var material2 = material[i];
18083 if (compiled.has(material2) === false) {
18084 initMaterial(material2, scene, object);
18085 compiled.set(material2);
18088 } else if (compiled.has(material) === false) {
18089 initMaterial(material, scene, object);
18090 compiled.set(material);
18094 }; // Animation Loop
18097 var onAnimationFrameCallback = null;
18099 function onAnimationFrame(time) {
18100 if (xr.isPresenting) return;
18101 if (onAnimationFrameCallback) onAnimationFrameCallback(time);
18104 var animation = new WebGLAnimation();
18105 animation.setAnimationLoop(onAnimationFrame);
18106 if (typeof window !== 'undefined') animation.setContext(window);
18108 this.setAnimationLoop = function (callback) {
18109 onAnimationFrameCallback = callback;
18110 xr.setAnimationLoop(callback);
18111 callback === null ? animation.stop() : animation.start();
18115 this.render = function (scene, camera) {
18116 var renderTarget, forceClear;
18118 if (arguments[2] !== undefined) {
18119 console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
18120 renderTarget = arguments[2];
18123 if (arguments[3] !== undefined) {
18124 console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
18125 forceClear = arguments[3];
18128 if (camera !== undefined && camera.isCamera !== true) {
18129 console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
18133 if (_isContextLost === true) return; // reset caching for this frame
18135 bindingStates.resetDefaultState();
18136 _currentMaterialId = -1;
18137 _currentCamera = null; // update scene graph
18139 if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
18141 if (camera.parent === null) camera.updateMatrixWorld();
18143 if (xr.enabled === true && xr.isPresenting === true) {
18144 camera = xr.getCamera(camera);
18148 if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
18149 currentRenderState = renderStates.get(scene, camera);
18150 currentRenderState.init();
18152 _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
18154 _frustum.setFromProjectionMatrix(_projScreenMatrix);
18156 _localClippingEnabled = this.localClippingEnabled;
18157 _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
18158 currentRenderList = renderLists.get(scene, camera);
18159 currentRenderList.init();
18160 projectObject(scene, camera, 0, _this.sortObjects);
18161 currentRenderList.finish();
18163 if (_this.sortObjects === true) {
18164 currentRenderList.sort(_opaqueSort, _transparentSort);
18168 if (_clippingEnabled === true) clipping.beginShadows();
18169 var shadowsArray = currentRenderState.state.shadowsArray;
18170 shadowMap.render(shadowsArray, scene, camera);
18171 currentRenderState.setupLights(camera);
18172 if (_clippingEnabled === true) clipping.endShadows(); //
18174 if (this.info.autoReset === true) this.info.reset();
18176 if (renderTarget !== undefined) {
18177 this.setRenderTarget(renderTarget);
18181 background.render(currentRenderList, scene, camera, forceClear); // render scene
18183 var opaqueObjects = currentRenderList.opaque;
18184 var transparentObjects = currentRenderList.transparent;
18185 if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
18186 if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
18188 if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); //
18190 if (_currentRenderTarget !== null) {
18191 // Generate mipmap if we're using any kind of mipmap filtering
18192 textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
18194 textures.updateMultisampleRenderTarget(_currentRenderTarget);
18195 } // Ensure depth buffer writing is enabled so it can be cleared on next render
18198 state.buffers.depth.setTest(true);
18199 state.buffers.depth.setMask(true);
18200 state.buffers.color.setMask(true);
18201 state.setPolygonOffset(false); // _gl.finish();
18203 currentRenderList = null;
18204 currentRenderState = null;
18207 function projectObject(object, camera, groupOrder, sortObjects) {
18208 if (object.visible === false) return;
18209 var visible = object.layers.test(camera.layers);
18212 if (object.isGroup) {
18213 groupOrder = object.renderOrder;
18214 } else if (object.isLOD) {
18215 if (object.autoUpdate === true) object.update(camera);
18216 } else if (object.isLight) {
18217 currentRenderState.pushLight(object);
18219 if (object.castShadow) {
18220 currentRenderState.pushShadow(object);
18222 } else if (object.isSprite) {
18223 if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
18225 _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
18228 var geometry = objects.update(object);
18229 var material = object.material;
18231 if (material.visible) {
18232 currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
18235 } else if (object.isImmediateRenderObject) {
18237 _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
18240 currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
18241 } else if (object.isMesh || object.isLine || object.isPoints) {
18242 if (object.isSkinnedMesh) {
18243 // update skeleton only once in a frame
18244 if (object.skeleton.frame !== info.render.frame) {
18245 object.skeleton.update();
18246 object.skeleton.frame = info.render.frame;
18250 if (!object.frustumCulled || _frustum.intersectsObject(object)) {
18252 _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
18255 var _geometry = objects.update(object);
18257 var _material = object.material;
18259 if (Array.isArray(_material)) {
18260 var groups = _geometry.groups;
18262 for (var i = 0, l = groups.length; i < l; i++) {
18263 var group = groups[i];
18264 var groupMaterial = _material[group.materialIndex];
18266 if (groupMaterial && groupMaterial.visible) {
18267 currentRenderList.push(object, _geometry, groupMaterial, groupOrder, _vector3.z, group);
18270 } else if (_material.visible) {
18271 currentRenderList.push(object, _geometry, _material, groupOrder, _vector3.z, null);
18277 var children = object.children;
18279 for (var _i = 0, _l = children.length; _i < _l; _i++) {
18280 projectObject(children[_i], camera, groupOrder, sortObjects);
18284 function renderObjects(renderList, scene, camera) {
18285 var overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
18287 for (var i = 0, l = renderList.length; i < l; i++) {
18288 var renderItem = renderList[i];
18289 var object = renderItem.object;
18290 var geometry = renderItem.geometry;
18291 var material = overrideMaterial === null ? renderItem.material : overrideMaterial;
18292 var group = renderItem.group;
18294 if (camera.isArrayCamera) {
18295 _currentArrayCamera = camera;
18296 var cameras = camera.cameras;
18298 for (var j = 0, jl = cameras.length; j < jl; j++) {
18299 var camera2 = cameras[j];
18301 if (object.layers.test(camera2.layers)) {
18302 state.viewport(_currentViewport.copy(camera2.viewport));
18303 currentRenderState.setupLights(camera2);
18304 renderObject(object, scene, camera2, geometry, material, group);
18308 _currentArrayCamera = null;
18309 renderObject(object, scene, camera, geometry, material, group);
18314 function renderObject(object, scene, camera, geometry, material, group) {
18315 object.onBeforeRender(_this, scene, camera, geometry, material, group);
18316 currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
18317 object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
18318 object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
18320 if (object.isImmediateRenderObject) {
18321 var program = setProgram(camera, scene, material, object);
18322 state.setMaterial(material);
18323 bindingStates.reset();
18324 renderObjectImmediate(object, program);
18326 _this.renderBufferDirect(camera, scene, geometry, material, object, group);
18329 object.onAfterRender(_this, scene, camera, geometry, material, group);
18330 currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
18333 function initMaterial(material, scene, object) {
18334 if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
18336 var materialProperties = properties.get(material);
18337 var lights = currentRenderState.state.lights;
18338 var shadowsArray = currentRenderState.state.shadowsArray;
18339 var lightsStateVersion = lights.state.version;
18340 var parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
18341 var programCacheKey = programCache.getProgramCacheKey(parameters);
18342 var program = materialProperties.program;
18343 var programChange = true;
18345 if (program === undefined) {
18347 material.addEventListener('dispose', onMaterialDispose);
18348 } else if (program.cacheKey !== programCacheKey) {
18349 // changed glsl or parameters
18350 releaseMaterialProgramReference(material);
18351 } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
18352 programChange = false;
18353 } else if (parameters.shaderID !== undefined) {
18354 // same glsl and uniform list, envMap still needs the update here to avoid a frame-late effect
18355 var environment = material.isMeshStandardMaterial ? scene.environment : null;
18356 materialProperties.envMap = cubemaps.get(material.envMap || environment);
18359 // only rebuild uniform list
18360 programChange = false;
18363 if (programChange) {
18364 parameters.uniforms = programCache.getUniforms(material);
18365 material.onBeforeCompile(parameters, _this);
18366 program = programCache.acquireProgram(parameters, programCacheKey);
18367 materialProperties.program = program;
18368 materialProperties.uniforms = parameters.uniforms;
18369 materialProperties.outputEncoding = parameters.outputEncoding;
18372 var uniforms = materialProperties.uniforms;
18374 if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
18375 materialProperties.numClippingPlanes = clipping.numPlanes;
18376 materialProperties.numIntersection = clipping.numIntersection;
18377 uniforms.clippingPlanes = clipping.uniform;
18380 materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
18381 materialProperties.fog = scene.fog;
18382 materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment); // store the light setup it was created for
18384 materialProperties.needsLights = materialNeedsLights(material);
18385 materialProperties.lightsStateVersion = lightsStateVersion;
18387 if (materialProperties.needsLights) {
18388 // wire up the material to this renderer's lighting state
18389 uniforms.ambientLightColor.value = lights.state.ambient;
18390 uniforms.lightProbe.value = lights.state.probe;
18391 uniforms.directionalLights.value = lights.state.directional;
18392 uniforms.directionalLightShadows.value = lights.state.directionalShadow;
18393 uniforms.spotLights.value = lights.state.spot;
18394 uniforms.spotLightShadows.value = lights.state.spotShadow;
18395 uniforms.rectAreaLights.value = lights.state.rectArea;
18396 uniforms.ltc_1.value = lights.state.rectAreaLTC1;
18397 uniforms.ltc_2.value = lights.state.rectAreaLTC2;
18398 uniforms.pointLights.value = lights.state.point;
18399 uniforms.pointLightShadows.value = lights.state.pointShadow;
18400 uniforms.hemisphereLights.value = lights.state.hemi;
18401 uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
18402 uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
18403 uniforms.spotShadowMap.value = lights.state.spotShadowMap;
18404 uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
18405 uniforms.pointShadowMap.value = lights.state.pointShadowMap;
18406 uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
18409 var progUniforms = materialProperties.program.getUniforms();
18410 var uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
18411 materialProperties.uniformsList = uniformsList;
18414 function setProgram(camera, scene, material, object) {
18415 if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
18417 textures.resetTextureUnits();
18418 var fog = scene.fog;
18419 var environment = material.isMeshStandardMaterial ? scene.environment : null;
18420 var encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
18421 var envMap = cubemaps.get(material.envMap || environment);
18422 var materialProperties = properties.get(material);
18423 var lights = currentRenderState.state.lights;
18425 if (_clippingEnabled === true) {
18426 if (_localClippingEnabled === true || camera !== _currentCamera) {
18427 var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
18428 // object instead of the material, once it becomes feasible
18431 clipping.setState(material, camera, useCache);
18435 if (material.version === materialProperties.__version) {
18436 if (material.fog && materialProperties.fog !== fog) {
18437 initMaterial(material, scene, object);
18438 } else if (materialProperties.environment !== environment) {
18439 initMaterial(material, scene, object);
18440 } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
18441 initMaterial(material, scene, object);
18442 } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
18443 initMaterial(material, scene, object);
18444 } else if (materialProperties.outputEncoding !== encoding) {
18445 initMaterial(material, scene, object);
18446 } else if (materialProperties.envMap !== envMap) {
18447 initMaterial(material, scene, object);
18450 initMaterial(material, scene, object);
18451 materialProperties.__version = material.version;
18454 var refreshProgram = false;
18455 var refreshMaterial = false;
18456 var refreshLights = false;
18457 var program = materialProperties.program,
18458 p_uniforms = program.getUniforms(),
18459 m_uniforms = materialProperties.uniforms;
18461 if (state.useProgram(program.program)) {
18462 refreshProgram = true;
18463 refreshMaterial = true;
18464 refreshLights = true;
18467 if (material.id !== _currentMaterialId) {
18468 _currentMaterialId = material.id;
18469 refreshMaterial = true;
18472 if (refreshProgram || _currentCamera !== camera) {
18473 p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
18475 if (capabilities.logarithmicDepthBuffer) {
18476 p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
18479 if (_currentCamera !== camera) {
18480 _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
18481 // now, in case this material supports lights - or later, when
18482 // the next material that does gets activated:
18484 refreshMaterial = true; // set to true on material change
18486 refreshLights = true; // remains set until update done
18487 } // load material specific uniforms
18488 // (shader material also gets them for the sake of genericity)
18491 if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
18492 var uCamPos = p_uniforms.map.cameraPosition;
18494 if (uCamPos !== undefined) {
18495 uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
18499 if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
18500 p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
18503 if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || material.skinning) {
18504 p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
18506 } // skinning uniforms must be set even if material didn't change
18507 // auto-setting of texture unit for bone texture must go before other textures
18508 // otherwise textures used for skinning can take over texture units reserved for other material textures
18511 if (material.skinning) {
18512 p_uniforms.setOptional(_gl, object, 'bindMatrix');
18513 p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
18514 var skeleton = object.skeleton;
18517 var bones = skeleton.bones;
18519 if (capabilities.floatVertexTextures) {
18520 if (skeleton.boneTexture === null) {
18521 // layout (1 matrix = 4 pixels)
18522 // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
18523 // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
18524 // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
18525 // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
18526 // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
18527 var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
18529 size = MathUtils.ceilPowerOfTwo(size);
18530 size = Math.max(size, 4);
18531 var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
18533 boneMatrices.set(skeleton.boneMatrices); // copy current values
18535 var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
18536 skeleton.boneMatrices = boneMatrices;
18537 skeleton.boneTexture = boneTexture;
18538 skeleton.boneTextureSize = size;
18541 p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
18542 p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
18544 p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
18549 if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
18550 materialProperties.receiveShadow = object.receiveShadow;
18551 p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
18554 if (refreshMaterial) {
18555 p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
18557 if (materialProperties.needsLights) {
18558 // the current material requires lighting info
18559 // note: all lighting uniforms are always set correctly
18560 // they simply reference the renderer's state for their
18563 // use the current material's .needsUpdate flags to set
18564 // the GL state when required
18565 markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
18566 } // refresh uniforms common to several materials
18569 if (fog && material.fog) {
18570 materials.refreshFogUniforms(m_uniforms, fog);
18573 materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height);
18574 WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
18577 if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
18578 WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
18579 material.uniformsNeedUpdate = false;
18582 if (material.isSpriteMaterial) {
18583 p_uniforms.setValue(_gl, 'center', object.center);
18584 } // common matrices
18587 p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
18588 p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
18589 p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
18591 } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
18594 function markUniformsLightsNeedsUpdate(uniforms, value) {
18595 uniforms.ambientLightColor.needsUpdate = value;
18596 uniforms.lightProbe.needsUpdate = value;
18597 uniforms.directionalLights.needsUpdate = value;
18598 uniforms.directionalLightShadows.needsUpdate = value;
18599 uniforms.pointLights.needsUpdate = value;
18600 uniforms.pointLightShadows.needsUpdate = value;
18601 uniforms.spotLights.needsUpdate = value;
18602 uniforms.spotLightShadows.needsUpdate = value;
18603 uniforms.rectAreaLights.needsUpdate = value;
18604 uniforms.hemisphereLights.needsUpdate = value;
18607 function materialNeedsLights(material) {
18608 return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
18612 this.setFramebuffer = function (value) {
18613 if (_framebuffer !== value && _currentRenderTarget === null) _gl.bindFramebuffer(36160, value);
18614 _framebuffer = value;
18617 this.getActiveCubeFace = function () {
18618 return _currentActiveCubeFace;
18621 this.getActiveMipmapLevel = function () {
18622 return _currentActiveMipmapLevel;
18625 this.getRenderList = function () {
18626 return currentRenderList;
18629 this.setRenderList = function (renderList) {
18630 currentRenderList = renderList;
18633 this.getRenderState = function () {
18634 return currentRenderState;
18637 this.setRenderState = function (renderState) {
18638 currentRenderState = renderState;
18641 this.getRenderTarget = function () {
18642 return _currentRenderTarget;
18645 this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
18646 if (activeCubeFace === void 0) {
18647 activeCubeFace = 0;
18650 if (activeMipmapLevel === void 0) {
18651 activeMipmapLevel = 0;
18654 _currentRenderTarget = renderTarget;
18655 _currentActiveCubeFace = activeCubeFace;
18656 _currentActiveMipmapLevel = activeMipmapLevel;
18658 if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
18659 textures.setupRenderTarget(renderTarget);
18662 var framebuffer = _framebuffer;
18663 var isCube = false;
18665 if (renderTarget) {
18666 var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
18668 if (renderTarget.isWebGLCubeRenderTarget) {
18669 framebuffer = __webglFramebuffer[activeCubeFace];
18671 } else if (renderTarget.isWebGLMultisampleRenderTarget) {
18672 framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
18674 framebuffer = __webglFramebuffer;
18677 _currentViewport.copy(renderTarget.viewport);
18679 _currentScissor.copy(renderTarget.scissor);
18681 _currentScissorTest = renderTarget.scissorTest;
18683 _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
18685 _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
18687 _currentScissorTest = _scissorTest;
18690 if (_currentFramebuffer !== framebuffer) {
18691 _gl.bindFramebuffer(36160, framebuffer);
18693 _currentFramebuffer = framebuffer;
18696 state.viewport(_currentViewport);
18697 state.scissor(_currentScissor);
18698 state.setScissorTest(_currentScissorTest);
18701 var textureProperties = properties.get(renderTarget.texture);
18703 _gl.framebufferTexture2D(36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
18707 this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
18708 if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
18709 console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
18713 var framebuffer = properties.get(renderTarget).__webglFramebuffer;
18715 if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
18716 framebuffer = framebuffer[activeCubeFaceIndex];
18720 var restore = false;
18722 if (framebuffer !== _currentFramebuffer) {
18723 _gl.bindFramebuffer(36160, framebuffer);
18729 var texture = renderTarget.texture;
18730 var textureFormat = texture.format;
18731 var textureType = texture.type;
18733 if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
18734 console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
18738 if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
18739 !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
18740 !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
18741 console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
18745 if (_gl.checkFramebufferStatus(36160) === 36053) {
18746 // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
18747 if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
18748 _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
18751 console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
18755 _gl.bindFramebuffer(36160, _currentFramebuffer);
18761 this.copyFramebufferToTexture = function (position, texture, level) {
18762 if (level === void 0) {
18766 var levelScale = Math.pow(2, -level);
18767 var width = Math.floor(texture.image.width * levelScale);
18768 var height = Math.floor(texture.image.height * levelScale);
18769 var glFormat = utils.convert(texture.format);
18770 textures.setTexture2D(texture, 0);
18772 _gl.copyTexImage2D(3553, level, glFormat, position.x, position.y, width, height, 0);
18774 state.unbindTexture();
18777 this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
18778 if (level === void 0) {
18782 var width = srcTexture.image.width;
18783 var height = srcTexture.image.height;
18784 var glFormat = utils.convert(dstTexture.format);
18785 var glType = utils.convert(dstTexture.type);
18786 textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
18787 // parameters, make sure they are correct for the dstTexture
18789 _gl.pixelStorei(37440, dstTexture.flipY);
18791 _gl.pixelStorei(37441, dstTexture.premultiplyAlpha);
18793 _gl.pixelStorei(3317, dstTexture.unpackAlignment);
18795 if (srcTexture.isDataTexture) {
18796 _gl.texSubImage2D(3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
18798 if (srcTexture.isCompressedTexture) {
18799 _gl.compressedTexSubImage2D(3553, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
18801 _gl.texSubImage2D(3553, level, position.x, position.y, glFormat, glType, srcTexture.image);
18803 } // Generate mipmaps only when copying level 0
18806 if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(3553);
18807 state.unbindTexture();
18810 this.initTexture = function (texture) {
18811 textures.setTexture2D(texture, 0);
18812 state.unbindTexture();
18815 if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
18816 __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
18818 })); // eslint-disable-line no-undef
18823 function WebGL1Renderer(parameters) {
18824 WebGLRenderer.call(this, parameters);
18827 WebGL1Renderer.prototype = Object.assign(Object.create(WebGLRenderer.prototype), {
18828 constructor: WebGL1Renderer,
18829 isWebGL1Renderer: true
18832 var FogExp2 = /*#__PURE__*/function () {
18833 function FogExp2(color, density) {
18834 Object.defineProperty(this, 'isFogExp2', {
18838 this.color = new Color(color);
18839 this.density = density !== undefined ? density : 0.00025;
18842 var _proto = FogExp2.prototype;
18844 _proto.clone = function clone() {
18845 return new FogExp2(this.color, this.density);
18848 _proto.toJSON = function toJSON()
18853 color: this.color.getHex(),
18854 density: this.density
18861 var Fog = /*#__PURE__*/function () {
18862 function Fog(color, near, far) {
18863 Object.defineProperty(this, 'isFog', {
18867 this.color = new Color(color);
18868 this.near = near !== undefined ? near : 1;
18869 this.far = far !== undefined ? far : 1000;
18872 var _proto = Fog.prototype;
18874 _proto.clone = function clone() {
18875 return new Fog(this.color, this.near, this.far);
18878 _proto.toJSON = function toJSON()
18883 color: this.color.getHex(),
18892 var Scene = /*#__PURE__*/function (_Object3D) {
18893 _inheritsLoose(Scene, _Object3D);
18898 _this = _Object3D.call(this) || this;
18899 Object.defineProperty(_assertThisInitialized(_this), 'isScene', {
18902 _this.type = 'Scene';
18903 _this.background = null;
18904 _this.environment = null;
18906 _this.overrideMaterial = null;
18907 _this.autoUpdate = true; // checked by the renderer
18909 if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
18910 __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
18911 detail: _assertThisInitialized(_this)
18912 })); // eslint-disable-line no-undef
18919 var _proto = Scene.prototype;
18921 _proto.copy = function copy(source, recursive) {
18922 _Object3D.prototype.copy.call(this, source, recursive);
18924 if (source.background !== null) this.background = source.background.clone();
18925 if (source.environment !== null) this.environment = source.environment.clone();
18926 if (source.fog !== null) this.fog = source.fog.clone();
18927 if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
18928 this.autoUpdate = source.autoUpdate;
18929 this.matrixAutoUpdate = source.matrixAutoUpdate;
18933 _proto.toJSON = function toJSON(meta) {
18934 var data = _Object3D.prototype.toJSON.call(this, meta);
18936 if (this.background !== null) data.object.background = this.background.toJSON(meta);
18937 if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
18938 if (this.fog !== null) data.object.fog = this.fog.toJSON();
18945 function InterleavedBuffer(array, stride) {
18946 this.array = array;
18947 this.stride = stride;
18948 this.count = array !== undefined ? array.length / stride : 0;
18949 this.usage = StaticDrawUsage;
18950 this.updateRange = {
18955 this.uuid = MathUtils.generateUUID();
18958 Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
18959 set: function set(value) {
18960 if (value === true) this.version++;
18963 Object.assign(InterleavedBuffer.prototype, {
18964 isInterleavedBuffer: true,
18965 onUploadCallback: function onUploadCallback() {},
18966 setUsage: function setUsage(value) {
18967 this.usage = value;
18970 copy: function copy(source) {
18971 this.array = new source.array.constructor(source.array);
18972 this.count = source.count;
18973 this.stride = source.stride;
18974 this.usage = source.usage;
18977 copyAt: function copyAt(index1, attribute, index2) {
18978 index1 *= this.stride;
18979 index2 *= attribute.stride;
18981 for (var i = 0, l = this.stride; i < l; i++) {
18982 this.array[index1 + i] = attribute.array[index2 + i];
18987 set: function set(value, offset) {
18988 if (offset === void 0) {
18992 this.array.set(value, offset);
18995 clone: function clone(data) {
18996 if (data.arrayBuffers === undefined) {
18997 data.arrayBuffers = {};
19000 if (this.array.buffer._uuid === undefined) {
19001 this.array.buffer._uuid = MathUtils.generateUUID();
19004 if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
19005 data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
19008 var array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
19009 var ib = new InterleavedBuffer(array, this.stride);
19010 ib.setUsage(this.usage);
19013 onUpload: function onUpload(callback) {
19014 this.onUploadCallback = callback;
19017 toJSON: function toJSON(data) {
19018 if (data.arrayBuffers === undefined) {
19019 data.arrayBuffers = {};
19020 } // generate UUID for array buffer if necessary
19023 if (this.array.buffer._uuid === undefined) {
19024 this.array.buffer._uuid = MathUtils.generateUUID();
19027 if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
19028 data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
19034 buffer: this.array.buffer._uuid,
19035 type: this.array.constructor.name,
19036 stride: this.stride
19041 var _vector$6 = new Vector3();
19043 function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
19045 this.data = interleavedBuffer;
19046 this.itemSize = itemSize;
19047 this.offset = offset;
19048 this.normalized = normalized === true;
19051 Object.defineProperties(InterleavedBufferAttribute.prototype, {
19053 get: function get() {
19054 return this.data.count;
19058 get: function get() {
19059 return this.data.array;
19063 set: function set(value) {
19064 this.data.needsUpdate = value;
19068 Object.assign(InterleavedBufferAttribute.prototype, {
19069 isInterleavedBufferAttribute: true,
19070 applyMatrix4: function applyMatrix4(m) {
19071 for (var i = 0, l = this.data.count; i < l; i++) {
19072 _vector$6.x = this.getX(i);
19073 _vector$6.y = this.getY(i);
19074 _vector$6.z = this.getZ(i);
19076 _vector$6.applyMatrix4(m);
19078 this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
19083 setX: function setX(index, x) {
19084 this.data.array[index * this.data.stride + this.offset] = x;
19087 setY: function setY(index, y) {
19088 this.data.array[index * this.data.stride + this.offset + 1] = y;
19091 setZ: function setZ(index, z) {
19092 this.data.array[index * this.data.stride + this.offset + 2] = z;
19095 setW: function setW(index, w) {
19096 this.data.array[index * this.data.stride + this.offset + 3] = w;
19099 getX: function getX(index) {
19100 return this.data.array[index * this.data.stride + this.offset];
19102 getY: function getY(index) {
19103 return this.data.array[index * this.data.stride + this.offset + 1];
19105 getZ: function getZ(index) {
19106 return this.data.array[index * this.data.stride + this.offset + 2];
19108 getW: function getW(index) {
19109 return this.data.array[index * this.data.stride + this.offset + 3];
19111 setXY: function setXY(index, x, y) {
19112 index = index * this.data.stride + this.offset;
19113 this.data.array[index + 0] = x;
19114 this.data.array[index + 1] = y;
19117 setXYZ: function setXYZ(index, x, y, z) {
19118 index = index * this.data.stride + this.offset;
19119 this.data.array[index + 0] = x;
19120 this.data.array[index + 1] = y;
19121 this.data.array[index + 2] = z;
19124 setXYZW: function setXYZW(index, x, y, z, w) {
19125 index = index * this.data.stride + this.offset;
19126 this.data.array[index + 0] = x;
19127 this.data.array[index + 1] = y;
19128 this.data.array[index + 2] = z;
19129 this.data.array[index + 3] = w;
19132 clone: function clone(data) {
19133 if (data === undefined) {
19134 console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
19137 for (var i = 0; i < this.count; i++) {
19138 var index = i * this.data.stride + this.offset;
19140 for (var j = 0; j < this.itemSize; j++) {
19141 array.push(this.data.array[index + j]);
19145 return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
19147 if (data.interleavedBuffers === undefined) {
19148 data.interleavedBuffers = {};
19151 if (data.interleavedBuffers[this.data.uuid] === undefined) {
19152 data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
19155 return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
19158 toJSON: function toJSON(data) {
19159 if (data === undefined) {
19160 console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
19163 for (var i = 0; i < this.count; i++) {
19164 var index = i * this.data.stride + this.offset;
19166 for (var j = 0; j < this.itemSize; j++) {
19167 array.push(this.data.array[index + j]);
19169 } // deinterleave data and save it as an ordinary buffer attribute for now
19173 itemSize: this.itemSize,
19174 type: this.array.constructor.name,
19176 normalized: this.normalized
19179 // save as true interlaved attribtue
19180 if (data.interleavedBuffers === undefined) {
19181 data.interleavedBuffers = {};
19184 if (data.interleavedBuffers[this.data.uuid] === undefined) {
19185 data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
19189 isInterleavedBufferAttribute: true,
19190 itemSize: this.itemSize,
19191 data: this.data.uuid,
19192 offset: this.offset,
19193 normalized: this.normalized
19202 * map: new THREE.Texture( <Image> ),
19203 * alphaMap: new THREE.Texture( <Image> ),
19204 * rotation: <float>,
19205 * sizeAttenuation: <bool>
19209 function SpriteMaterial(parameters) {
19210 Material.call(this);
19211 this.type = 'SpriteMaterial';
19212 this.color = new Color(0xffffff);
19214 this.alphaMap = null;
19216 this.sizeAttenuation = true;
19217 this.transparent = true;
19218 this.setValues(parameters);
19221 SpriteMaterial.prototype = Object.create(Material.prototype);
19222 SpriteMaterial.prototype.constructor = SpriteMaterial;
19223 SpriteMaterial.prototype.isSpriteMaterial = true;
19225 SpriteMaterial.prototype.copy = function (source) {
19226 Material.prototype.copy.call(this, source);
19227 this.color.copy(source.color);
19228 this.map = source.map;
19229 this.alphaMap = source.alphaMap;
19230 this.rotation = source.rotation;
19231 this.sizeAttenuation = source.sizeAttenuation;
19237 var _intersectPoint = new Vector3();
19239 var _worldScale = new Vector3();
19241 var _mvPosition = new Vector3();
19243 var _alignedPosition = new Vector2();
19245 var _rotatedPosition = new Vector2();
19247 var _viewWorldMatrix = new Matrix4();
19249 var _vA$1 = new Vector3();
19251 var _vB$1 = new Vector3();
19253 var _vC$1 = new Vector3();
19255 var _uvA$1 = new Vector2();
19257 var _uvB$1 = new Vector2();
19259 var _uvC$1 = new Vector2();
19261 function Sprite(material) {
19262 Object3D.call(this);
19263 this.type = 'Sprite';
19265 if (_geometry === undefined) {
19266 _geometry = new BufferGeometry();
19267 var 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]);
19268 var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
19270 _geometry.setIndex([0, 1, 2, 0, 2, 3]);
19272 _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
19274 _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
19277 this.geometry = _geometry;
19278 this.material = material !== undefined ? material : new SpriteMaterial();
19279 this.center = new Vector2(0.5, 0.5);
19282 Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
19283 constructor: Sprite,
19285 raycast: function raycast(raycaster, intersects) {
19286 if (raycaster.camera === null) {
19287 console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
19290 _worldScale.setFromMatrixScale(this.matrixWorld);
19292 _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
19294 this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
19296 _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
19298 if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
19299 _worldScale.multiplyScalar(-_mvPosition.z);
19302 var rotation = this.material.rotation;
19305 if (rotation !== 0) {
19306 cos = Math.cos(rotation);
19307 sin = Math.sin(rotation);
19310 var center = this.center;
19311 transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
19312 transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
19313 transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
19319 _uvC$1.set(1, 1); // check first triangle
19322 var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
19324 if (intersect === null) {
19325 // check second triangle
19326 transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
19330 intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
19332 if (intersect === null) {
19337 var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
19338 if (distance < raycaster.near || distance > raycaster.far) return;
19340 distance: distance,
19341 point: _intersectPoint.clone(),
19342 uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
19347 copy: function copy(source) {
19348 Object3D.prototype.copy.call(this, source);
19349 if (source.center !== undefined) this.center.copy(source.center);
19350 this.material = source.material;
19355 function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
19356 // compute position in camera space
19357 _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
19360 if (sin !== undefined) {
19361 _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
19362 _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
19364 _rotatedPosition.copy(_alignedPosition);
19367 vertexPosition.copy(mvPosition);
19368 vertexPosition.x += _rotatedPosition.x;
19369 vertexPosition.y += _rotatedPosition.y; // transform to world space
19371 vertexPosition.applyMatrix4(_viewWorldMatrix);
19374 var _v1$4 = new Vector3();
19376 var _v2$2 = new Vector3();
19379 Object3D.call(this);
19380 this._currentLevel = 0;
19382 Object.defineProperties(this, {
19388 this.autoUpdate = true;
19391 LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
19394 copy: function copy(source) {
19395 Object3D.prototype.copy.call(this, source, false);
19396 var levels = source.levels;
19398 for (var i = 0, l = levels.length; i < l; i++) {
19399 var level = levels[i];
19400 this.addLevel(level.object.clone(), level.distance);
19403 this.autoUpdate = source.autoUpdate;
19406 addLevel: function addLevel(object, distance) {
19407 if (distance === void 0) {
19411 distance = Math.abs(distance);
19412 var levels = this.levels;
19415 for (l = 0; l < levels.length; l++) {
19416 if (distance < levels[l].distance) {
19421 levels.splice(l, 0, {
19422 distance: distance,
19428 getCurrentLevel: function getCurrentLevel() {
19429 return this._currentLevel;
19431 getObjectForDistance: function getObjectForDistance(distance) {
19432 var levels = this.levels;
19434 if (levels.length > 0) {
19437 for (i = 1, l = levels.length; i < l; i++) {
19438 if (distance < levels[i].distance) {
19443 return levels[i - 1].object;
19448 raycast: function raycast(raycaster, intersects) {
19449 var levels = this.levels;
19451 if (levels.length > 0) {
19452 _v1$4.setFromMatrixPosition(this.matrixWorld);
19454 var distance = raycaster.ray.origin.distanceTo(_v1$4);
19455 this.getObjectForDistance(distance).raycast(raycaster, intersects);
19458 update: function update(camera) {
19459 var levels = this.levels;
19461 if (levels.length > 1) {
19462 _v1$4.setFromMatrixPosition(camera.matrixWorld);
19464 _v2$2.setFromMatrixPosition(this.matrixWorld);
19466 var distance = _v1$4.distanceTo(_v2$2) / camera.zoom;
19467 levels[0].object.visible = true;
19470 for (i = 1, l = levels.length; i < l; i++) {
19471 if (distance >= levels[i].distance) {
19472 levels[i - 1].object.visible = false;
19473 levels[i].object.visible = true;
19479 this._currentLevel = i - 1;
19481 for (; i < l; i++) {
19482 levels[i].object.visible = false;
19486 toJSON: function toJSON(meta) {
19487 var data = Object3D.prototype.toJSON.call(this, meta);
19488 if (this.autoUpdate === false) data.object.autoUpdate = false;
19489 data.object.levels = [];
19490 var levels = this.levels;
19492 for (var i = 0, l = levels.length; i < l; i++) {
19493 var level = levels[i];
19494 data.object.levels.push({
19495 object: level.object.uuid,
19496 distance: level.distance
19504 function SkinnedMesh(geometry, material) {
19505 if (geometry && geometry.isGeometry) {
19506 console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
19509 Mesh.call(this, geometry, material);
19510 this.type = 'SkinnedMesh';
19511 this.bindMode = 'attached';
19512 this.bindMatrix = new Matrix4();
19513 this.bindMatrixInverse = new Matrix4();
19516 SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
19517 constructor: SkinnedMesh,
19518 isSkinnedMesh: true,
19519 copy: function copy(source) {
19520 Mesh.prototype.copy.call(this, source);
19521 this.bindMode = source.bindMode;
19522 this.bindMatrix.copy(source.bindMatrix);
19523 this.bindMatrixInverse.copy(source.bindMatrixInverse);
19524 this.skeleton = source.skeleton;
19527 bind: function bind(skeleton, bindMatrix) {
19528 this.skeleton = skeleton;
19530 if (bindMatrix === undefined) {
19531 this.updateMatrixWorld(true);
19532 this.skeleton.calculateInverses();
19533 bindMatrix = this.matrixWorld;
19536 this.bindMatrix.copy(bindMatrix);
19537 this.bindMatrixInverse.copy(bindMatrix).invert();
19539 pose: function pose() {
19540 this.skeleton.pose();
19542 normalizeSkinWeights: function normalizeSkinWeights() {
19543 var vector = new Vector4();
19544 var skinWeight = this.geometry.attributes.skinWeight;
19546 for (var i = 0, l = skinWeight.count; i < l; i++) {
19547 vector.x = skinWeight.getX(i);
19548 vector.y = skinWeight.getY(i);
19549 vector.z = skinWeight.getZ(i);
19550 vector.w = skinWeight.getW(i);
19551 var scale = 1.0 / vector.manhattanLength();
19553 if (scale !== Infinity) {
19554 vector.multiplyScalar(scale);
19556 vector.set(1, 0, 0, 0); // do something reasonable
19559 skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
19562 updateMatrixWorld: function updateMatrixWorld(force) {
19563 Mesh.prototype.updateMatrixWorld.call(this, force);
19565 if (this.bindMode === 'attached') {
19566 this.bindMatrixInverse.copy(this.matrixWorld).invert();
19567 } else if (this.bindMode === 'detached') {
19568 this.bindMatrixInverse.copy(this.bindMatrix).invert();
19570 console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
19573 boneTransform: function () {
19574 var basePosition = new Vector3();
19575 var skinIndex = new Vector4();
19576 var skinWeight = new Vector4();
19577 var vector = new Vector3();
19578 var matrix = new Matrix4();
19579 return function (index, target) {
19580 var skeleton = this.skeleton;
19581 var geometry = this.geometry;
19582 skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
19583 skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
19584 basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
19585 target.set(0, 0, 0);
19587 for (var i = 0; i < 4; i++) {
19588 var weight = skinWeight.getComponent(i);
19590 if (weight !== 0) {
19591 var boneIndex = skinIndex.getComponent(i);
19592 matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
19593 target.addScaledVector(vector.copy(basePosition).applyMatrix4(matrix), weight);
19597 return target.applyMatrix4(this.bindMatrixInverse);
19603 Object3D.call(this);
19604 this.type = 'Bone';
19607 Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
19612 var _offsetMatrix = new Matrix4();
19614 var _identityMatrix = new Matrix4();
19616 function Skeleton(bones, boneInverses) {
19617 if (bones === void 0) {
19621 if (boneInverses === void 0) {
19625 this.uuid = MathUtils.generateUUID();
19626 this.bones = bones.slice(0);
19627 this.boneInverses = boneInverses;
19628 this.boneMatrices = null;
19629 this.boneTexture = null;
19630 this.boneTextureSize = 0;
19635 Object.assign(Skeleton.prototype, {
19636 init: function init() {
19637 var bones = this.bones;
19638 var boneInverses = this.boneInverses;
19639 this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
19641 if (boneInverses.length === 0) {
19642 this.calculateInverses();
19644 // handle special case
19645 if (bones.length !== boneInverses.length) {
19646 console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
19647 this.boneInverses = [];
19649 for (var i = 0, il = this.bones.length; i < il; i++) {
19650 this.boneInverses.push(new Matrix4());
19655 calculateInverses: function calculateInverses() {
19656 this.boneInverses.length = 0;
19658 for (var i = 0, il = this.bones.length; i < il; i++) {
19659 var inverse = new Matrix4();
19661 if (this.bones[i]) {
19662 inverse.copy(this.bones[i].matrixWorld).invert();
19665 this.boneInverses.push(inverse);
19668 pose: function pose() {
19669 // recover the bind-time world matrices
19670 for (var i = 0, il = this.bones.length; i < il; i++) {
19671 var bone = this.bones[i];
19674 bone.matrixWorld.copy(this.boneInverses[i]).invert();
19676 } // compute the local matrices, positions, rotations and scales
19679 for (var _i = 0, _il = this.bones.length; _i < _il; _i++) {
19680 var _bone = this.bones[_i];
19683 if (_bone.parent && _bone.parent.isBone) {
19684 _bone.matrix.copy(_bone.parent.matrixWorld).invert();
19686 _bone.matrix.multiply(_bone.matrixWorld);
19688 _bone.matrix.copy(_bone.matrixWorld);
19691 _bone.matrix.decompose(_bone.position, _bone.quaternion, _bone.scale);
19695 update: function update() {
19696 var bones = this.bones;
19697 var boneInverses = this.boneInverses;
19698 var boneMatrices = this.boneMatrices;
19699 var boneTexture = this.boneTexture; // flatten bone matrices to array
19701 for (var i = 0, il = bones.length; i < il; i++) {
19702 // compute the offset between the current and the original transform
19703 var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
19705 _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
19707 _offsetMatrix.toArray(boneMatrices, i * 16);
19710 if (boneTexture !== null) {
19711 boneTexture.needsUpdate = true;
19714 clone: function clone() {
19715 return new Skeleton(this.bones, this.boneInverses);
19717 getBoneByName: function getBoneByName(name) {
19718 for (var i = 0, il = this.bones.length; i < il; i++) {
19719 var bone = this.bones[i];
19721 if (bone.name === name) {
19728 dispose: function dispose() {
19729 if (this.boneTexture !== null) {
19730 this.boneTexture.dispose();
19731 this.boneTexture = null;
19734 fromJSON: function fromJSON(json, bones) {
19735 this.uuid = json.uuid;
19737 for (var i = 0, l = json.bones.length; i < l; i++) {
19738 var uuid = json.bones[i];
19739 var bone = bones[uuid];
19741 if (bone === undefined) {
19742 console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
19746 this.bones.push(bone);
19747 this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
19753 toJSON: function toJSON() {
19758 generator: 'Skeleton.toJSON'
19763 data.uuid = this.uuid;
19764 var bones = this.bones;
19765 var boneInverses = this.boneInverses;
19767 for (var i = 0, l = bones.length; i < l; i++) {
19768 var bone = bones[i];
19769 data.bones.push(bone.uuid);
19770 var boneInverse = boneInverses[i];
19771 data.boneInverses.push(boneInverse.toArray());
19778 var _instanceLocalMatrix = new Matrix4();
19780 var _instanceWorldMatrix = new Matrix4();
19782 var _instanceIntersects = [];
19784 var _mesh = new Mesh();
19786 function InstancedMesh(geometry, material, count) {
19787 Mesh.call(this, geometry, material);
19788 this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
19789 this.instanceColor = null;
19790 this.count = count;
19791 this.frustumCulled = false;
19794 InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
19795 constructor: InstancedMesh,
19796 isInstancedMesh: true,
19797 copy: function copy(source) {
19798 Mesh.prototype.copy.call(this, source);
19799 this.instanceMatrix.copy(source.instanceMatrix);
19800 this.count = source.count;
19803 getColorAt: function getColorAt(index, color) {
19804 color.fromArray(this.instanceColor.array, index * 3);
19806 getMatrixAt: function getMatrixAt(index, matrix) {
19807 matrix.fromArray(this.instanceMatrix.array, index * 16);
19809 raycast: function raycast(raycaster, intersects) {
19810 var matrixWorld = this.matrixWorld;
19811 var raycastTimes = this.count;
19812 _mesh.geometry = this.geometry;
19813 _mesh.material = this.material;
19814 if (_mesh.material === undefined) return;
19816 for (var instanceId = 0; instanceId < raycastTimes; instanceId++) {
19817 // calculate the world matrix for each instance
19818 this.getMatrixAt(instanceId, _instanceLocalMatrix);
19820 _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
19823 _mesh.matrixWorld = _instanceWorldMatrix;
19825 _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
19828 for (var i = 0, l = _instanceIntersects.length; i < l; i++) {
19829 var intersect = _instanceIntersects[i];
19830 intersect.instanceId = instanceId;
19831 intersect.object = this;
19832 intersects.push(intersect);
19835 _instanceIntersects.length = 0;
19838 setColorAt: function setColorAt(index, color) {
19839 if (this.instanceColor === null) {
19840 this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
19843 color.toArray(this.instanceColor.array, index * 3);
19845 setMatrixAt: function setMatrixAt(index, matrix) {
19846 matrix.toArray(this.instanceMatrix.array, index * 16);
19848 updateMorphTargets: function updateMorphTargets() {}
19854 * opacity: <float>,
19856 * linewidth: <float>,
19857 * linecap: "round",
19858 * linejoin: "round"
19862 function LineBasicMaterial(parameters) {
19863 Material.call(this);
19864 this.type = 'LineBasicMaterial';
19865 this.color = new Color(0xffffff);
19866 this.linewidth = 1;
19867 this.linecap = 'round';
19868 this.linejoin = 'round';
19869 this.morphTargets = false;
19870 this.setValues(parameters);
19873 LineBasicMaterial.prototype = Object.create(Material.prototype);
19874 LineBasicMaterial.prototype.constructor = LineBasicMaterial;
19875 LineBasicMaterial.prototype.isLineBasicMaterial = true;
19877 LineBasicMaterial.prototype.copy = function (source) {
19878 Material.prototype.copy.call(this, source);
19879 this.color.copy(source.color);
19880 this.linewidth = source.linewidth;
19881 this.linecap = source.linecap;
19882 this.linejoin = source.linejoin;
19883 this.morphTargets = source.morphTargets;
19887 var _start = new Vector3();
19889 var _end = new Vector3();
19891 var _inverseMatrix$1 = new Matrix4();
19893 var _ray$1 = new Ray();
19895 var _sphere$2 = new Sphere();
19897 function Line(geometry, material, mode) {
19899 console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
19902 Object3D.call(this);
19903 this.type = 'Line';
19904 this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
19905 this.material = material !== undefined ? material : new LineBasicMaterial();
19906 this.updateMorphTargets();
19909 Line.prototype = Object.assign(Object.create(Object3D.prototype), {
19912 copy: function copy(source) {
19913 Object3D.prototype.copy.call(this, source);
19914 this.material = source.material;
19915 this.geometry = source.geometry;
19918 computeLineDistances: function computeLineDistances() {
19919 var geometry = this.geometry;
19921 if (geometry.isBufferGeometry) {
19922 // we assume non-indexed geometry
19923 if (geometry.index === null) {
19924 var positionAttribute = geometry.attributes.position;
19925 var lineDistances = [0];
19927 for (var i = 1, l = positionAttribute.count; i < l; i++) {
19928 _start.fromBufferAttribute(positionAttribute, i - 1);
19930 _end.fromBufferAttribute(positionAttribute, i);
19932 lineDistances[i] = lineDistances[i - 1];
19933 lineDistances[i] += _start.distanceTo(_end);
19936 geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
19938 console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
19940 } else if (geometry.isGeometry) {
19941 var vertices = geometry.vertices;
19942 var _lineDistances = geometry.lineDistances;
19943 _lineDistances[0] = 0;
19945 for (var _i = 1, _l = vertices.length; _i < _l; _i++) {
19946 _lineDistances[_i] = _lineDistances[_i - 1];
19947 _lineDistances[_i] += vertices[_i - 1].distanceTo(vertices[_i]);
19953 raycast: function raycast(raycaster, intersects) {
19954 var geometry = this.geometry;
19955 var matrixWorld = this.matrixWorld;
19956 var threshold = raycaster.params.Line.threshold; // Checking boundingSphere distance to ray
19958 if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
19960 _sphere$2.copy(geometry.boundingSphere);
19962 _sphere$2.applyMatrix4(matrixWorld);
19964 _sphere$2.radius += threshold;
19965 if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
19967 _inverseMatrix$1.copy(matrixWorld).invert();
19969 _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
19971 var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
19972 var localThresholdSq = localThreshold * localThreshold;
19973 var vStart = new Vector3();
19974 var vEnd = new Vector3();
19975 var interSegment = new Vector3();
19976 var interRay = new Vector3();
19977 var step = this.isLineSegments ? 2 : 1;
19979 if (geometry.isBufferGeometry) {
19980 var index = geometry.index;
19981 var attributes = geometry.attributes;
19982 var positionAttribute = attributes.position;
19984 if (index !== null) {
19985 var indices = index.array;
19987 for (var i = 0, l = indices.length - 1; i < l; i += step) {
19988 var a = indices[i];
19989 var b = indices[i + 1];
19990 vStart.fromBufferAttribute(positionAttribute, a);
19991 vEnd.fromBufferAttribute(positionAttribute, b);
19993 var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
19995 if (distSq > localThresholdSq) continue;
19996 interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
19998 var distance = raycaster.ray.origin.distanceTo(interRay);
19999 if (distance < raycaster.near || distance > raycaster.far) continue;
20001 distance: distance,
20002 // What do we want? intersection point on the ray or on the segment??
20003 // point: raycaster.ray.at( distance ),
20004 point: interSegment.clone().applyMatrix4(this.matrixWorld),
20012 for (var _i2 = 0, _l2 = positionAttribute.count - 1; _i2 < _l2; _i2 += step) {
20013 vStart.fromBufferAttribute(positionAttribute, _i2);
20014 vEnd.fromBufferAttribute(positionAttribute, _i2 + 1);
20016 var _distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
20018 if (_distSq > localThresholdSq) continue;
20019 interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
20021 var _distance = raycaster.ray.origin.distanceTo(interRay);
20023 if (_distance < raycaster.near || _distance > raycaster.far) continue;
20025 distance: _distance,
20026 // What do we want? intersection point on the ray or on the segment??
20027 // point: raycaster.ray.at( distance ),
20028 point: interSegment.clone().applyMatrix4(this.matrixWorld),
20036 } else if (geometry.isGeometry) {
20037 var vertices = geometry.vertices;
20038 var nbVertices = vertices.length;
20040 for (var _i3 = 0; _i3 < nbVertices - 1; _i3 += step) {
20041 var _distSq2 = _ray$1.distanceSqToSegment(vertices[_i3], vertices[_i3 + 1], interRay, interSegment);
20043 if (_distSq2 > localThresholdSq) continue;
20044 interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
20046 var _distance2 = raycaster.ray.origin.distanceTo(interRay);
20048 if (_distance2 < raycaster.near || _distance2 > raycaster.far) continue;
20050 distance: _distance2,
20051 // What do we want? intersection point on the ray or on the segment??
20052 // point: raycaster.ray.at( distance ),
20053 point: interSegment.clone().applyMatrix4(this.matrixWorld),
20062 updateMorphTargets: function updateMorphTargets() {
20063 var geometry = this.geometry;
20065 if (geometry.isBufferGeometry) {
20066 var morphAttributes = geometry.morphAttributes;
20067 var keys = Object.keys(morphAttributes);
20069 if (keys.length > 0) {
20070 var morphAttribute = morphAttributes[keys[0]];
20072 if (morphAttribute !== undefined) {
20073 this.morphTargetInfluences = [];
20074 this.morphTargetDictionary = {};
20076 for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
20077 var name = morphAttribute[m].name || String(m);
20078 this.morphTargetInfluences.push(0);
20079 this.morphTargetDictionary[name] = m;
20084 var morphTargets = geometry.morphTargets;
20086 if (morphTargets !== undefined && morphTargets.length > 0) {
20087 console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
20093 var _start$1 = new Vector3();
20095 var _end$1 = new Vector3();
20097 function LineSegments(geometry, material) {
20098 Line.call(this, geometry, material);
20099 this.type = 'LineSegments';
20102 LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
20103 constructor: LineSegments,
20104 isLineSegments: true,
20105 computeLineDistances: function computeLineDistances() {
20106 var geometry = this.geometry;
20108 if (geometry.isBufferGeometry) {
20109 // we assume non-indexed geometry
20110 if (geometry.index === null) {
20111 var positionAttribute = geometry.attributes.position;
20112 var lineDistances = [];
20114 for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
20115 _start$1.fromBufferAttribute(positionAttribute, i);
20117 _end$1.fromBufferAttribute(positionAttribute, i + 1);
20119 lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
20120 lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
20123 geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
20125 console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
20127 } else if (geometry.isGeometry) {
20128 var vertices = geometry.vertices;
20129 var _lineDistances = geometry.lineDistances;
20131 for (var _i = 0, _l = vertices.length; _i < _l; _i += 2) {
20132 _start$1.copy(vertices[_i]);
20134 _end$1.copy(vertices[_i + 1]);
20136 _lineDistances[_i] = _i === 0 ? 0 : _lineDistances[_i - 1];
20137 _lineDistances[_i + 1] = _lineDistances[_i] + _start$1.distanceTo(_end$1);
20145 function LineLoop(geometry, material) {
20146 Line.call(this, geometry, material);
20147 this.type = 'LineLoop';
20150 LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
20151 constructor: LineLoop,
20158 * opacity: <float>,
20159 * map: new THREE.Texture( <Image> ),
20160 * alphaMap: new THREE.Texture( <Image> ),
20163 * sizeAttenuation: <bool>
20165 * morphTargets: <bool>
20169 function PointsMaterial(parameters) {
20170 Material.call(this);
20171 this.type = 'PointsMaterial';
20172 this.color = new Color(0xffffff);
20174 this.alphaMap = null;
20176 this.sizeAttenuation = true;
20177 this.morphTargets = false;
20178 this.setValues(parameters);
20181 PointsMaterial.prototype = Object.create(Material.prototype);
20182 PointsMaterial.prototype.constructor = PointsMaterial;
20183 PointsMaterial.prototype.isPointsMaterial = true;
20185 PointsMaterial.prototype.copy = function (source) {
20186 Material.prototype.copy.call(this, source);
20187 this.color.copy(source.color);
20188 this.map = source.map;
20189 this.alphaMap = source.alphaMap;
20190 this.size = source.size;
20191 this.sizeAttenuation = source.sizeAttenuation;
20192 this.morphTargets = source.morphTargets;
20196 var _inverseMatrix$2 = new Matrix4();
20198 var _ray$2 = new Ray();
20200 var _sphere$3 = new Sphere();
20202 var _position$1 = new Vector3();
20204 function Points(geometry, material) {
20205 Object3D.call(this);
20206 this.type = 'Points';
20207 this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
20208 this.material = material !== undefined ? material : new PointsMaterial();
20209 this.updateMorphTargets();
20212 Points.prototype = Object.assign(Object.create(Object3D.prototype), {
20213 constructor: Points,
20215 copy: function copy(source) {
20216 Object3D.prototype.copy.call(this, source);
20217 this.material = source.material;
20218 this.geometry = source.geometry;
20221 raycast: function raycast(raycaster, intersects) {
20222 var geometry = this.geometry;
20223 var matrixWorld = this.matrixWorld;
20224 var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
20226 if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
20228 _sphere$3.copy(geometry.boundingSphere);
20230 _sphere$3.applyMatrix4(matrixWorld);
20232 _sphere$3.radius += threshold;
20233 if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
20235 _inverseMatrix$2.copy(matrixWorld).invert();
20237 _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
20239 var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
20240 var localThresholdSq = localThreshold * localThreshold;
20242 if (geometry.isBufferGeometry) {
20243 var index = geometry.index;
20244 var attributes = geometry.attributes;
20245 var positionAttribute = attributes.position;
20247 if (index !== null) {
20248 var indices = index.array;
20250 for (var i = 0, il = indices.length; i < il; i++) {
20251 var a = indices[i];
20253 _position$1.fromBufferAttribute(positionAttribute, a);
20255 testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
20258 for (var _i = 0, l = positionAttribute.count; _i < l; _i++) {
20259 _position$1.fromBufferAttribute(positionAttribute, _i);
20261 testPoint(_position$1, _i, localThresholdSq, matrixWorld, raycaster, intersects, this);
20265 var vertices = geometry.vertices;
20267 for (var _i2 = 0, _l = vertices.length; _i2 < _l; _i2++) {
20268 testPoint(vertices[_i2], _i2, localThresholdSq, matrixWorld, raycaster, intersects, this);
20272 updateMorphTargets: function updateMorphTargets() {
20273 var geometry = this.geometry;
20275 if (geometry.isBufferGeometry) {
20276 var morphAttributes = geometry.morphAttributes;
20277 var keys = Object.keys(morphAttributes);
20279 if (keys.length > 0) {
20280 var morphAttribute = morphAttributes[keys[0]];
20282 if (morphAttribute !== undefined) {
20283 this.morphTargetInfluences = [];
20284 this.morphTargetDictionary = {};
20286 for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
20287 var name = morphAttribute[m].name || String(m);
20288 this.morphTargetInfluences.push(0);
20289 this.morphTargetDictionary[name] = m;
20294 var morphTargets = geometry.morphTargets;
20296 if (morphTargets !== undefined && morphTargets.length > 0) {
20297 console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
20303 function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
20304 var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
20306 if (rayPointDistanceSq < localThresholdSq) {
20307 var intersectPoint = new Vector3();
20309 _ray$2.closestPointToPoint(point, intersectPoint);
20311 intersectPoint.applyMatrix4(matrixWorld);
20312 var distance = raycaster.ray.origin.distanceTo(intersectPoint);
20313 if (distance < raycaster.near || distance > raycaster.far) return;
20315 distance: distance,
20316 distanceToRay: Math.sqrt(rayPointDistanceSq),
20317 point: intersectPoint,
20325 function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
20326 Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
20327 this.format = format !== undefined ? format : RGBFormat;
20328 this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
20329 this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
20330 this.generateMipmaps = false;
20333 function updateVideo() {
20334 scope.needsUpdate = true;
20335 video.requestVideoFrameCallback(updateVideo);
20338 if ('requestVideoFrameCallback' in video) {
20339 video.requestVideoFrameCallback(updateVideo);
20343 VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
20344 constructor: VideoTexture,
20345 clone: function clone() {
20346 return new this.constructor(this.image).copy(this);
20348 isVideoTexture: true,
20349 update: function update() {
20350 var video = this.image;
20351 var hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
20353 if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
20354 this.needsUpdate = true;
20359 function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
20360 Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
20365 this.mipmaps = mipmaps; // no flipping for cube textures
20366 // (also flipping doesn't work for compressed textures )
20368 this.flipY = false; // can't generate mipmaps for compressed textures
20369 // mips must be embedded in DDS files
20371 this.generateMipmaps = false;
20374 CompressedTexture.prototype = Object.create(Texture.prototype);
20375 CompressedTexture.prototype.constructor = CompressedTexture;
20376 CompressedTexture.prototype.isCompressedTexture = true;
20378 function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
20379 Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
20380 this.needsUpdate = true;
20383 CanvasTexture.prototype = Object.create(Texture.prototype);
20384 CanvasTexture.prototype.constructor = CanvasTexture;
20385 CanvasTexture.prototype.isCanvasTexture = true;
20387 function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
20388 format = format !== undefined ? format : DepthFormat;
20390 if (format !== DepthFormat && format !== DepthStencilFormat) {
20391 throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
20394 if (type === undefined && format === DepthFormat) type = UnsignedShortType;
20395 if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
20396 Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
20401 this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
20402 this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
20403 this.flipY = false;
20404 this.generateMipmaps = false;
20407 DepthTexture.prototype = Object.create(Texture.prototype);
20408 DepthTexture.prototype.constructor = DepthTexture;
20409 DepthTexture.prototype.isDepthTexture = true;
20411 var _geometryId = 0; // Geometry uses even numbers as Id
20413 var _m1$3 = new Matrix4();
20415 var _obj$1 = new Object3D();
20417 var _offset$1 = new Vector3();
20419 function Geometry() {
20420 Object.defineProperty(this, 'id', {
20421 value: _geometryId += 2
20423 this.uuid = MathUtils.generateUUID();
20425 this.type = 'Geometry';
20426 this.vertices = [];
20429 this.faceVertexUvs = [[]];
20430 this.morphTargets = [];
20431 this.morphNormals = [];
20432 this.skinWeights = [];
20433 this.skinIndices = [];
20434 this.lineDistances = [];
20435 this.boundingBox = null;
20436 this.boundingSphere = null; // update flags
20438 this.elementsNeedUpdate = false;
20439 this.verticesNeedUpdate = false;
20440 this.uvsNeedUpdate = false;
20441 this.normalsNeedUpdate = false;
20442 this.colorsNeedUpdate = false;
20443 this.lineDistancesNeedUpdate = false;
20444 this.groupsNeedUpdate = false;
20447 Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
20448 constructor: Geometry,
20450 applyMatrix4: function applyMatrix4(matrix) {
20451 var normalMatrix = new Matrix3().getNormalMatrix(matrix);
20453 for (var i = 0, il = this.vertices.length; i < il; i++) {
20454 var vertex = this.vertices[i];
20455 vertex.applyMatrix4(matrix);
20458 for (var _i = 0, _il = this.faces.length; _i < _il; _i++) {
20459 var face = this.faces[_i];
20460 face.normal.applyMatrix3(normalMatrix).normalize();
20462 for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
20463 face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
20467 if (this.boundingBox !== null) {
20468 this.computeBoundingBox();
20471 if (this.boundingSphere !== null) {
20472 this.computeBoundingSphere();
20475 this.verticesNeedUpdate = true;
20476 this.normalsNeedUpdate = true;
20479 rotateX: function rotateX(angle) {
20480 // rotate geometry around world x-axis
20481 _m1$3.makeRotationX(angle);
20483 this.applyMatrix4(_m1$3);
20486 rotateY: function rotateY(angle) {
20487 // rotate geometry around world y-axis
20488 _m1$3.makeRotationY(angle);
20490 this.applyMatrix4(_m1$3);
20493 rotateZ: function rotateZ(angle) {
20494 // rotate geometry around world z-axis
20495 _m1$3.makeRotationZ(angle);
20497 this.applyMatrix4(_m1$3);
20500 translate: function translate(x, y, z) {
20501 // translate geometry
20502 _m1$3.makeTranslation(x, y, z);
20504 this.applyMatrix4(_m1$3);
20507 scale: function scale(x, y, z) {
20509 _m1$3.makeScale(x, y, z);
20511 this.applyMatrix4(_m1$3);
20514 lookAt: function lookAt(vector) {
20515 _obj$1.lookAt(vector);
20517 _obj$1.updateMatrix();
20519 this.applyMatrix4(_obj$1.matrix);
20522 fromBufferGeometry: function fromBufferGeometry(geometry) {
20524 var index = geometry.index !== null ? geometry.index : undefined;
20525 var attributes = geometry.attributes;
20527 if (attributes.position === undefined) {
20528 console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
20532 var position = attributes.position;
20533 var normal = attributes.normal;
20534 var color = attributes.color;
20535 var uv = attributes.uv;
20536 var uv2 = attributes.uv2;
20537 if (uv2 !== undefined) this.faceVertexUvs[1] = [];
20539 for (var i = 0; i < position.count; i++) {
20540 scope.vertices.push(new Vector3().fromBufferAttribute(position, i));
20542 if (color !== undefined) {
20543 scope.colors.push(new Color().fromBufferAttribute(color, i));
20547 function addFace(a, b, c, materialIndex) {
20548 var vertexColors = color === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
20549 var vertexNormals = normal === undefined ? [] : [new Vector3().fromBufferAttribute(normal, a), new Vector3().fromBufferAttribute(normal, b), new Vector3().fromBufferAttribute(normal, c)];
20550 var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
20551 scope.faces.push(face);
20553 if (uv !== undefined) {
20554 scope.faceVertexUvs[0].push([new Vector2().fromBufferAttribute(uv, a), new Vector2().fromBufferAttribute(uv, b), new Vector2().fromBufferAttribute(uv, c)]);
20557 if (uv2 !== undefined) {
20558 scope.faceVertexUvs[1].push([new Vector2().fromBufferAttribute(uv2, a), new Vector2().fromBufferAttribute(uv2, b), new Vector2().fromBufferAttribute(uv2, c)]);
20562 var groups = geometry.groups;
20564 if (groups.length > 0) {
20565 for (var _i2 = 0; _i2 < groups.length; _i2++) {
20566 var group = groups[_i2];
20567 var start = group.start;
20568 var count = group.count;
20570 for (var j = start, jl = start + count; j < jl; j += 3) {
20571 if (index !== undefined) {
20572 addFace(index.getX(j), index.getX(j + 1), index.getX(j + 2), group.materialIndex);
20574 addFace(j, j + 1, j + 2, group.materialIndex);
20579 if (index !== undefined) {
20580 for (var _i3 = 0; _i3 < index.count; _i3 += 3) {
20581 addFace(index.getX(_i3), index.getX(_i3 + 1), index.getX(_i3 + 2));
20584 for (var _i4 = 0; _i4 < position.count; _i4 += 3) {
20585 addFace(_i4, _i4 + 1, _i4 + 2);
20590 this.computeFaceNormals();
20592 if (geometry.boundingBox !== null) {
20593 this.boundingBox = geometry.boundingBox.clone();
20596 if (geometry.boundingSphere !== null) {
20597 this.boundingSphere = geometry.boundingSphere.clone();
20602 center: function center() {
20603 this.computeBoundingBox();
20604 this.boundingBox.getCenter(_offset$1).negate();
20605 this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
20608 normalize: function normalize() {
20609 this.computeBoundingSphere();
20610 var center = this.boundingSphere.center;
20611 var radius = this.boundingSphere.radius;
20612 var s = radius === 0 ? 1 : 1.0 / radius;
20613 var matrix = new Matrix4();
20614 matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
20615 this.applyMatrix4(matrix);
20618 computeFaceNormals: function computeFaceNormals() {
20619 var cb = new Vector3(),
20620 ab = new Vector3();
20622 for (var f = 0, fl = this.faces.length; f < fl; f++) {
20623 var face = this.faces[f];
20624 var vA = this.vertices[face.a];
20625 var vB = this.vertices[face.b];
20626 var vC = this.vertices[face.c];
20627 cb.subVectors(vC, vB);
20628 ab.subVectors(vA, vB);
20631 face.normal.copy(cb);
20634 computeVertexNormals: function computeVertexNormals(areaWeighted) {
20635 if (areaWeighted === void 0) {
20636 areaWeighted = true;
20639 var vertices = new Array(this.vertices.length);
20641 for (var v = 0, vl = this.vertices.length; v < vl; v++) {
20642 vertices[v] = new Vector3();
20645 if (areaWeighted) {
20646 // vertex normals weighted by triangle areas
20647 // http://www.iquilezles.org/www/articles/normals/normals.htm
20648 var cb = new Vector3(),
20649 ab = new Vector3();
20651 for (var f = 0, fl = this.faces.length; f < fl; f++) {
20652 var face = this.faces[f];
20653 var vA = this.vertices[face.a];
20654 var vB = this.vertices[face.b];
20655 var vC = this.vertices[face.c];
20656 cb.subVectors(vC, vB);
20657 ab.subVectors(vA, vB);
20659 vertices[face.a].add(cb);
20660 vertices[face.b].add(cb);
20661 vertices[face.c].add(cb);
20664 this.computeFaceNormals();
20666 for (var _f = 0, _fl = this.faces.length; _f < _fl; _f++) {
20667 var _face = this.faces[_f];
20669 vertices[_face.a].add(_face.normal);
20671 vertices[_face.b].add(_face.normal);
20673 vertices[_face.c].add(_face.normal);
20677 for (var _v = 0, _vl = this.vertices.length; _v < _vl; _v++) {
20678 vertices[_v].normalize();
20681 for (var _f2 = 0, _fl2 = this.faces.length; _f2 < _fl2; _f2++) {
20682 var _face2 = this.faces[_f2];
20683 var vertexNormals = _face2.vertexNormals;
20685 if (vertexNormals.length === 3) {
20686 vertexNormals[0].copy(vertices[_face2.a]);
20687 vertexNormals[1].copy(vertices[_face2.b]);
20688 vertexNormals[2].copy(vertices[_face2.c]);
20690 vertexNormals[0] = vertices[_face2.a].clone();
20691 vertexNormals[1] = vertices[_face2.b].clone();
20692 vertexNormals[2] = vertices[_face2.c].clone();
20696 if (this.faces.length > 0) {
20697 this.normalsNeedUpdate = true;
20700 computeFlatVertexNormals: function computeFlatVertexNormals() {
20701 this.computeFaceNormals();
20703 for (var f = 0, fl = this.faces.length; f < fl; f++) {
20704 var face = this.faces[f];
20705 var vertexNormals = face.vertexNormals;
20707 if (vertexNormals.length === 3) {
20708 vertexNormals[0].copy(face.normal);
20709 vertexNormals[1].copy(face.normal);
20710 vertexNormals[2].copy(face.normal);
20712 vertexNormals[0] = face.normal.clone();
20713 vertexNormals[1] = face.normal.clone();
20714 vertexNormals[2] = face.normal.clone();
20718 if (this.faces.length > 0) {
20719 this.normalsNeedUpdate = true;
20722 computeMorphNormals: function computeMorphNormals() {
20723 // save original normals
20724 // - create temp variables on first access
20725 // otherwise just copy (for faster repeated calls)
20726 for (var f = 0, fl = this.faces.length; f < fl; f++) {
20727 var face = this.faces[f];
20729 if (!face.__originalFaceNormal) {
20730 face.__originalFaceNormal = face.normal.clone();
20732 face.__originalFaceNormal.copy(face.normal);
20735 if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
20737 for (var i = 0, il = face.vertexNormals.length; i < il; i++) {
20738 if (!face.__originalVertexNormals[i]) {
20739 face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
20741 face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
20744 } // use temp geometry to compute face and vertex normals for each morph
20747 var tmpGeo = new Geometry();
20748 tmpGeo.faces = this.faces;
20750 for (var _i5 = 0, _il2 = this.morphTargets.length; _i5 < _il2; _i5++) {
20751 // create on first access
20752 if (!this.morphNormals[_i5]) {
20753 this.morphNormals[_i5] = {};
20754 this.morphNormals[_i5].faceNormals = [];
20755 this.morphNormals[_i5].vertexNormals = [];
20756 var dstNormalsFace = this.morphNormals[_i5].faceNormals;
20757 var dstNormalsVertex = this.morphNormals[_i5].vertexNormals;
20759 for (var _f3 = 0, _fl3 = this.faces.length; _f3 < _fl3; _f3++) {
20760 var faceNormal = new Vector3();
20761 var vertexNormals = {
20766 dstNormalsFace.push(faceNormal);
20767 dstNormalsVertex.push(vertexNormals);
20771 var morphNormals = this.morphNormals[_i5]; // set vertices to morph target
20773 tmpGeo.vertices = this.morphTargets[_i5].vertices; // compute morph normals
20775 tmpGeo.computeFaceNormals();
20776 tmpGeo.computeVertexNormals(); // store morph normals
20778 for (var _f4 = 0, _fl4 = this.faces.length; _f4 < _fl4; _f4++) {
20779 var _face3 = this.faces[_f4];
20780 var _faceNormal = morphNormals.faceNormals[_f4];
20781 var _vertexNormals = morphNormals.vertexNormals[_f4];
20783 _faceNormal.copy(_face3.normal);
20785 _vertexNormals.a.copy(_face3.vertexNormals[0]);
20787 _vertexNormals.b.copy(_face3.vertexNormals[1]);
20789 _vertexNormals.c.copy(_face3.vertexNormals[2]);
20791 } // restore original normals
20794 for (var _f5 = 0, _fl5 = this.faces.length; _f5 < _fl5; _f5++) {
20795 var _face4 = this.faces[_f5];
20796 _face4.normal = _face4.__originalFaceNormal;
20797 _face4.vertexNormals = _face4.__originalVertexNormals;
20800 computeBoundingBox: function computeBoundingBox() {
20801 if (this.boundingBox === null) {
20802 this.boundingBox = new Box3();
20805 this.boundingBox.setFromPoints(this.vertices);
20807 computeBoundingSphere: function computeBoundingSphere() {
20808 if (this.boundingSphere === null) {
20809 this.boundingSphere = new Sphere();
20812 this.boundingSphere.setFromPoints(this.vertices);
20814 merge: function merge(geometry, matrix, materialIndexOffset) {
20815 if (materialIndexOffset === void 0) {
20816 materialIndexOffset = 0;
20819 if (!(geometry && geometry.isGeometry)) {
20820 console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
20825 var vertexOffset = this.vertices.length,
20826 vertices1 = this.vertices,
20827 vertices2 = geometry.vertices,
20828 faces1 = this.faces,
20829 faces2 = geometry.faces,
20830 colors1 = this.colors,
20831 colors2 = geometry.colors;
20833 if (matrix !== undefined) {
20834 normalMatrix = new Matrix3().getNormalMatrix(matrix);
20838 for (var i = 0, il = vertices2.length; i < il; i++) {
20839 var vertex = vertices2[i];
20840 var vertexCopy = vertex.clone();
20841 if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
20842 vertices1.push(vertexCopy);
20846 for (var _i6 = 0, _il3 = colors2.length; _i6 < _il3; _i6++) {
20847 colors1.push(colors2[_i6].clone());
20851 for (var _i7 = 0, _il4 = faces2.length; _i7 < _il4; _i7++) {
20852 var face = faces2[_i7];
20853 var normal = void 0,
20855 var faceVertexNormals = face.vertexNormals,
20856 faceVertexColors = face.vertexColors;
20857 var faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
20858 faceCopy.normal.copy(face.normal);
20860 if (normalMatrix !== undefined) {
20861 faceCopy.normal.applyMatrix3(normalMatrix).normalize();
20864 for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
20865 normal = faceVertexNormals[j].clone();
20867 if (normalMatrix !== undefined) {
20868 normal.applyMatrix3(normalMatrix).normalize();
20871 faceCopy.vertexNormals.push(normal);
20874 faceCopy.color.copy(face.color);
20876 for (var _j = 0, _jl = faceVertexColors.length; _j < _jl; _j++) {
20877 color = faceVertexColors[_j];
20878 faceCopy.vertexColors.push(color.clone());
20881 faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
20882 faces1.push(faceCopy);
20886 for (var _i8 = 0, _il5 = geometry.faceVertexUvs.length; _i8 < _il5; _i8++) {
20887 var faceVertexUvs2 = geometry.faceVertexUvs[_i8];
20888 if (this.faceVertexUvs[_i8] === undefined) this.faceVertexUvs[_i8] = [];
20890 for (var _j2 = 0, _jl2 = faceVertexUvs2.length; _j2 < _jl2; _j2++) {
20891 var uvs2 = faceVertexUvs2[_j2],
20894 for (var k = 0, kl = uvs2.length; k < kl; k++) {
20895 uvsCopy.push(uvs2[k].clone());
20898 this.faceVertexUvs[_i8].push(uvsCopy);
20902 mergeMesh: function mergeMesh(mesh) {
20903 if (!(mesh && mesh.isMesh)) {
20904 console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
20908 if (mesh.matrixAutoUpdate) mesh.updateMatrix();
20909 this.merge(mesh.geometry, mesh.matrix);
20913 * Checks for duplicate vertices with hashmap.
20914 * Duplicated vertices are removed
20915 * and faces' vertices are updated.
20917 mergeVertices: function mergeVertices(precisionPoints) {
20918 if (precisionPoints === void 0) {
20919 precisionPoints = 4;
20922 var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
20926 var precision = Math.pow(10, precisionPoints);
20928 for (var i = 0, il = this.vertices.length; i < il; i++) {
20929 var v = this.vertices[i];
20930 var key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
20932 if (verticesMap[key] === undefined) {
20933 verticesMap[key] = i;
20934 unique.push(this.vertices[i]);
20935 changes[i] = unique.length - 1;
20937 //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
20938 changes[i] = changes[verticesMap[key]];
20940 } // if faces are completely degenerate after merging vertices, we
20941 // have to remove them from the geometry.
20944 var faceIndicesToRemove = [];
20946 for (var _i9 = 0, _il6 = this.faces.length; _i9 < _il6; _i9++) {
20947 var face = this.faces[_i9];
20948 face.a = changes[face.a];
20949 face.b = changes[face.b];
20950 face.c = changes[face.c];
20951 var indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
20952 // we have to remove the face as nothing can be saved
20954 for (var n = 0; n < 3; n++) {
20955 if (indices[n] === indices[(n + 1) % 3]) {
20956 faceIndicesToRemove.push(_i9);
20962 for (var _i10 = faceIndicesToRemove.length - 1; _i10 >= 0; _i10--) {
20963 var idx = faceIndicesToRemove[_i10];
20964 this.faces.splice(idx, 1);
20966 for (var j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
20967 this.faceVertexUvs[j].splice(idx, 1);
20969 } // Use unique set of vertices
20972 var diff = this.vertices.length - unique.length;
20973 this.vertices = unique;
20976 setFromPoints: function setFromPoints(points) {
20977 this.vertices = [];
20979 for (var i = 0, l = points.length; i < l; i++) {
20980 var point = points[i];
20981 this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
20986 sortFacesByMaterialIndex: function sortFacesByMaterialIndex() {
20987 var faces = this.faces;
20988 var length = faces.length; // tag faces
20990 for (var i = 0; i < length; i++) {
20995 function materialIndexSort(a, b) {
20996 return a.materialIndex - b.materialIndex;
20999 faces.sort(materialIndexSort); // sort uvs
21001 var uvs1 = this.faceVertexUvs[0];
21002 var uvs2 = this.faceVertexUvs[1];
21003 var newUvs1, newUvs2;
21004 if (uvs1 && uvs1.length === length) newUvs1 = [];
21005 if (uvs2 && uvs2.length === length) newUvs2 = [];
21007 for (var _i11 = 0; _i11 < length; _i11++) {
21008 var id = faces[_i11]._id;
21009 if (newUvs1) newUvs1.push(uvs1[id]);
21010 if (newUvs2) newUvs2.push(uvs2[id]);
21013 if (newUvs1) this.faceVertexUvs[0] = newUvs1;
21014 if (newUvs2) this.faceVertexUvs[1] = newUvs2;
21016 toJSON: function toJSON() {
21021 generator: 'Geometry.toJSON'
21023 }; // standard Geometry serialization
21025 data.uuid = this.uuid;
21026 data.type = this.type;
21027 if (this.name !== '') data.name = this.name;
21029 if (this.parameters !== undefined) {
21030 var parameters = this.parameters;
21032 for (var key in parameters) {
21033 if (parameters[key] !== undefined) data[key] = parameters[key];
21041 for (var i = 0; i < this.vertices.length; i++) {
21042 var vertex = this.vertices[i];
21043 vertices.push(vertex.x, vertex.y, vertex.z);
21048 var normalsHash = {};
21050 var colorsHash = {};
21054 for (var _i12 = 0; _i12 < this.faces.length; _i12++) {
21055 var face = this.faces[_i12];
21056 var hasMaterial = true;
21057 var hasFaceUv = false; // deprecated
21059 var hasFaceVertexUv = this.faceVertexUvs[0][_i12] !== undefined;
21060 var hasFaceNormal = face.normal.length() > 0;
21061 var hasFaceVertexNormal = face.vertexNormals.length > 0;
21062 var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
21063 var hasFaceVertexColor = face.vertexColors.length > 0;
21065 faceType = setBit(faceType, 0, 0); // isQuad
21067 faceType = setBit(faceType, 1, hasMaterial);
21068 faceType = setBit(faceType, 2, hasFaceUv);
21069 faceType = setBit(faceType, 3, hasFaceVertexUv);
21070 faceType = setBit(faceType, 4, hasFaceNormal);
21071 faceType = setBit(faceType, 5, hasFaceVertexNormal);
21072 faceType = setBit(faceType, 6, hasFaceColor);
21073 faceType = setBit(faceType, 7, hasFaceVertexColor);
21074 faces.push(faceType);
21075 faces.push(face.a, face.b, face.c);
21076 faces.push(face.materialIndex);
21078 if (hasFaceVertexUv) {
21079 var faceVertexUvs = this.faceVertexUvs[0][_i12];
21080 faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
21083 if (hasFaceNormal) {
21084 faces.push(getNormalIndex(face.normal));
21087 if (hasFaceVertexNormal) {
21088 var vertexNormals = face.vertexNormals;
21089 faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
21092 if (hasFaceColor) {
21093 faces.push(getColorIndex(face.color));
21096 if (hasFaceVertexColor) {
21097 var vertexColors = face.vertexColors;
21098 faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
21102 function setBit(value, position, enabled) {
21103 return enabled ? value | 1 << position : value & ~(1 << position);
21106 function getNormalIndex(normal) {
21107 var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
21109 if (normalsHash[hash] !== undefined) {
21110 return normalsHash[hash];
21113 normalsHash[hash] = normals.length / 3;
21114 normals.push(normal.x, normal.y, normal.z);
21115 return normalsHash[hash];
21118 function getColorIndex(color) {
21119 var hash = color.r.toString() + color.g.toString() + color.b.toString();
21121 if (colorsHash[hash] !== undefined) {
21122 return colorsHash[hash];
21125 colorsHash[hash] = colors.length;
21126 colors.push(color.getHex());
21127 return colorsHash[hash];
21130 function getUvIndex(uv) {
21131 var hash = uv.x.toString() + uv.y.toString();
21133 if (uvsHash[hash] !== undefined) {
21134 return uvsHash[hash];
21137 uvsHash[hash] = uvs.length / 2;
21138 uvs.push(uv.x, uv.y);
21139 return uvsHash[hash];
21143 data.data.vertices = vertices;
21144 data.data.normals = normals;
21145 if (colors.length > 0) data.data.colors = colors;
21146 if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
21148 data.data.faces = faces;
21151 clone: function clone() {
21153 // Handle primitives
21154 const parameters = this.parameters;
21155 if ( parameters !== undefined ) {
21157 for ( const key in parameters ) {
21158 values.push( parameters[ key ] );
21160 const geometry = Object.create( this.constructor.prototype );
21161 this.constructor.apply( geometry, values );
21164 return new this.constructor().copy( this );
21166 return new Geometry().copy(this);
21168 copy: function copy(source) {
21170 this.vertices = [];
21173 this.faceVertexUvs = [[]];
21174 this.morphTargets = [];
21175 this.morphNormals = [];
21176 this.skinWeights = [];
21177 this.skinIndices = [];
21178 this.lineDistances = [];
21179 this.boundingBox = null;
21180 this.boundingSphere = null; // name
21182 this.name = source.name; // vertices
21184 var vertices = source.vertices;
21186 for (var i = 0, il = vertices.length; i < il; i++) {
21187 this.vertices.push(vertices[i].clone());
21191 var colors = source.colors;
21193 for (var _i13 = 0, _il7 = colors.length; _i13 < _il7; _i13++) {
21194 this.colors.push(colors[_i13].clone());
21198 var faces = source.faces;
21200 for (var _i14 = 0, _il8 = faces.length; _i14 < _il8; _i14++) {
21201 this.faces.push(faces[_i14].clone());
21202 } // face vertex uvs
21205 for (var _i15 = 0, _il9 = source.faceVertexUvs.length; _i15 < _il9; _i15++) {
21206 var faceVertexUvs = source.faceVertexUvs[_i15];
21208 if (this.faceVertexUvs[_i15] === undefined) {
21209 this.faceVertexUvs[_i15] = [];
21212 for (var j = 0, jl = faceVertexUvs.length; j < jl; j++) {
21213 var uvs = faceVertexUvs[j],
21216 for (var k = 0, kl = uvs.length; k < kl; k++) {
21218 uvsCopy.push(uv.clone());
21221 this.faceVertexUvs[_i15].push(uvsCopy);
21226 var morphTargets = source.morphTargets;
21228 for (var _i16 = 0, _il10 = morphTargets.length; _i16 < _il10; _i16++) {
21229 var morphTarget = {};
21230 morphTarget.name = morphTargets[_i16].name; // vertices
21232 if (morphTargets[_i16].vertices !== undefined) {
21233 morphTarget.vertices = [];
21235 for (var _j3 = 0, _jl3 = morphTargets[_i16].vertices.length; _j3 < _jl3; _j3++) {
21236 morphTarget.vertices.push(morphTargets[_i16].vertices[_j3].clone());
21241 if (morphTargets[_i16].normals !== undefined) {
21242 morphTarget.normals = [];
21244 for (var _j4 = 0, _jl4 = morphTargets[_i16].normals.length; _j4 < _jl4; _j4++) {
21245 morphTarget.normals.push(morphTargets[_i16].normals[_j4].clone());
21249 this.morphTargets.push(morphTarget);
21253 var morphNormals = source.morphNormals;
21255 for (var _i17 = 0, _il11 = morphNormals.length; _i17 < _il11; _i17++) {
21256 var morphNormal = {}; // vertex normals
21258 if (morphNormals[_i17].vertexNormals !== undefined) {
21259 morphNormal.vertexNormals = [];
21261 for (var _j5 = 0, _jl5 = morphNormals[_i17].vertexNormals.length; _j5 < _jl5; _j5++) {
21262 var srcVertexNormal = morphNormals[_i17].vertexNormals[_j5];
21263 var destVertexNormal = {};
21264 destVertexNormal.a = srcVertexNormal.a.clone();
21265 destVertexNormal.b = srcVertexNormal.b.clone();
21266 destVertexNormal.c = srcVertexNormal.c.clone();
21267 morphNormal.vertexNormals.push(destVertexNormal);
21272 if (morphNormals[_i17].faceNormals !== undefined) {
21273 morphNormal.faceNormals = [];
21275 for (var _j6 = 0, _jl6 = morphNormals[_i17].faceNormals.length; _j6 < _jl6; _j6++) {
21276 morphNormal.faceNormals.push(morphNormals[_i17].faceNormals[_j6].clone());
21280 this.morphNormals.push(morphNormal);
21284 var skinWeights = source.skinWeights;
21286 for (var _i18 = 0, _il12 = skinWeights.length; _i18 < _il12; _i18++) {
21287 this.skinWeights.push(skinWeights[_i18].clone());
21291 var skinIndices = source.skinIndices;
21293 for (var _i19 = 0, _il13 = skinIndices.length; _i19 < _il13; _i19++) {
21294 this.skinIndices.push(skinIndices[_i19].clone());
21295 } // line distances
21298 var lineDistances = source.lineDistances;
21300 for (var _i20 = 0, _il14 = lineDistances.length; _i20 < _il14; _i20++) {
21301 this.lineDistances.push(lineDistances[_i20]);
21305 var boundingBox = source.boundingBox;
21307 if (boundingBox !== null) {
21308 this.boundingBox = boundingBox.clone();
21309 } // bounding sphere
21312 var boundingSphere = source.boundingSphere;
21314 if (boundingSphere !== null) {
21315 this.boundingSphere = boundingSphere.clone();
21319 this.elementsNeedUpdate = source.elementsNeedUpdate;
21320 this.verticesNeedUpdate = source.verticesNeedUpdate;
21321 this.uvsNeedUpdate = source.uvsNeedUpdate;
21322 this.normalsNeedUpdate = source.normalsNeedUpdate;
21323 this.colorsNeedUpdate = source.colorsNeedUpdate;
21324 this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
21325 this.groupsNeedUpdate = source.groupsNeedUpdate;
21328 dispose: function dispose() {
21329 this.dispatchEvent({
21335 var BoxGeometry = /*#__PURE__*/function (_Geometry) {
21336 _inheritsLoose(BoxGeometry, _Geometry);
21338 function BoxGeometry(width, height, depth, widthSegments, heightSegments, depthSegments) {
21341 _this = _Geometry.call(this) || this;
21342 _this.type = 'BoxGeometry';
21343 _this.parameters = {
21347 widthSegments: widthSegments,
21348 heightSegments: heightSegments,
21349 depthSegments: depthSegments
21352 _this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
21354 _this.mergeVertices();
21359 return BoxGeometry;
21362 var CircleBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
21363 _inheritsLoose(CircleBufferGeometry, _BufferGeometry);
21365 function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
21368 if (radius === void 0) {
21372 if (segments === void 0) {
21376 if (thetaStart === void 0) {
21380 if (thetaLength === void 0) {
21381 thetaLength = Math.PI * 2;
21384 _this = _BufferGeometry.call(this) || this;
21385 _this.type = 'CircleBufferGeometry';
21386 _this.parameters = {
21388 segments: segments,
21389 thetaStart: thetaStart,
21390 thetaLength: thetaLength
21392 segments = Math.max(3, segments); // buffers
21397 var uvs = []; // helper variables
21399 var vertex = new Vector3();
21400 var uv = new Vector2(); // center point
21402 vertices.push(0, 0, 0);
21403 normals.push(0, 0, 1);
21404 uvs.push(0.5, 0.5);
21406 for (var s = 0, i = 3; s <= segments; s++, i += 3) {
21407 var segment = thetaStart + s / segments * thetaLength; // vertex
21409 vertex.x = radius * Math.cos(segment);
21410 vertex.y = radius * Math.sin(segment);
21411 vertices.push(vertex.x, vertex.y, vertex.z); // normal
21413 normals.push(0, 0, 1); // uvs
21415 uv.x = (vertices[i] / radius + 1) / 2;
21416 uv.y = (vertices[i + 1] / radius + 1) / 2;
21417 uvs.push(uv.x, uv.y);
21421 for (var _i = 1; _i <= segments; _i++) {
21422 indices.push(_i, _i + 1, 0);
21423 } // build geometry
21426 _this.setIndex(indices);
21428 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
21430 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
21432 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
21437 return CircleBufferGeometry;
21440 var CircleGeometry = /*#__PURE__*/function (_Geometry) {
21441 _inheritsLoose(CircleGeometry, _Geometry);
21443 function CircleGeometry(radius, segments, thetaStart, thetaLength) {
21446 _this = _Geometry.call(this) || this;
21447 _this.type = 'CircleGeometry';
21448 _this.parameters = {
21450 segments: segments,
21451 thetaStart: thetaStart,
21452 thetaLength: thetaLength
21455 _this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
21457 _this.mergeVertices();
21462 return CircleGeometry;
21465 var CylinderBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
21466 _inheritsLoose(CylinderBufferGeometry, _BufferGeometry);
21468 function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
21471 if (radiusTop === void 0) {
21475 if (radiusBottom === void 0) {
21479 if (height === void 0) {
21483 if (radialSegments === void 0) {
21484 radialSegments = 8;
21487 if (heightSegments === void 0) {
21488 heightSegments = 1;
21491 if (openEnded === void 0) {
21495 if (thetaStart === void 0) {
21499 if (thetaLength === void 0) {
21500 thetaLength = Math.PI * 2;
21503 _this = _BufferGeometry.call(this) || this;
21504 _this.type = 'CylinderBufferGeometry';
21505 _this.parameters = {
21506 radiusTop: radiusTop,
21507 radiusBottom: radiusBottom,
21509 radialSegments: radialSegments,
21510 heightSegments: heightSegments,
21511 openEnded: openEnded,
21512 thetaStart: thetaStart,
21513 thetaLength: thetaLength
21516 var scope = _assertThisInitialized(_this);
21518 radialSegments = Math.floor(radialSegments);
21519 heightSegments = Math.floor(heightSegments); // buffers
21524 var uvs = []; // helper variables
21527 var indexArray = [];
21528 var halfHeight = height / 2;
21529 var groupStart = 0; // generate geometry
21533 if (openEnded === false) {
21534 if (radiusTop > 0) generateCap(true);
21535 if (radiusBottom > 0) generateCap(false);
21536 } // build geometry
21539 _this.setIndex(indices);
21541 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
21543 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
21545 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
21547 function generateTorso() {
21548 var normal = new Vector3();
21549 var vertex = new Vector3();
21550 var groupCount = 0; // this will be used to calculate the normal
21552 var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
21554 for (var y = 0; y <= heightSegments; y++) {
21556 var v = y / heightSegments; // calculate the radius of the current row
21558 var radius = v * (radiusBottom - radiusTop) + radiusTop;
21560 for (var x = 0; x <= radialSegments; x++) {
21561 var u = x / radialSegments;
21562 var theta = u * thetaLength + thetaStart;
21563 var sinTheta = Math.sin(theta);
21564 var cosTheta = Math.cos(theta); // vertex
21566 vertex.x = radius * sinTheta;
21567 vertex.y = -v * height + halfHeight;
21568 vertex.z = radius * cosTheta;
21569 vertices.push(vertex.x, vertex.y, vertex.z); // normal
21571 normal.set(sinTheta, slope, cosTheta).normalize();
21572 normals.push(normal.x, normal.y, normal.z); // uv
21574 uvs.push(u, 1 - v); // save index of vertex in respective row
21576 indexRow.push(index++);
21577 } // now save vertices of the row in our index array
21580 indexArray.push(indexRow);
21581 } // generate indices
21584 for (var _x = 0; _x < radialSegments; _x++) {
21585 for (var _y = 0; _y < heightSegments; _y++) {
21586 // we use the index array to access the correct indices
21587 var a = indexArray[_y][_x];
21588 var b = indexArray[_y + 1][_x];
21589 var c = indexArray[_y + 1][_x + 1];
21590 var d = indexArray[_y][_x + 1]; // faces
21592 indices.push(a, b, d);
21593 indices.push(b, c, d); // update group counter
21597 } // add a group to the geometry. this will ensure multi material support
21600 scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
21602 groupStart += groupCount;
21605 function generateCap(top) {
21606 // save the index of the first center vertex
21607 var centerIndexStart = index;
21608 var uv = new Vector2();
21609 var vertex = new Vector3();
21610 var groupCount = 0;
21611 var radius = top === true ? radiusTop : radiusBottom;
21612 var sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
21613 // because the geometry needs one set of uvs per face,
21614 // we must generate a center vertex per face/segment
21616 for (var x = 1; x <= radialSegments; x++) {
21618 vertices.push(0, halfHeight * sign, 0); // normal
21620 normals.push(0, sign, 0); // uv
21622 uvs.push(0.5, 0.5); // increase index
21625 } // save the index of the last center vertex
21628 var centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
21630 for (var _x2 = 0; _x2 <= radialSegments; _x2++) {
21631 var u = _x2 / radialSegments;
21632 var theta = u * thetaLength + thetaStart;
21633 var cosTheta = Math.cos(theta);
21634 var sinTheta = Math.sin(theta); // vertex
21636 vertex.x = radius * sinTheta;
21637 vertex.y = halfHeight * sign;
21638 vertex.z = radius * cosTheta;
21639 vertices.push(vertex.x, vertex.y, vertex.z); // normal
21641 normals.push(0, sign, 0); // uv
21643 uv.x = cosTheta * 0.5 + 0.5;
21644 uv.y = sinTheta * 0.5 * sign + 0.5;
21645 uvs.push(uv.x, uv.y); // increase index
21648 } // generate indices
21651 for (var _x3 = 0; _x3 < radialSegments; _x3++) {
21652 var c = centerIndexStart + _x3;
21653 var i = centerIndexEnd + _x3;
21655 if (top === true) {
21657 indices.push(i, i + 1, c);
21660 indices.push(i + 1, i, c);
21664 } // add a group to the geometry. this will ensure multi material support
21667 scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
21669 groupStart += groupCount;
21675 return CylinderBufferGeometry;
21678 var CylinderGeometry = /*#__PURE__*/function (_Geometry) {
21679 _inheritsLoose(CylinderGeometry, _Geometry);
21681 function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
21684 _this = _Geometry.call(this) || this;
21685 _this.type = 'CylinderGeometry';
21686 _this.parameters = {
21687 radiusTop: radiusTop,
21688 radiusBottom: radiusBottom,
21690 radialSegments: radialSegments,
21691 heightSegments: heightSegments,
21692 openEnded: openEnded,
21693 thetaStart: thetaStart,
21694 thetaLength: thetaLength
21697 _this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
21699 _this.mergeVertices();
21704 return CylinderGeometry;
21707 var ConeGeometry = /*#__PURE__*/function (_CylinderGeometry) {
21708 _inheritsLoose(ConeGeometry, _CylinderGeometry);
21710 function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
21713 _this = _CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) || this;
21714 _this.type = 'ConeGeometry';
21715 _this.parameters = {
21718 radialSegments: radialSegments,
21719 heightSegments: heightSegments,
21720 openEnded: openEnded,
21721 thetaStart: thetaStart,
21722 thetaLength: thetaLength
21727 return ConeGeometry;
21728 }(CylinderGeometry);
21730 var ConeBufferGeometry = /*#__PURE__*/function (_CylinderBufferGeomet) {
21731 _inheritsLoose(ConeBufferGeometry, _CylinderBufferGeomet);
21733 function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
21736 if (radius === void 0) {
21740 if (height === void 0) {
21744 if (radialSegments === void 0) {
21745 radialSegments = 8;
21748 if (heightSegments === void 0) {
21749 heightSegments = 1;
21752 if (openEnded === void 0) {
21756 if (thetaStart === void 0) {
21760 if (thetaLength === void 0) {
21761 thetaLength = Math.PI * 2;
21764 _this = _CylinderBufferGeomet.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) || this;
21765 _this.type = 'ConeBufferGeometry';
21766 _this.parameters = {
21769 radialSegments: radialSegments,
21770 heightSegments: heightSegments,
21771 openEnded: openEnded,
21772 thetaStart: thetaStart,
21773 thetaLength: thetaLength
21778 return ConeBufferGeometry;
21779 }(CylinderBufferGeometry);
21781 var PolyhedronBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
21782 _inheritsLoose(PolyhedronBufferGeometry, _BufferGeometry);
21784 function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
21787 if (radius === void 0) {
21791 if (detail === void 0) {
21795 _this = _BufferGeometry.call(this) || this;
21796 _this.type = 'PolyhedronBufferGeometry';
21797 _this.parameters = {
21798 vertices: vertices,
21802 }; // default buffer data
21804 var vertexBuffer = [];
21805 var uvBuffer = []; // the subdivision creates the vertex buffer data
21807 subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
21809 applyRadius(radius); // finally, create the uv data
21811 generateUVs(); // build non-indexed geometry
21813 _this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
21815 _this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
21817 _this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
21819 if (detail === 0) {
21820 _this.computeVertexNormals(); // flat normals
21823 _this.normalizeNormals(); // smooth normals
21825 } // helper functions
21828 function subdivide(detail) {
21829 var a = new Vector3();
21830 var b = new Vector3();
21831 var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
21833 for (var i = 0; i < indices.length; i += 3) {
21834 // get the vertices of the face
21835 getVertexByIndex(indices[i + 0], a);
21836 getVertexByIndex(indices[i + 1], b);
21837 getVertexByIndex(indices[i + 2], c); // perform subdivision
21839 subdivideFace(a, b, c, detail);
21843 function subdivideFace(a, b, c, detail) {
21844 var cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
21846 var v = []; // construct all of the vertices for this subdivision
21848 for (var i = 0; i <= cols; i++) {
21850 var aj = a.clone().lerp(c, i / cols);
21851 var bj = b.clone().lerp(c, i / cols);
21852 var rows = cols - i;
21854 for (var j = 0; j <= rows; j++) {
21855 if (j === 0 && i === cols) {
21858 v[i][j] = aj.clone().lerp(bj, j / rows);
21861 } // construct all of the faces
21864 for (var _i = 0; _i < cols; _i++) {
21865 for (var _j = 0; _j < 2 * (cols - _i) - 1; _j++) {
21866 var k = Math.floor(_j / 2);
21868 if (_j % 2 === 0) {
21869 pushVertex(v[_i][k + 1]);
21870 pushVertex(v[_i + 1][k]);
21871 pushVertex(v[_i][k]);
21873 pushVertex(v[_i][k + 1]);
21874 pushVertex(v[_i + 1][k + 1]);
21875 pushVertex(v[_i + 1][k]);
21881 function applyRadius(radius) {
21882 var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
21884 for (var i = 0; i < vertexBuffer.length; i += 3) {
21885 vertex.x = vertexBuffer[i + 0];
21886 vertex.y = vertexBuffer[i + 1];
21887 vertex.z = vertexBuffer[i + 2];
21888 vertex.normalize().multiplyScalar(radius);
21889 vertexBuffer[i + 0] = vertex.x;
21890 vertexBuffer[i + 1] = vertex.y;
21891 vertexBuffer[i + 2] = vertex.z;
21895 function generateUVs() {
21896 var vertex = new Vector3();
21898 for (var i = 0; i < vertexBuffer.length; i += 3) {
21899 vertex.x = vertexBuffer[i + 0];
21900 vertex.y = vertexBuffer[i + 1];
21901 vertex.z = vertexBuffer[i + 2];
21902 var u = azimuth(vertex) / 2 / Math.PI + 0.5;
21903 var v = inclination(vertex) / Math.PI + 0.5;
21904 uvBuffer.push(u, 1 - v);
21911 function correctSeam() {
21912 // handle case when face straddles the seam, see #3269
21913 for (var i = 0; i < uvBuffer.length; i += 6) {
21914 // uv data of a single face
21915 var x0 = uvBuffer[i + 0];
21916 var x1 = uvBuffer[i + 2];
21917 var x2 = uvBuffer[i + 4];
21918 var max = Math.max(x0, x1, x2);
21919 var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
21921 if (max > 0.9 && min < 0.1) {
21922 if (x0 < 0.2) uvBuffer[i + 0] += 1;
21923 if (x1 < 0.2) uvBuffer[i + 2] += 1;
21924 if (x2 < 0.2) uvBuffer[i + 4] += 1;
21929 function pushVertex(vertex) {
21930 vertexBuffer.push(vertex.x, vertex.y, vertex.z);
21933 function getVertexByIndex(index, vertex) {
21934 var stride = index * 3;
21935 vertex.x = vertices[stride + 0];
21936 vertex.y = vertices[stride + 1];
21937 vertex.z = vertices[stride + 2];
21940 function correctUVs() {
21941 var a = new Vector3();
21942 var b = new Vector3();
21943 var c = new Vector3();
21944 var centroid = new Vector3();
21945 var uvA = new Vector2();
21946 var uvB = new Vector2();
21947 var uvC = new Vector2();
21949 for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
21950 a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
21951 b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
21952 c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
21953 uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
21954 uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
21955 uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
21956 centroid.copy(a).add(b).add(c).divideScalar(3);
21957 var azi = azimuth(centroid);
21958 correctUV(uvA, j + 0, a, azi);
21959 correctUV(uvB, j + 2, b, azi);
21960 correctUV(uvC, j + 4, c, azi);
21964 function correctUV(uv, stride, vector, azimuth) {
21965 if (azimuth < 0 && uv.x === 1) {
21966 uvBuffer[stride] = uv.x - 1;
21969 if (vector.x === 0 && vector.z === 0) {
21970 uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
21972 } // Angle around the Y axis, counter-clockwise when looking from above.
21975 function azimuth(vector) {
21976 return Math.atan2(vector.z, -vector.x);
21977 } // Angle above the XZ plane.
21980 function inclination(vector) {
21981 return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
21987 return PolyhedronBufferGeometry;
21990 var DodecahedronBufferGeometry = /*#__PURE__*/function (_PolyhedronBufferGeom) {
21991 _inheritsLoose(DodecahedronBufferGeometry, _PolyhedronBufferGeom);
21993 function DodecahedronBufferGeometry(radius, detail) {
21996 if (radius === void 0) {
22000 if (detail === void 0) {
22004 var t = (1 + Math.sqrt(5)) / 2;
22006 var vertices = [// (±1, ±1, ±1)
22007 -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/φ, ±φ)
22008 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
22009 -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
22010 -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
22011 var 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];
22012 _this = _PolyhedronBufferGeom.call(this, vertices, indices, radius, detail) || this;
22013 _this.type = 'DodecahedronBufferGeometry';
22014 _this.parameters = {
22021 return DodecahedronBufferGeometry;
22022 }(PolyhedronBufferGeometry);
22024 var DodecahedronGeometry = /*#__PURE__*/function (_Geometry) {
22025 _inheritsLoose(DodecahedronGeometry, _Geometry);
22027 function DodecahedronGeometry(radius, detail) {
22030 _this = _Geometry.call(this) || this;
22031 _this.type = 'DodecahedronGeometry';
22032 _this.parameters = {
22037 _this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
22039 _this.mergeVertices();
22044 return DodecahedronGeometry;
22047 var _v0$2 = new Vector3();
22049 var _v1$5 = new Vector3();
22051 var _normal$1 = new Vector3();
22053 var _triangle = new Triangle();
22055 var EdgesGeometry = /*#__PURE__*/function (_BufferGeometry) {
22056 _inheritsLoose(EdgesGeometry, _BufferGeometry);
22058 function EdgesGeometry(geometry, thresholdAngle) {
22061 _this = _BufferGeometry.call(this) || this;
22062 _this.type = 'EdgesGeometry';
22063 _this.parameters = {
22064 thresholdAngle: thresholdAngle
22066 thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
22068 if (geometry.isGeometry) {
22069 geometry = new BufferGeometry().fromGeometry(geometry);
22072 var precisionPoints = 4;
22073 var precision = Math.pow(10, precisionPoints);
22074 var thresholdDot = Math.cos(MathUtils.DEG2RAD * thresholdAngle);
22075 var indexAttr = geometry.getIndex();
22076 var positionAttr = geometry.getAttribute('position');
22077 var indexCount = indexAttr ? indexAttr.count : positionAttr.count;
22078 var indexArr = [0, 0, 0];
22079 var vertKeys = ['a', 'b', 'c'];
22080 var hashes = new Array(3);
22084 for (var i = 0; i < indexCount; i += 3) {
22086 indexArr[0] = indexAttr.getX(i);
22087 indexArr[1] = indexAttr.getX(i + 1);
22088 indexArr[2] = indexAttr.getX(i + 2);
22091 indexArr[1] = i + 1;
22092 indexArr[2] = i + 2;
22095 var a = _triangle.a,
22098 a.fromBufferAttribute(positionAttr, indexArr[0]);
22099 b.fromBufferAttribute(positionAttr, indexArr[1]);
22100 c.fromBufferAttribute(positionAttr, indexArr[2]);
22102 _triangle.getNormal(_normal$1); // create hashes for the edge from the vertices
22105 hashes[0] = Math.round(a.x * precision) + "," + Math.round(a.y * precision) + "," + Math.round(a.z * precision);
22106 hashes[1] = Math.round(b.x * precision) + "," + Math.round(b.y * precision) + "," + Math.round(b.z * precision);
22107 hashes[2] = Math.round(c.x * precision) + "," + Math.round(c.y * precision) + "," + Math.round(c.z * precision); // skip degenerate triangles
22109 if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
22111 } // iterate over every edge
22114 for (var j = 0; j < 3; j++) {
22115 // get the first and next vertex making up the edge
22116 var jNext = (j + 1) % 3;
22117 var vecHash0 = hashes[j];
22118 var vecHash1 = hashes[jNext];
22119 var v0 = _triangle[vertKeys[j]];
22120 var v1 = _triangle[vertKeys[jNext]];
22121 var hash = vecHash0 + "_" + vecHash1;
22122 var reverseHash = vecHash1 + "_" + vecHash0;
22124 if (reverseHash in edgeData && edgeData[reverseHash]) {
22125 // if we found a sibling edge add it into the vertex array if
22126 // it meets the angle threshold and delete the edge from the map.
22127 if (_normal$1.dot(edgeData[reverseHash].normal) <= thresholdDot) {
22128 vertices.push(v0.x, v0.y, v0.z);
22129 vertices.push(v1.x, v1.y, v1.z);
22132 edgeData[reverseHash] = null;
22133 } else if (!(hash in edgeData)) {
22134 // if we've already got an edge here then skip adding a new one
22136 index0: indexArr[j],
22137 index1: indexArr[jNext],
22138 normal: _normal$1.clone()
22142 } // iterate over all remaining, unmatched edges and add them to the vertex array
22145 for (var key in edgeData) {
22146 if (edgeData[key]) {
22147 var _edgeData$key = edgeData[key],
22148 index0 = _edgeData$key.index0,
22149 index1 = _edgeData$key.index1;
22151 _v0$2.fromBufferAttribute(positionAttr, index0);
22153 _v1$5.fromBufferAttribute(positionAttr, index1);
22155 vertices.push(_v0$2.x, _v0$2.y, _v0$2.z);
22156 vertices.push(_v1$5.x, _v1$5.y, _v1$5.z);
22160 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
22165 return EdgesGeometry;
22169 * Port from https://github.com/mapbox/earcut (v2.2.2)
22172 triangulate: function triangulate(data, holeIndices, dim) {
22174 var hasHoles = holeIndices && holeIndices.length;
22175 var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
22176 var outerNode = linkedList(data, 0, outerLen, dim, true);
22177 var triangles = [];
22178 if (!outerNode || outerNode.next === outerNode.prev) return triangles;
22179 var minX, minY, maxX, maxY, x, y, invSize;
22180 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
22182 if (data.length > 80 * dim) {
22183 minX = maxX = data[0];
22184 minY = maxY = data[1];
22186 for (var i = dim; i < outerLen; i += dim) {
22189 if (x < minX) minX = x;
22190 if (y < minY) minY = y;
22191 if (x > maxX) maxX = x;
22192 if (y > maxY) maxY = y;
22193 } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
22196 invSize = Math.max(maxX - minX, maxY - minY);
22197 invSize = invSize !== 0 ? 1 / invSize : 0;
22200 earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
22203 }; // create a circular doubly linked list from polygon points in the specified winding order
22205 function linkedList(data, start, end, dim, clockwise) {
22208 if (clockwise === signedArea(data, start, end, dim) > 0) {
22209 for (i = start; i < end; i += dim) {
22210 last = insertNode(i, data[i], data[i + 1], last);
22213 for (i = end - dim; i >= start; i -= dim) {
22214 last = insertNode(i, data[i], data[i + 1], last);
22218 if (last && equals(last, last.next)) {
22224 } // eliminate colinear or duplicate points
22227 function filterPoints(start, end) {
22228 if (!start) return start;
22229 if (!end) end = start;
22236 if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
22239 if (p === p.next) break;
22244 } while (again || p !== end);
22247 } // main ear slicing loop which triangulates a polygon (given as a linked list)
22250 function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
22251 if (!ear) return; // interlink polygon nodes in z-order
22253 if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
22256 next; // iterate through ears, slicing them one by one
22258 while (ear.prev !== ear.next) {
22262 if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
22263 // cut off the triangle
22264 triangles.push(prev.i / dim);
22265 triangles.push(ear.i / dim);
22266 triangles.push(next.i / dim);
22267 removeNode(ear); // skipping the next vertex leads to less sliver triangles
22274 ear = next; // if we looped through the whole remaining polygon and can't find any more ears
22276 if (ear === stop) {
22277 // try filtering points and slicing again
22279 earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
22280 } else if (pass === 1) {
22281 ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
22282 earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
22283 } else if (pass === 2) {
22284 splitEarcut(ear, triangles, dim, minX, minY, invSize);
22290 } // check whether a polygon node forms a valid ear with adjacent nodes
22293 function isEar(ear) {
22297 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
22298 // now make sure we don't have other points inside the potential ear
22300 var p = ear.next.next;
22302 while (p !== ear.prev) {
22303 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;
22310 function isEarHashed(ear, minX, minY, invSize) {
22314 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
22315 // triangle bbox; min & max are calculated like this for speed
22317 var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
22318 minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
22319 maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
22320 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;
22322 var minZ = zOrder(minTX, minTY, minX, minY, invSize),
22323 maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
22325 n = ear.nextZ; // look for points inside the triangle in both directions
22327 while (p && p.z >= minZ && n && n.z <= maxZ) {
22328 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;
22330 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;
22332 } // look for remaining points in decreasing z-order
22335 while (p && p.z >= minZ) {
22336 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;
22338 } // look for remaining points in increasing z-order
22341 while (n && n.z <= maxZ) {
22342 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;
22347 } // go through all polygon nodes and cure small local self-intersections
22350 function cureLocalIntersections(start, triangles, dim) {
22357 if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
22358 triangles.push(a.i / dim);
22359 triangles.push(p.i / dim);
22360 triangles.push(b.i / dim); // remove two nodes involved
22363 removeNode(p.next);
22368 } while (p !== start);
22370 return filterPoints(p);
22371 } // try splitting polygon into two and triangulate them independently
22374 function splitEarcut(start, triangles, dim, minX, minY, invSize) {
22375 // look for a valid diagonal that divides the polygon into two
22379 var b = a.next.next;
22381 while (b !== a.prev) {
22382 if (a.i !== b.i && isValidDiagonal(a, b)) {
22383 // split the polygon in two by the diagonal
22384 var c = splitPolygon(a, b); // filter colinear points around the cuts
22386 a = filterPoints(a, a.next);
22387 c = filterPoints(c, c.next); // run earcut on each half
22389 earcutLinked(a, triangles, dim, minX, minY, invSize);
22390 earcutLinked(c, triangles, dim, minX, minY, invSize);
22398 } while (a !== start);
22399 } // link every hole into the outer loop, producing a single-ring polygon without holes
22402 function eliminateHoles(data, holeIndices, outerNode, dim) {
22404 var i, len, start, end, list;
22406 for (i = 0, len = holeIndices.length; i < len; i++) {
22407 start = holeIndices[i] * dim;
22408 end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
22409 list = linkedList(data, start, end, dim, false);
22410 if (list === list.next) list.steiner = true;
22411 queue.push(getLeftmost(list));
22414 queue.sort(compareX); // process holes from left to right
22416 for (i = 0; i < queue.length; i++) {
22417 eliminateHole(queue[i], outerNode);
22418 outerNode = filterPoints(outerNode, outerNode.next);
22424 function compareX(a, b) {
22426 } // find a bridge between vertices that connects hole with an outer ring and and link it
22429 function eliminateHole(hole, outerNode) {
22430 outerNode = findHoleBridge(hole, outerNode);
22433 var b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
22435 filterPoints(outerNode, outerNode.next);
22436 filterPoints(b, b.next);
22438 } // David Eberly's algorithm for finding a bridge between hole and outer polygon
22441 function findHoleBridge(hole, outerNode) {
22445 var qx = -Infinity,
22446 m; // find a segment intersected by a ray from the hole's leftmost point to the left;
22447 // segment's endpoint with lesser x will be potential connection point
22450 if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
22451 var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
22453 if (x <= hx && x > qx) {
22457 if (hy === p.y) return p;
22458 if (hy === p.next.y) return p.next;
22461 m = p.x < p.next.x ? p : p.next;
22466 } while (p !== outerNode);
22468 if (!m) return null;
22469 if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
22470 // look for points inside the triangle of hole point, segment intersection and endpoint;
22471 // if there are no points found, we have a valid connection;
22472 // otherwise choose the point of the minimum angle with the ray as connection point
22477 var tanMin = Infinity,
22482 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)) {
22483 tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
22485 if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
22492 } while (p !== stop);
22495 } // whether sector in vertex m contains sector in vertex p in the same coordinates
22498 function sectorContainsSector(m, p) {
22499 return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
22500 } // interlink polygon nodes in z-order
22503 function indexCurve(start, minX, minY, invSize) {
22507 if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
22511 } while (p !== start);
22513 p.prevZ.nextZ = null;
22516 } // Simon Tatham's linked list merge sort algorithm
22517 // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
22520 function sortLinked(list) {
22542 for (i = 0; i < inSize; i++) {
22550 while (pSize > 0 || qSize > 0 && q) {
22551 if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
22561 if (tail) tail.nextZ = e;else list = e;
22571 } while (numMerges > 1);
22574 } // z-order of a point given coords and inverse of the longer side of data bbox
22577 function zOrder(x, y, minX, minY, invSize) {
22578 // coords are transformed into non-negative 15-bit integer range
22579 x = 32767 * (x - minX) * invSize;
22580 y = 32767 * (y - minY) * invSize;
22581 x = (x | x << 8) & 0x00FF00FF;
22582 x = (x | x << 4) & 0x0F0F0F0F;
22583 x = (x | x << 2) & 0x33333333;
22584 x = (x | x << 1) & 0x55555555;
22585 y = (y | y << 8) & 0x00FF00FF;
22586 y = (y | y << 4) & 0x0F0F0F0F;
22587 y = (y | y << 2) & 0x33333333;
22588 y = (y | y << 1) & 0x55555555;
22590 } // find the leftmost node of a polygon ring
22593 function getLeftmost(start) {
22598 if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
22600 } while (p !== start);
22603 } // check if a point lies within a convex triangle
22606 function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
22607 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;
22608 } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
22611 function isValidDiagonal(a, b) {
22612 return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
22613 locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
22614 area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
22615 equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
22616 } // signed area of a triangle
22619 function area(p, q, r) {
22620 return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
22621 } // check if two points are equal
22624 function equals(p1, p2) {
22625 return p1.x === p2.x && p1.y === p2.y;
22626 } // check if two segments intersect
22629 function intersects(p1, q1, p2, q2) {
22630 var o1 = sign(area(p1, q1, p2));
22631 var o2 = sign(area(p1, q1, q2));
22632 var o3 = sign(area(p2, q2, p1));
22633 var o4 = sign(area(p2, q2, q1));
22634 if (o1 !== o2 && o3 !== o4) return true; // general case
22636 if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
22638 if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
22640 if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
22642 if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
22645 } // for collinear points p, q, r, check if point q lies on segment pr
22648 function onSegment(p, q, r) {
22649 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);
22652 function sign(num) {
22653 return num > 0 ? 1 : num < 0 ? -1 : 0;
22654 } // check if a polygon diagonal intersects any polygon segments
22657 function intersectsPolygon(a, b) {
22661 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;
22666 } // check if a polygon diagonal is locally inside the polygon
22669 function locallyInside(a, b) {
22670 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;
22671 } // check if the middle point of a polygon diagonal is inside the polygon
22674 function middleInside(a, b) {
22677 var px = (a.x + b.x) / 2,
22678 py = (a.y + b.y) / 2;
22681 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;
22686 } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
22687 // if one belongs to the outer ring and another to a hole, it merges it into a single ring
22690 function splitPolygon(a, b) {
22691 var a2 = new Node(a.i, a.x, a.y),
22692 b2 = new Node(b.i, b.x, b.y),
22704 } // create a node and optionally link it with previous one (in a circular doubly linked list)
22707 function insertNode(i, x, y, last) {
22708 var p = new Node(i, x, y);
22714 p.next = last.next;
22716 last.next.prev = p;
22723 function removeNode(p) {
22724 p.next.prev = p.prev;
22725 p.prev.next = p.next;
22726 if (p.prevZ) p.prevZ.nextZ = p.nextZ;
22727 if (p.nextZ) p.nextZ.prevZ = p.prevZ;
22730 function Node(i, x, y) {
22731 // vertex index in coordinates array
22732 this.i = i; // vertex coordinates
22735 this.y = y; // previous and next vertex nodes in a polygon ring
22738 this.next = null; // z-order curve value
22740 this.z = null; // previous and next nodes in z-order
22743 this.nextZ = null; // indicates whether this is a steiner point
22745 this.steiner = false;
22748 function signedArea(data, start, end, dim) {
22751 for (var i = start, j = end - dim; i < end; i += dim) {
22752 sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
22760 // calculate area of the contour polygon
22761 area: function area(contour) {
22762 var n = contour.length;
22765 for (var p = n - 1, q = 0; q < n; p = q++) {
22766 a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
22771 isClockWise: function isClockWise(pts) {
22772 return ShapeUtils.area(pts) < 0;
22774 triangulateShape: function triangulateShape(contour, holes) {
22775 var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
22777 var holeIndices = []; // array of hole indices
22779 var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
22781 removeDupEndPts(contour);
22782 addContour(vertices, contour); //
22784 var holeIndex = contour.length;
22785 holes.forEach(removeDupEndPts);
22787 for (var i = 0; i < holes.length; i++) {
22788 holeIndices.push(holeIndex);
22789 holeIndex += holes[i].length;
22790 addContour(vertices, holes[i]);
22794 var triangles = Earcut.triangulate(vertices, holeIndices); //
22796 for (var _i = 0; _i < triangles.length; _i += 3) {
22797 faces.push(triangles.slice(_i, _i + 3));
22804 function removeDupEndPts(points) {
22805 var l = points.length;
22807 if (l > 2 && points[l - 1].equals(points[0])) {
22812 function addContour(vertices, contour) {
22813 for (var i = 0; i < contour.length; i++) {
22814 vertices.push(contour[i].x);
22815 vertices.push(contour[i].y);
22819 var ExtrudeBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
22820 _inheritsLoose(ExtrudeBufferGeometry, _BufferGeometry);
22822 function ExtrudeBufferGeometry(shapes, options) {
22825 _this = _BufferGeometry.call(this) || this;
22826 _this.type = 'ExtrudeBufferGeometry';
22827 _this.parameters = {
22831 shapes = Array.isArray(shapes) ? shapes : [shapes];
22833 var scope = _assertThisInitialized(_this);
22835 var verticesArray = [];
22838 for (var i = 0, l = shapes.length; i < l; i++) {
22839 var shape = shapes[i];
22841 } // build geometry
22844 _this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
22846 _this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
22848 _this.computeVertexNormals(); // functions
22851 function addShape(shape) {
22852 var placeholder = []; // options
22854 var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
22855 var steps = options.steps !== undefined ? options.steps : 1;
22856 var depth = options.depth !== undefined ? options.depth : 100;
22857 var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
22858 var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
22859 var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
22860 var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
22861 var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
22862 var extrudePath = options.extrudePath;
22863 var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
22865 if (options.amount !== undefined) {
22866 console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
22867 depth = options.amount;
22872 extrudeByPath = false;
22873 var splineTube, binormal, normal, position2;
22876 extrudePts = extrudePath.getSpacedPoints(steps);
22877 extrudeByPath = true;
22878 bevelEnabled = false; // bevels not supported for path extrusion
22879 // SETUP TNB variables
22880 // TODO1 - have a .isClosed in spline?
22882 splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
22884 binormal = new Vector3();
22885 normal = new Vector3();
22886 position2 = new Vector3();
22887 } // Safeguards if bevels are not enabled
22890 if (!bevelEnabled) {
22892 bevelThickness = 0;
22895 } // Variables initialization
22898 var shapePoints = shape.extractPoints(curveSegments);
22899 var vertices = shapePoints.shape;
22900 var holes = shapePoints.holes;
22901 var reverse = !ShapeUtils.isClockWise(vertices);
22904 vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
22906 for (var h = 0, hl = holes.length; h < hl; h++) {
22907 var ahole = holes[h];
22909 if (ShapeUtils.isClockWise(ahole)) {
22910 holes[h] = ahole.reverse();
22915 var faces = ShapeUtils.triangulateShape(vertices, holes);
22918 var contour = vertices; // vertices has all points but contour has only points of circumference
22920 for (var _h = 0, _hl = holes.length; _h < _hl; _h++) {
22921 var _ahole = holes[_h];
22922 vertices = vertices.concat(_ahole);
22925 function scalePt2(pt, vec, size) {
22926 if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
22927 return vec.clone().multiplyScalar(size).add(pt);
22930 var vlen = vertices.length,
22931 flen = faces.length; // Find directions for point movement
22933 function getBevelVec(inPt, inPrev, inNext) {
22934 // computes for inPt the corresponding point inPt' on a new contour
22935 // shifted by 1 unit (length of normalized vector) to the left
22936 // if we walk along contour clockwise, this new contour is outside the old one
22938 // inPt' is the intersection of the two lines parallel to the two
22939 // adjacent edges of inPt at a distance of 1 unit on the left side.
22940 var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
22941 // good reading for geometry algorithms (here: line-line intersection)
22942 // http://geomalgorithms.com/a05-_intersect-1.html
22944 var v_prev_x = inPt.x - inPrev.x,
22945 v_prev_y = inPt.y - inPrev.y;
22946 var v_next_x = inNext.x - inPt.x,
22947 v_next_y = inNext.y - inPt.y;
22948 var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
22950 var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
22952 if (Math.abs(collinear0) > Number.EPSILON) {
22954 // length of vectors for normalizing
22955 var v_prev_len = Math.sqrt(v_prev_lensq);
22956 var v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the left
22958 var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
22959 var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
22960 var ptNextShift_x = inNext.x - v_next_y / v_next_len;
22961 var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
22963 var sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); // vector from inPt to intersection point
22965 v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
22966 v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
22967 // but prevent crazy spikes
22969 var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
22971 if (v_trans_lensq <= 2) {
22972 return new Vector2(v_trans_x, v_trans_y);
22974 shrink_by = Math.sqrt(v_trans_lensq / 2);
22977 // handle special case of collinear edges
22978 var direction_eq = false; // assumes: opposite
22980 if (v_prev_x > Number.EPSILON) {
22981 if (v_next_x > Number.EPSILON) {
22982 direction_eq = true;
22985 if (v_prev_x < -Number.EPSILON) {
22986 if (v_next_x < -Number.EPSILON) {
22987 direction_eq = true;
22990 if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
22991 direction_eq = true;
22996 if (direction_eq) {
22997 // console.log("Warning: lines are a straight sequence");
22998 v_trans_x = -v_prev_y;
22999 v_trans_y = v_prev_x;
23000 shrink_by = Math.sqrt(v_prev_lensq);
23002 // console.log("Warning: lines are a straight spike");
23003 v_trans_x = v_prev_x;
23004 v_trans_y = v_prev_y;
23005 shrink_by = Math.sqrt(v_prev_lensq / 2);
23009 return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
23012 var contourMovements = [];
23014 for (var _i = 0, il = contour.length, j = il - 1, k = _i + 1; _i < il; _i++, j++, k++) {
23015 if (j === il) j = 0;
23016 if (k === il) k = 0; // (j)---(i)---(k)
23017 // console.log('i,j,k', i, j , k)
23019 contourMovements[_i] = getBevelVec(contour[_i], contour[j], contour[k]);
23022 var holesMovements = [];
23023 var oneHoleMovements,
23024 verticesMovements = contourMovements.concat();
23026 for (var _h2 = 0, _hl2 = holes.length; _h2 < _hl2; _h2++) {
23027 var _ahole2 = holes[_h2];
23028 oneHoleMovements = [];
23030 for (var _i2 = 0, _il = _ahole2.length, _j = _il - 1, _k = _i2 + 1; _i2 < _il; _i2++, _j++, _k++) {
23031 if (_j === _il) _j = 0;
23032 if (_k === _il) _k = 0; // (j)---(i)---(k)
23034 oneHoleMovements[_i2] = getBevelVec(_ahole2[_i2], _ahole2[_j], _ahole2[_k]);
23037 holesMovements.push(oneHoleMovements);
23038 verticesMovements = verticesMovements.concat(oneHoleMovements);
23039 } // Loop bevelSegments, 1 for the front, 1 for the back
23042 for (var b = 0; b < bevelSegments; b++) {
23043 //for ( b = bevelSegments; b > 0; b -- ) {
23044 var t = b / bevelSegments;
23045 var z = bevelThickness * Math.cos(t * Math.PI / 2);
23047 var _bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
23050 for (var _i3 = 0, _il2 = contour.length; _i3 < _il2; _i3++) {
23051 var vert = scalePt2(contour[_i3], contourMovements[_i3], _bs);
23052 v(vert.x, vert.y, -z);
23056 for (var _h3 = 0, _hl3 = holes.length; _h3 < _hl3; _h3++) {
23057 var _ahole3 = holes[_h3];
23058 oneHoleMovements = holesMovements[_h3];
23060 for (var _i4 = 0, _il3 = _ahole3.length; _i4 < _il3; _i4++) {
23061 var _vert = scalePt2(_ahole3[_i4], oneHoleMovements[_i4], _bs);
23063 v(_vert.x, _vert.y, -z);
23068 var bs = bevelSize + bevelOffset; // Back facing vertices
23070 for (var _i5 = 0; _i5 < vlen; _i5++) {
23071 var _vert2 = bevelEnabled ? scalePt2(vertices[_i5], verticesMovements[_i5], bs) : vertices[_i5];
23073 if (!extrudeByPath) {
23074 v(_vert2.x, _vert2.y, 0);
23076 // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
23077 normal.copy(splineTube.normals[0]).multiplyScalar(_vert2.x);
23078 binormal.copy(splineTube.binormals[0]).multiplyScalar(_vert2.y);
23079 position2.copy(extrudePts[0]).add(normal).add(binormal);
23080 v(position2.x, position2.y, position2.z);
23082 } // Add stepped vertices...
23083 // Including front facing vertices
23086 for (var s = 1; s <= steps; s++) {
23087 for (var _i6 = 0; _i6 < vlen; _i6++) {
23088 var _vert3 = bevelEnabled ? scalePt2(vertices[_i6], verticesMovements[_i6], bs) : vertices[_i6];
23090 if (!extrudeByPath) {
23091 v(_vert3.x, _vert3.y, depth / steps * s);
23093 // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
23094 normal.copy(splineTube.normals[s]).multiplyScalar(_vert3.x);
23095 binormal.copy(splineTube.binormals[s]).multiplyScalar(_vert3.y);
23096 position2.copy(extrudePts[s]).add(normal).add(binormal);
23097 v(position2.x, position2.y, position2.z);
23100 } // Add bevel segments planes
23101 //for ( b = 1; b <= bevelSegments; b ++ ) {
23104 for (var _b = bevelSegments - 1; _b >= 0; _b--) {
23105 var _t = _b / bevelSegments;
23107 var _z = bevelThickness * Math.cos(_t * Math.PI / 2);
23109 var _bs2 = bevelSize * Math.sin(_t * Math.PI / 2) + bevelOffset; // contract shape
23112 for (var _i7 = 0, _il4 = contour.length; _i7 < _il4; _i7++) {
23113 var _vert4 = scalePt2(contour[_i7], contourMovements[_i7], _bs2);
23115 v(_vert4.x, _vert4.y, depth + _z);
23119 for (var _h4 = 0, _hl4 = holes.length; _h4 < _hl4; _h4++) {
23120 var _ahole4 = holes[_h4];
23121 oneHoleMovements = holesMovements[_h4];
23123 for (var _i8 = 0, _il5 = _ahole4.length; _i8 < _il5; _i8++) {
23124 var _vert5 = scalePt2(_ahole4[_i8], oneHoleMovements[_i8], _bs2);
23126 if (!extrudeByPath) {
23127 v(_vert5.x, _vert5.y, depth + _z);
23129 v(_vert5.x, _vert5.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + _z);
23135 // Top and bottom faces
23138 buildLidFaces(); // Sides faces
23140 buildSideFaces(); ///// Internal functions
23142 function buildLidFaces() {
23143 var start = verticesArray.length / 3;
23145 if (bevelEnabled) {
23146 var layer = 0; // steps + 1
23148 var offset = vlen * layer; // Bottom faces
23150 for (var _i9 = 0; _i9 < flen; _i9++) {
23151 var face = faces[_i9];
23152 f3(face[2] + offset, face[1] + offset, face[0] + offset);
23155 layer = steps + bevelSegments * 2;
23156 offset = vlen * layer; // Top faces
23158 for (var _i10 = 0; _i10 < flen; _i10++) {
23159 var _face = faces[_i10];
23160 f3(_face[0] + offset, _face[1] + offset, _face[2] + offset);
23164 for (var _i11 = 0; _i11 < flen; _i11++) {
23165 var _face2 = faces[_i11];
23166 f3(_face2[2], _face2[1], _face2[0]);
23170 for (var _i12 = 0; _i12 < flen; _i12++) {
23171 var _face3 = faces[_i12];
23172 f3(_face3[0] + vlen * steps, _face3[1] + vlen * steps, _face3[2] + vlen * steps);
23176 scope.addGroup(start, verticesArray.length / 3 - start, 0);
23177 } // Create faces for the z-sides of the shape
23180 function buildSideFaces() {
23181 var start = verticesArray.length / 3;
23182 var layeroffset = 0;
23183 sidewalls(contour, layeroffset);
23184 layeroffset += contour.length;
23186 for (var _h5 = 0, _hl5 = holes.length; _h5 < _hl5; _h5++) {
23187 var _ahole5 = holes[_h5];
23188 sidewalls(_ahole5, layeroffset); //, true
23190 layeroffset += _ahole5.length;
23193 scope.addGroup(start, verticesArray.length / 3 - start, 1);
23196 function sidewalls(contour, layeroffset) {
23197 var i = contour.length;
23204 if (_k2 < 0) _k2 = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
23206 for (var _s = 0, sl = steps + bevelSegments * 2; _s < sl; _s++) {
23207 var slen1 = vlen * _s;
23208 var slen2 = vlen * (_s + 1);
23210 var a = layeroffset + _j2 + slen1,
23211 _b2 = layeroffset + _k2 + slen1,
23212 c = layeroffset + _k2 + slen2,
23213 d = layeroffset + _j2 + slen2;
23220 function v(x, y, z) {
23221 placeholder.push(x);
23222 placeholder.push(y);
23223 placeholder.push(z);
23226 function f3(a, b, c) {
23230 var nextIndex = verticesArray.length / 3;
23231 var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
23237 function f4(a, b, c, d) {
23244 var nextIndex = verticesArray.length / 3;
23245 var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
23254 function addVertex(index) {
23255 verticesArray.push(placeholder[index * 3 + 0]);
23256 verticesArray.push(placeholder[index * 3 + 1]);
23257 verticesArray.push(placeholder[index * 3 + 2]);
23260 function addUV(vector2) {
23261 uvArray.push(vector2.x);
23262 uvArray.push(vector2.y);
23269 var _proto = ExtrudeBufferGeometry.prototype;
23271 _proto.toJSON = function toJSON() {
23272 var data = BufferGeometry.prototype.toJSON.call(this);
23273 var shapes = this.parameters.shapes;
23274 var options = this.parameters.options;
23275 return _toJSON(shapes, options, data);
23278 return ExtrudeBufferGeometry;
23281 var WorldUVGenerator = {
23282 generateTopUV: function generateTopUV(geometry, vertices, indexA, indexB, indexC) {
23283 var a_x = vertices[indexA * 3];
23284 var a_y = vertices[indexA * 3 + 1];
23285 var b_x = vertices[indexB * 3];
23286 var b_y = vertices[indexB * 3 + 1];
23287 var c_x = vertices[indexC * 3];
23288 var c_y = vertices[indexC * 3 + 1];
23289 return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
23291 generateSideWallUV: function generateSideWallUV(geometry, vertices, indexA, indexB, indexC, indexD) {
23292 var a_x = vertices[indexA * 3];
23293 var a_y = vertices[indexA * 3 + 1];
23294 var a_z = vertices[indexA * 3 + 2];
23295 var b_x = vertices[indexB * 3];
23296 var b_y = vertices[indexB * 3 + 1];
23297 var b_z = vertices[indexB * 3 + 2];
23298 var c_x = vertices[indexC * 3];
23299 var c_y = vertices[indexC * 3 + 1];
23300 var c_z = vertices[indexC * 3 + 2];
23301 var d_x = vertices[indexD * 3];
23302 var d_y = vertices[indexD * 3 + 1];
23303 var d_z = vertices[indexD * 3 + 2];
23305 if (Math.abs(a_y - b_y) < 0.01) {
23306 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)];
23308 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)];
23313 function _toJSON(shapes, options, data) {
23316 if (Array.isArray(shapes)) {
23317 for (var i = 0, l = shapes.length; i < l; i++) {
23318 var shape = shapes[i];
23319 data.shapes.push(shape.uuid);
23322 data.shapes.push(shapes.uuid);
23325 if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
23329 var ExtrudeGeometry = /*#__PURE__*/function (_Geometry) {
23330 _inheritsLoose(ExtrudeGeometry, _Geometry);
23332 function ExtrudeGeometry(shapes, options) {
23335 _this = _Geometry.call(this) || this;
23336 _this.type = 'ExtrudeGeometry';
23337 _this.parameters = {
23342 _this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
23344 _this.mergeVertices();
23349 var _proto = ExtrudeGeometry.prototype;
23351 _proto.toJSON = function toJSON() {
23352 var data = _Geometry.prototype.toJSON.call(this);
23354 var shapes = this.parameters.shapes;
23355 var options = this.parameters.options;
23356 return _toJSON$1(shapes, options, data);
23359 return ExtrudeGeometry;
23362 function _toJSON$1(shapes, options, data) {
23365 if (Array.isArray(shapes)) {
23366 for (var i = 0, l = shapes.length; i < l; i++) {
23367 var shape = shapes[i];
23368 data.shapes.push(shape.uuid);
23371 data.shapes.push(shapes.uuid);
23374 if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
23378 var IcosahedronBufferGeometry = /*#__PURE__*/function (_PolyhedronBufferGeom) {
23379 _inheritsLoose(IcosahedronBufferGeometry, _PolyhedronBufferGeom);
23381 function IcosahedronBufferGeometry(radius, detail) {
23384 if (radius === void 0) {
23388 if (detail === void 0) {
23392 var t = (1 + Math.sqrt(5)) / 2;
23393 var vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];
23394 var 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];
23395 _this = _PolyhedronBufferGeom.call(this, vertices, indices, radius, detail) || this;
23396 _this.type = 'IcosahedronBufferGeometry';
23397 _this.parameters = {
23404 return IcosahedronBufferGeometry;
23405 }(PolyhedronBufferGeometry);
23407 var IcosahedronGeometry = /*#__PURE__*/function (_Geometry) {
23408 _inheritsLoose(IcosahedronGeometry, _Geometry);
23410 function IcosahedronGeometry(radius, detail) {
23413 _this = _Geometry.call(this) || this;
23414 _this.type = 'IcosahedronGeometry';
23415 _this.parameters = {
23420 _this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
23422 _this.mergeVertices();
23427 return IcosahedronGeometry;
23430 var LatheBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
23431 _inheritsLoose(LatheBufferGeometry, _BufferGeometry);
23433 function LatheBufferGeometry(points, segments, phiStart, phiLength) {
23436 if (segments === void 0) {
23440 if (phiStart === void 0) {
23444 if (phiLength === void 0) {
23445 phiLength = Math.PI * 2;
23448 _this = _BufferGeometry.call(this) || this;
23449 _this.type = 'LatheBufferGeometry';
23450 _this.parameters = {
23452 segments: segments,
23453 phiStart: phiStart,
23454 phiLength: phiLength
23456 segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
23458 phiLength = MathUtils.clamp(phiLength, 0, Math.PI * 2); // buffers
23462 var uvs = []; // helper variables
23464 var inverseSegments = 1.0 / segments;
23465 var vertex = new Vector3();
23466 var uv = new Vector2(); // generate vertices and uvs
23468 for (var i = 0; i <= segments; i++) {
23469 var phi = phiStart + i * inverseSegments * phiLength;
23470 var sin = Math.sin(phi);
23471 var cos = Math.cos(phi);
23473 for (var j = 0; j <= points.length - 1; j++) {
23475 vertex.x = points[j].x * sin;
23476 vertex.y = points[j].y;
23477 vertex.z = points[j].x * cos;
23478 vertices.push(vertex.x, vertex.y, vertex.z); // uv
23480 uv.x = i / segments;
23481 uv.y = j / (points.length - 1);
23482 uvs.push(uv.x, uv.y);
23487 for (var _i = 0; _i < segments; _i++) {
23488 for (var _j = 0; _j < points.length - 1; _j++) {
23489 var base = _j + _i * points.length;
23491 var b = base + points.length;
23492 var c = base + points.length + 1;
23493 var d = base + 1; // faces
23495 indices.push(a, b, d);
23496 indices.push(b, c, d);
23498 } // build geometry
23501 _this.setIndex(indices);
23503 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
23505 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
23508 _this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
23509 // because the corresponding vertices are identical (but still have different UVs).
23512 if (phiLength === Math.PI * 2) {
23513 var normals = _this.attributes.normal.array;
23514 var n1 = new Vector3();
23515 var n2 = new Vector3();
23516 var n = new Vector3(); // this is the buffer offset for the last line of vertices
23518 var _base = segments * points.length * 3;
23520 for (var _i2 = 0, _j2 = 0; _i2 < points.length; _i2++, _j2 += 3) {
23521 // select the normal of the vertex in the first line
23522 n1.x = normals[_j2 + 0];
23523 n1.y = normals[_j2 + 1];
23524 n1.z = normals[_j2 + 2]; // select the normal of the vertex in the last line
23526 n2.x = normals[_base + _j2 + 0];
23527 n2.y = normals[_base + _j2 + 1];
23528 n2.z = normals[_base + _j2 + 2]; // average normals
23530 n.addVectors(n1, n2).normalize(); // assign the new values to both normals
23532 normals[_j2 + 0] = normals[_base + _j2 + 0] = n.x;
23533 normals[_j2 + 1] = normals[_base + _j2 + 1] = n.y;
23534 normals[_j2 + 2] = normals[_base + _j2 + 2] = n.z;
23541 return LatheBufferGeometry;
23544 var LatheGeometry = /*#__PURE__*/function (_Geometry) {
23545 _inheritsLoose(LatheGeometry, _Geometry);
23547 function LatheGeometry(points, segments, phiStart, phiLength) {
23550 _this = _Geometry.call(this) || this;
23551 _this.type = 'LatheGeometry';
23552 _this.parameters = {
23554 segments: segments,
23555 phiStart: phiStart,
23556 phiLength: phiLength
23559 _this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
23561 _this.mergeVertices();
23566 return LatheGeometry;
23569 var OctahedronBufferGeometry = /*#__PURE__*/function (_PolyhedronBufferGeom) {
23570 _inheritsLoose(OctahedronBufferGeometry, _PolyhedronBufferGeom);
23572 function OctahedronBufferGeometry(radius, detail) {
23575 if (radius === void 0) {
23579 if (detail === void 0) {
23583 var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
23584 var 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];
23585 _this = _PolyhedronBufferGeom.call(this, vertices, indices, radius, detail) || this;
23586 _this.type = 'OctahedronBufferGeometry';
23587 _this.parameters = {
23594 return OctahedronBufferGeometry;
23595 }(PolyhedronBufferGeometry);
23597 var OctahedronGeometry = /*#__PURE__*/function (_Geometry) {
23598 _inheritsLoose(OctahedronGeometry, _Geometry);
23600 function OctahedronGeometry(radius, detail) {
23603 _this = _Geometry.call(this) || this;
23604 _this.type = 'OctahedronGeometry';
23605 _this.parameters = {
23610 _this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
23612 _this.mergeVertices();
23617 return OctahedronGeometry;
23621 * Parametric Surfaces Geometry
23622 * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
23625 function ParametricBufferGeometry(func, slices, stacks) {
23626 BufferGeometry.call(this);
23627 this.type = 'ParametricBufferGeometry';
23628 this.parameters = {
23639 var normal = new Vector3();
23640 var p0 = new Vector3(),
23641 p1 = new Vector3();
23642 var pu = new Vector3(),
23643 pv = new Vector3();
23645 if (func.length < 3) {
23646 console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
23647 } // generate vertices, normals and uvs
23650 var sliceCount = slices + 1;
23652 for (var i = 0; i <= stacks; i++) {
23653 var v = i / stacks;
23655 for (var j = 0; j <= slices; j++) {
23656 var u = j / slices; // vertex
23659 vertices.push(p0.x, p0.y, p0.z); // normal
23660 // approximate tangent vectors via finite differences
23662 if (u - EPS >= 0) {
23663 func(u - EPS, v, p1);
23664 pu.subVectors(p0, p1);
23666 func(u + EPS, v, p1);
23667 pu.subVectors(p1, p0);
23670 if (v - EPS >= 0) {
23671 func(u, v - EPS, p1);
23672 pv.subVectors(p0, p1);
23674 func(u, v + EPS, p1);
23675 pv.subVectors(p1, p0);
23676 } // cross product of tangent vectors returns surface normal
23679 normal.crossVectors(pu, pv).normalize();
23680 normals.push(normal.x, normal.y, normal.z); // uv
23684 } // generate indices
23687 for (var _i = 0; _i < stacks; _i++) {
23688 for (var _j = 0; _j < slices; _j++) {
23689 var a = _i * sliceCount + _j;
23690 var b = _i * sliceCount + _j + 1;
23691 var c = (_i + 1) * sliceCount + _j + 1;
23692 var d = (_i + 1) * sliceCount + _j; // faces one and two
23694 indices.push(a, b, d);
23695 indices.push(b, c, d);
23697 } // build geometry
23700 this.setIndex(indices);
23701 this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
23702 this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
23703 this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
23706 ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
23707 ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
23710 * Parametric Surfaces Geometry
23711 * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
23714 function ParametricGeometry(func, slices, stacks) {
23715 Geometry.call(this);
23716 this.type = 'ParametricGeometry';
23717 this.parameters = {
23722 this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
23723 this.mergeVertices();
23726 ParametricGeometry.prototype = Object.create(Geometry.prototype);
23727 ParametricGeometry.prototype.constructor = ParametricGeometry;
23729 var PlaneGeometry = /*#__PURE__*/function (_Geometry) {
23730 _inheritsLoose(PlaneGeometry, _Geometry);
23732 function PlaneGeometry(width, height, widthSegments, heightSegments) {
23735 _this = _Geometry.call(this) || this;
23736 _this.type = 'PlaneGeometry';
23737 _this.parameters = {
23740 widthSegments: widthSegments,
23741 heightSegments: heightSegments
23744 _this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
23746 _this.mergeVertices();
23751 return PlaneGeometry;
23754 var PolyhedronGeometry = /*#__PURE__*/function (_Geometry) {
23755 _inheritsLoose(PolyhedronGeometry, _Geometry);
23757 function PolyhedronGeometry(vertices, indices, radius, detail) {
23760 _this = _Geometry.call(this) || this;
23761 _this.type = 'PolyhedronGeometry';
23762 _this.parameters = {
23763 vertices: vertices,
23769 _this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
23771 _this.mergeVertices();
23776 return PolyhedronGeometry;
23779 var RingBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
23780 _inheritsLoose(RingBufferGeometry, _BufferGeometry);
23782 function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
23785 if (innerRadius === void 0) {
23789 if (outerRadius === void 0) {
23793 if (thetaSegments === void 0) {
23797 if (phiSegments === void 0) {
23801 if (thetaStart === void 0) {
23805 if (thetaLength === void 0) {
23806 thetaLength = Math.PI * 2;
23809 _this = _BufferGeometry.call(this) || this;
23810 _this.type = 'RingBufferGeometry';
23811 _this.parameters = {
23812 innerRadius: innerRadius,
23813 outerRadius: outerRadius,
23814 thetaSegments: thetaSegments,
23815 phiSegments: phiSegments,
23816 thetaStart: thetaStart,
23817 thetaLength: thetaLength
23819 thetaSegments = Math.max(3, thetaSegments);
23820 phiSegments = Math.max(1, phiSegments); // buffers
23825 var uvs = []; // some helper variables
23827 var radius = innerRadius;
23828 var radiusStep = (outerRadius - innerRadius) / phiSegments;
23829 var vertex = new Vector3();
23830 var uv = new Vector2(); // generate vertices, normals and uvs
23832 for (var j = 0; j <= phiSegments; j++) {
23833 for (var i = 0; i <= thetaSegments; i++) {
23834 // values are generate from the inside of the ring to the outside
23835 var segment = thetaStart + i / thetaSegments * thetaLength; // vertex
23837 vertex.x = radius * Math.cos(segment);
23838 vertex.y = radius * Math.sin(segment);
23839 vertices.push(vertex.x, vertex.y, vertex.z); // normal
23841 normals.push(0, 0, 1); // uv
23843 uv.x = (vertex.x / outerRadius + 1) / 2;
23844 uv.y = (vertex.y / outerRadius + 1) / 2;
23845 uvs.push(uv.x, uv.y);
23846 } // increase the radius for next row of vertices
23849 radius += radiusStep;
23853 for (var _j = 0; _j < phiSegments; _j++) {
23854 var thetaSegmentLevel = _j * (thetaSegments + 1);
23856 for (var _i = 0; _i < thetaSegments; _i++) {
23857 var _segment = _i + thetaSegmentLevel;
23860 var b = _segment + thetaSegments + 1;
23861 var c = _segment + thetaSegments + 2;
23862 var d = _segment + 1; // faces
23864 indices.push(a, b, d);
23865 indices.push(b, c, d);
23867 } // build geometry
23870 _this.setIndex(indices);
23872 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
23874 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
23876 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
23881 return RingBufferGeometry;
23884 var RingGeometry = /*#__PURE__*/function (_Geometry) {
23885 _inheritsLoose(RingGeometry, _Geometry);
23887 function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
23890 _this = _Geometry.call(this) || this;
23891 _this.type = 'RingGeometry';
23892 _this.parameters = {
23893 innerRadius: innerRadius,
23894 outerRadius: outerRadius,
23895 thetaSegments: thetaSegments,
23896 phiSegments: phiSegments,
23897 thetaStart: thetaStart,
23898 thetaLength: thetaLength
23901 _this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
23903 _this.mergeVertices();
23908 return RingGeometry;
23911 var ShapeBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
23912 _inheritsLoose(ShapeBufferGeometry, _BufferGeometry);
23914 function ShapeBufferGeometry(shapes, curveSegments) {
23917 if (curveSegments === void 0) {
23918 curveSegments = 12;
23921 _this = _BufferGeometry.call(this) || this;
23922 _this.type = 'ShapeBufferGeometry';
23923 _this.parameters = {
23925 curveSegments: curveSegments
23931 var uvs = []; // helper variables
23933 var groupStart = 0;
23934 var groupCount = 0; // allow single and array values for "shapes" parameter
23936 if (Array.isArray(shapes) === false) {
23939 for (var i = 0; i < shapes.length; i++) {
23940 addShape(shapes[i]);
23942 _this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
23945 groupStart += groupCount;
23948 } // build geometry
23951 _this.setIndex(indices);
23953 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
23955 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
23957 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
23960 function addShape(shape) {
23961 var indexOffset = vertices.length / 3;
23962 var points = shape.extractPoints(curveSegments);
23963 var shapeVertices = points.shape;
23964 var shapeHoles = points.holes; // check direction of vertices
23966 if (ShapeUtils.isClockWise(shapeVertices) === false) {
23967 shapeVertices = shapeVertices.reverse();
23970 for (var _i = 0, l = shapeHoles.length; _i < l; _i++) {
23971 var shapeHole = shapeHoles[_i];
23973 if (ShapeUtils.isClockWise(shapeHole) === true) {
23974 shapeHoles[_i] = shapeHole.reverse();
23978 var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
23980 for (var _i2 = 0, _l = shapeHoles.length; _i2 < _l; _i2++) {
23981 var _shapeHole = shapeHoles[_i2];
23982 shapeVertices = shapeVertices.concat(_shapeHole);
23983 } // vertices, normals, uvs
23986 for (var _i3 = 0, _l2 = shapeVertices.length; _i3 < _l2; _i3++) {
23987 var vertex = shapeVertices[_i3];
23988 vertices.push(vertex.x, vertex.y, 0);
23989 normals.push(0, 0, 1);
23990 uvs.push(vertex.x, vertex.y); // world uvs
23994 for (var _i4 = 0, _l3 = faces.length; _i4 < _l3; _i4++) {
23995 var face = faces[_i4];
23996 var a = face[0] + indexOffset;
23997 var b = face[1] + indexOffset;
23998 var c = face[2] + indexOffset;
23999 indices.push(a, b, c);
24007 var _proto = ShapeBufferGeometry.prototype;
24009 _proto.toJSON = function toJSON() {
24010 var data = BufferGeometry.prototype.toJSON.call(this);
24011 var shapes = this.parameters.shapes;
24012 return _toJSON$2(shapes, data);
24015 return ShapeBufferGeometry;
24018 function _toJSON$2(shapes, data) {
24021 if (Array.isArray(shapes)) {
24022 for (var i = 0, l = shapes.length; i < l; i++) {
24023 var shape = shapes[i];
24024 data.shapes.push(shape.uuid);
24027 data.shapes.push(shapes.uuid);
24033 var ShapeGeometry = /*#__PURE__*/function (_Geometry) {
24034 _inheritsLoose(ShapeGeometry, _Geometry);
24036 function ShapeGeometry(shapes, curveSegments) {
24039 _this = _Geometry.call(this) || this;
24040 _this.type = 'ShapeGeometry';
24042 if (typeof curveSegments === 'object') {
24043 console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
24044 curveSegments = curveSegments.curveSegments;
24047 _this.parameters = {
24049 curveSegments: curveSegments
24052 _this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
24054 _this.mergeVertices();
24059 var _proto = ShapeGeometry.prototype;
24061 _proto.toJSON = function toJSON() {
24062 var data = Geometry.prototype.toJSON.call(this);
24063 var shapes = this.parameters.shapes;
24064 return _toJSON$3(shapes, data);
24067 return ShapeGeometry;
24070 function _toJSON$3(shapes, data) {
24073 if (Array.isArray(shapes)) {
24074 for (var i = 0, l = shapes.length; i < l; i++) {
24075 var shape = shapes[i];
24076 data.shapes.push(shape.uuid);
24079 data.shapes.push(shapes.uuid);
24085 var SphereBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
24086 _inheritsLoose(SphereBufferGeometry, _BufferGeometry);
24088 function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
24091 if (radius === void 0) {
24095 if (widthSegments === void 0) {
24099 if (heightSegments === void 0) {
24100 heightSegments = 6;
24103 if (phiStart === void 0) {
24107 if (phiLength === void 0) {
24108 phiLength = Math.PI * 2;
24111 if (thetaStart === void 0) {
24115 if (thetaLength === void 0) {
24116 thetaLength = Math.PI;
24119 _this = _BufferGeometry.call(this) || this;
24120 _this.type = 'SphereBufferGeometry';
24121 _this.parameters = {
24123 widthSegments: widthSegments,
24124 heightSegments: heightSegments,
24125 phiStart: phiStart,
24126 phiLength: phiLength,
24127 thetaStart: thetaStart,
24128 thetaLength: thetaLength
24130 widthSegments = Math.max(3, Math.floor(widthSegments));
24131 heightSegments = Math.max(2, Math.floor(heightSegments));
24132 var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
24135 var vertex = new Vector3();
24136 var normal = new Vector3(); // buffers
24141 var uvs = []; // generate vertices, normals and uvs
24143 for (var iy = 0; iy <= heightSegments; iy++) {
24144 var verticesRow = [];
24145 var v = iy / heightSegments; // special case for the poles
24149 if (iy == 0 && thetaStart == 0) {
24150 uOffset = 0.5 / widthSegments;
24151 } else if (iy == heightSegments && thetaEnd == Math.PI) {
24152 uOffset = -0.5 / widthSegments;
24155 for (var ix = 0; ix <= widthSegments; ix++) {
24156 var u = ix / widthSegments; // vertex
24158 vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
24159 vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
24160 vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
24161 vertices.push(vertex.x, vertex.y, vertex.z); // normal
24163 normal.copy(vertex).normalize();
24164 normals.push(normal.x, normal.y, normal.z); // uv
24166 uvs.push(u + uOffset, 1 - v);
24167 verticesRow.push(index++);
24170 grid.push(verticesRow);
24174 for (var _iy = 0; _iy < heightSegments; _iy++) {
24175 for (var _ix = 0; _ix < widthSegments; _ix++) {
24176 var a = grid[_iy][_ix + 1];
24177 var b = grid[_iy][_ix];
24178 var c = grid[_iy + 1][_ix];
24179 var d = grid[_iy + 1][_ix + 1];
24180 if (_iy !== 0 || thetaStart > 0) indices.push(a, b, d);
24181 if (_iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
24183 } // build geometry
24186 _this.setIndex(indices);
24188 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
24190 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
24192 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
24197 return SphereBufferGeometry;
24200 var SphereGeometry = /*#__PURE__*/function (_Geometry) {
24201 _inheritsLoose(SphereGeometry, _Geometry);
24203 function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
24206 _this = _Geometry.call(this) || this;
24207 _this.type = 'SphereGeometry';
24208 _this.parameters = {
24210 widthSegments: widthSegments,
24211 heightSegments: heightSegments,
24212 phiStart: phiStart,
24213 phiLength: phiLength,
24214 thetaStart: thetaStart,
24215 thetaLength: thetaLength
24218 _this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
24220 _this.mergeVertices();
24225 return SphereGeometry;
24228 var TetrahedronBufferGeometry = /*#__PURE__*/function (_PolyhedronBufferGeom) {
24229 _inheritsLoose(TetrahedronBufferGeometry, _PolyhedronBufferGeom);
24231 function TetrahedronBufferGeometry(radius, detail) {
24234 if (radius === void 0) {
24238 if (detail === void 0) {
24242 var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
24243 var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
24244 _this = _PolyhedronBufferGeom.call(this, vertices, indices, radius, detail) || this;
24245 _this.type = 'TetrahedronBufferGeometry';
24246 _this.parameters = {
24253 return TetrahedronBufferGeometry;
24254 }(PolyhedronBufferGeometry);
24256 var TetrahedronGeometry = /*#__PURE__*/function (_Geometry) {
24257 _inheritsLoose(TetrahedronGeometry, _Geometry);
24259 function TetrahedronGeometry(radius, detail) {
24262 _this = _Geometry.call(this) || this;
24263 _this.type = 'TetrahedronGeometry';
24264 _this.parameters = {
24269 _this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
24271 _this.mergeVertices();
24276 return TetrahedronGeometry;
24279 var TextBufferGeometry = /*#__PURE__*/function (_ExtrudeBufferGeometr) {
24280 _inheritsLoose(TextBufferGeometry, _ExtrudeBufferGeometr);
24282 function TextBufferGeometry(text, parameters) {
24285 if (parameters === void 0) {
24289 var font = parameters.font;
24291 if (!(font && font.isFont)) {
24292 console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
24293 return new BufferGeometry() || _assertThisInitialized(_this);
24296 var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
24298 parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
24300 if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
24301 if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
24302 if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
24303 _this = _ExtrudeBufferGeometr.call(this, shapes, parameters) || this;
24304 _this.type = 'TextBufferGeometry';
24308 return TextBufferGeometry;
24309 }(ExtrudeBufferGeometry);
24311 var TextGeometry = /*#__PURE__*/function (_Geometry) {
24312 _inheritsLoose(TextGeometry, _Geometry);
24314 function TextGeometry(text, parameters) {
24317 _this = _Geometry.call(this) || this;
24318 _this.type = 'TextGeometry';
24319 _this.parameters = {
24321 parameters: parameters
24324 _this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
24326 _this.mergeVertices();
24331 return TextGeometry;
24334 var TorusBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
24335 _inheritsLoose(TorusBufferGeometry, _BufferGeometry);
24337 function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
24340 if (radius === void 0) {
24344 if (tube === void 0) {
24348 if (radialSegments === void 0) {
24349 radialSegments = 8;
24352 if (tubularSegments === void 0) {
24353 tubularSegments = 6;
24356 if (arc === void 0) {
24360 _this = _BufferGeometry.call(this) || this;
24361 _this.type = 'TorusBufferGeometry';
24362 _this.parameters = {
24365 radialSegments: radialSegments,
24366 tubularSegments: tubularSegments,
24369 radialSegments = Math.floor(radialSegments);
24370 tubularSegments = Math.floor(tubularSegments); // buffers
24375 var uvs = []; // helper variables
24377 var center = new Vector3();
24378 var vertex = new Vector3();
24379 var normal = new Vector3(); // generate vertices, normals and uvs
24381 for (var j = 0; j <= radialSegments; j++) {
24382 for (var i = 0; i <= tubularSegments; i++) {
24383 var u = i / tubularSegments * arc;
24384 var v = j / radialSegments * Math.PI * 2; // vertex
24386 vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
24387 vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
24388 vertex.z = tube * Math.sin(v);
24389 vertices.push(vertex.x, vertex.y, vertex.z); // normal
24391 center.x = radius * Math.cos(u);
24392 center.y = radius * Math.sin(u);
24393 normal.subVectors(vertex, center).normalize();
24394 normals.push(normal.x, normal.y, normal.z); // uv
24396 uvs.push(i / tubularSegments);
24397 uvs.push(j / radialSegments);
24399 } // generate indices
24402 for (var _j = 1; _j <= radialSegments; _j++) {
24403 for (var _i = 1; _i <= tubularSegments; _i++) {
24405 var a = (tubularSegments + 1) * _j + _i - 1;
24406 var b = (tubularSegments + 1) * (_j - 1) + _i - 1;
24407 var c = (tubularSegments + 1) * (_j - 1) + _i;
24408 var d = (tubularSegments + 1) * _j + _i; // faces
24410 indices.push(a, b, d);
24411 indices.push(b, c, d);
24413 } // build geometry
24416 _this.setIndex(indices);
24418 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
24420 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
24422 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
24427 return TorusBufferGeometry;
24430 var TorusGeometry = /*#__PURE__*/function (_Geometry) {
24431 _inheritsLoose(TorusGeometry, _Geometry);
24433 function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
24436 _this = _Geometry.call(this) || this;
24437 _this.type = 'TorusGeometry';
24438 _this.parameters = {
24441 radialSegments: radialSegments,
24442 tubularSegments: tubularSegments,
24446 _this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
24448 _this.mergeVertices();
24453 return TorusGeometry;
24456 var TorusKnotBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
24457 _inheritsLoose(TorusKnotBufferGeometry, _BufferGeometry);
24459 function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
24462 if (radius === void 0) {
24466 if (tube === void 0) {
24470 if (tubularSegments === void 0) {
24471 tubularSegments = 64;
24474 if (radialSegments === void 0) {
24475 radialSegments = 8;
24478 if (p === void 0) {
24482 if (q === void 0) {
24486 _this = _BufferGeometry.call(this) || this;
24487 _this.type = 'TorusKnotBufferGeometry';
24488 _this.parameters = {
24491 tubularSegments: tubularSegments,
24492 radialSegments: radialSegments,
24496 tubularSegments = Math.floor(tubularSegments);
24497 radialSegments = Math.floor(radialSegments); // buffers
24502 var uvs = []; // helper variables
24504 var vertex = new Vector3();
24505 var normal = new Vector3();
24506 var P1 = new Vector3();
24507 var P2 = new Vector3();
24508 var B = new Vector3();
24509 var T = new Vector3();
24510 var N = new Vector3(); // generate vertices, normals and uvs
24512 for (var i = 0; i <= tubularSegments; ++i) {
24513 // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
24514 var 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.
24515 // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
24517 calculatePositionOnCurve(u, p, q, radius, P1);
24518 calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
24520 T.subVectors(P2, P1);
24521 N.addVectors(P2, P1);
24522 B.crossVectors(T, N);
24523 N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
24528 for (var j = 0; j <= radialSegments; ++j) {
24529 // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
24530 // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
24531 var v = j / radialSegments * Math.PI * 2;
24532 var cx = -tube * Math.cos(v);
24533 var cy = tube * Math.sin(v); // now calculate the final vertex position.
24534 // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
24536 vertex.x = P1.x + (cx * N.x + cy * B.x);
24537 vertex.y = P1.y + (cx * N.y + cy * B.y);
24538 vertex.z = P1.z + (cx * N.z + cy * B.z);
24539 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)
24541 normal.subVectors(vertex, P1).normalize();
24542 normals.push(normal.x, normal.y, normal.z); // uv
24544 uvs.push(i / tubularSegments);
24545 uvs.push(j / radialSegments);
24547 } // generate indices
24550 for (var _j = 1; _j <= tubularSegments; _j++) {
24551 for (var _i = 1; _i <= radialSegments; _i++) {
24553 var a = (radialSegments + 1) * (_j - 1) + (_i - 1);
24554 var b = (radialSegments + 1) * _j + (_i - 1);
24555 var c = (radialSegments + 1) * _j + _i;
24556 var d = (radialSegments + 1) * (_j - 1) + _i; // faces
24558 indices.push(a, b, d);
24559 indices.push(b, c, d);
24561 } // build geometry
24564 _this.setIndex(indices);
24566 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
24568 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
24570 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
24573 function calculatePositionOnCurve(u, p, q, radius, position) {
24574 var cu = Math.cos(u);
24575 var su = Math.sin(u);
24576 var quOverP = q / p * u;
24577 var cs = Math.cos(quOverP);
24578 position.x = radius * (2 + cs) * 0.5 * cu;
24579 position.y = radius * (2 + cs) * su * 0.5;
24580 position.z = radius * Math.sin(quOverP) * 0.5;
24586 return TorusKnotBufferGeometry;
24589 var TorusKnotGeometry = /*#__PURE__*/function (_Geometry) {
24590 _inheritsLoose(TorusKnotGeometry, _Geometry);
24592 function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
24595 _this = _Geometry.call(this) || this;
24596 _this.type = 'TorusKnotGeometry';
24597 _this.parameters = {
24600 tubularSegments: tubularSegments,
24601 radialSegments: radialSegments,
24605 if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
24607 _this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
24609 _this.mergeVertices();
24614 return TorusKnotGeometry;
24617 var TubeBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
24618 _inheritsLoose(TubeBufferGeometry, _BufferGeometry);
24620 function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
24623 if (tubularSegments === void 0) {
24624 tubularSegments = 64;
24627 if (radius === void 0) {
24631 if (radialSegments === void 0) {
24632 radialSegments = 8;
24635 if (closed === void 0) {
24639 _this = _BufferGeometry.call(this) || this;
24640 _this.type = 'TubeBufferGeometry';
24641 _this.parameters = {
24643 tubularSegments: tubularSegments,
24645 radialSegments: radialSegments,
24648 var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
24650 _this.tangents = frames.tangents;
24651 _this.normals = frames.normals;
24652 _this.binormals = frames.binormals; // helper variables
24654 var vertex = new Vector3();
24655 var normal = new Vector3();
24656 var uv = new Vector2();
24657 var P = new Vector3(); // buffer
24662 var indices = []; // create buffer data
24664 generateBufferData(); // build geometry
24666 _this.setIndex(indices);
24668 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
24670 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
24672 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
24675 function generateBufferData() {
24676 for (var i = 0; i < tubularSegments; i++) {
24677 generateSegment(i);
24678 } // if the geometry is not closed, generate the last row of vertices and normals
24679 // at the regular position on the given path
24681 // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
24684 generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
24685 // this makes it easy compute correct values for closed geometries
24687 generateUVs(); // finally create faces
24692 function generateSegment(i) {
24693 // we use getPointAt to sample evenly distributed points from the given path
24694 P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
24696 var N = frames.normals[i];
24697 var B = frames.binormals[i]; // generate normals and vertices for the current segment
24699 for (var j = 0; j <= radialSegments; j++) {
24700 var v = j / radialSegments * Math.PI * 2;
24701 var sin = Math.sin(v);
24702 var cos = -Math.cos(v); // normal
24704 normal.x = cos * N.x + sin * B.x;
24705 normal.y = cos * N.y + sin * B.y;
24706 normal.z = cos * N.z + sin * B.z;
24707 normal.normalize();
24708 normals.push(normal.x, normal.y, normal.z); // vertex
24710 vertex.x = P.x + radius * normal.x;
24711 vertex.y = P.y + radius * normal.y;
24712 vertex.z = P.z + radius * normal.z;
24713 vertices.push(vertex.x, vertex.y, vertex.z);
24717 function generateIndices() {
24718 for (var j = 1; j <= tubularSegments; j++) {
24719 for (var i = 1; i <= radialSegments; i++) {
24720 var a = (radialSegments + 1) * (j - 1) + (i - 1);
24721 var b = (radialSegments + 1) * j + (i - 1);
24722 var c = (radialSegments + 1) * j + i;
24723 var d = (radialSegments + 1) * (j - 1) + i; // faces
24725 indices.push(a, b, d);
24726 indices.push(b, c, d);
24731 function generateUVs() {
24732 for (var i = 0; i <= tubularSegments; i++) {
24733 for (var j = 0; j <= radialSegments; j++) {
24734 uv.x = i / tubularSegments;
24735 uv.y = j / radialSegments;
24736 uvs.push(uv.x, uv.y);
24744 var _proto = TubeBufferGeometry.prototype;
24746 _proto.toJSON = function toJSON() {
24747 var data = BufferGeometry.prototype.toJSON.call(this);
24748 data.path = this.parameters.path.toJSON();
24752 return TubeBufferGeometry;
24755 var TubeGeometry = /*#__PURE__*/function (_Geometry) {
24756 _inheritsLoose(TubeGeometry, _Geometry);
24758 function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
24761 _this = _Geometry.call(this) || this;
24762 _this.type = 'TubeGeometry';
24763 _this.parameters = {
24765 tubularSegments: tubularSegments,
24767 radialSegments: radialSegments,
24770 if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
24771 var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
24773 _this.tangents = bufferGeometry.tangents;
24774 _this.normals = bufferGeometry.normals;
24775 _this.binormals = bufferGeometry.binormals; // create geometry
24777 _this.fromBufferGeometry(bufferGeometry);
24779 _this.mergeVertices();
24784 return TubeGeometry;
24787 var WireframeGeometry = /*#__PURE__*/function (_BufferGeometry) {
24788 _inheritsLoose(WireframeGeometry, _BufferGeometry);
24790 function WireframeGeometry(geometry) {
24793 _this = _BufferGeometry.call(this) || this;
24794 _this.type = 'WireframeGeometry'; // buffer
24796 var vertices = []; // helper variables
24800 var keys = ['a', 'b', 'c']; // different logic for Geometry and BufferGeometry
24802 if (geometry && geometry.isGeometry) {
24803 // create a data structure that contains all edges without duplicates
24804 var faces = geometry.faces;
24806 for (var i = 0, l = faces.length; i < l; i++) {
24807 var face = faces[i];
24809 for (var j = 0; j < 3; j++) {
24810 var edge1 = face[keys[j]];
24811 var edge2 = face[keys[(j + 1) % 3]];
24812 edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
24814 edge[1] = Math.max(edge1, edge2);
24815 var key = edge[0] + ',' + edge[1];
24817 if (edges[key] === undefined) {
24824 } // generate vertices
24827 for (var _key in edges) {
24828 var e = edges[_key];
24829 var vertex = geometry.vertices[e.index1];
24830 vertices.push(vertex.x, vertex.y, vertex.z);
24831 vertex = geometry.vertices[e.index2];
24832 vertices.push(vertex.x, vertex.y, vertex.z);
24834 } else if (geometry && geometry.isBufferGeometry) {
24835 var _vertex = new Vector3();
24837 if (geometry.index !== null) {
24838 // indexed BufferGeometry
24839 var position = geometry.attributes.position;
24840 var indices = geometry.index;
24841 var groups = geometry.groups;
24843 if (groups.length === 0) {
24846 count: indices.count,
24849 } // create a data structure that contains all eges without duplicates
24852 for (var o = 0, ol = groups.length; o < ol; ++o) {
24853 var group = groups[o];
24854 var start = group.start;
24855 var count = group.count;
24857 for (var _i = start, _l = start + count; _i < _l; _i += 3) {
24858 for (var _j = 0; _j < 3; _j++) {
24859 var _edge = indices.getX(_i + _j);
24861 var _edge2 = indices.getX(_i + (_j + 1) % 3);
24863 edge[0] = Math.min(_edge, _edge2); // sorting prevents duplicates
24865 edge[1] = Math.max(_edge, _edge2);
24867 var _key2 = edge[0] + ',' + edge[1];
24869 if (edges[_key2] === undefined) {
24877 } // generate vertices
24880 for (var _key3 in edges) {
24881 var _e = edges[_key3];
24883 _vertex.fromBufferAttribute(position, _e.index1);
24885 vertices.push(_vertex.x, _vertex.y, _vertex.z);
24887 _vertex.fromBufferAttribute(position, _e.index2);
24889 vertices.push(_vertex.x, _vertex.y, _vertex.z);
24892 // non-indexed BufferGeometry
24893 var _position = geometry.attributes.position;
24895 for (var _i2 = 0, _l2 = _position.count / 3; _i2 < _l2; _i2++) {
24896 for (var _j2 = 0; _j2 < 3; _j2++) {
24897 // three edges per triangle, an edge is represented as (index1, index2)
24898 // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
24899 var index1 = 3 * _i2 + _j2;
24901 _vertex.fromBufferAttribute(_position, index1);
24903 vertices.push(_vertex.x, _vertex.y, _vertex.z);
24904 var index2 = 3 * _i2 + (_j2 + 1) % 3;
24906 _vertex.fromBufferAttribute(_position, index2);
24908 vertices.push(_vertex.x, _vertex.y, _vertex.z);
24912 } // build geometry
24915 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
24920 return WireframeGeometry;
24923 var Geometries = /*#__PURE__*/Object.freeze({
24925 BoxGeometry: BoxGeometry,
24926 BoxBufferGeometry: BoxBufferGeometry,
24927 CircleGeometry: CircleGeometry,
24928 CircleBufferGeometry: CircleBufferGeometry,
24929 ConeGeometry: ConeGeometry,
24930 ConeBufferGeometry: ConeBufferGeometry,
24931 CylinderGeometry: CylinderGeometry,
24932 CylinderBufferGeometry: CylinderBufferGeometry,
24933 DodecahedronGeometry: DodecahedronGeometry,
24934 DodecahedronBufferGeometry: DodecahedronBufferGeometry,
24935 EdgesGeometry: EdgesGeometry,
24936 ExtrudeGeometry: ExtrudeGeometry,
24937 ExtrudeBufferGeometry: ExtrudeBufferGeometry,
24938 IcosahedronGeometry: IcosahedronGeometry,
24939 IcosahedronBufferGeometry: IcosahedronBufferGeometry,
24940 LatheGeometry: LatheGeometry,
24941 LatheBufferGeometry: LatheBufferGeometry,
24942 OctahedronGeometry: OctahedronGeometry,
24943 OctahedronBufferGeometry: OctahedronBufferGeometry,
24944 ParametricGeometry: ParametricGeometry,
24945 ParametricBufferGeometry: ParametricBufferGeometry,
24946 PlaneGeometry: PlaneGeometry,
24947 PlaneBufferGeometry: PlaneBufferGeometry,
24948 PolyhedronGeometry: PolyhedronGeometry,
24949 PolyhedronBufferGeometry: PolyhedronBufferGeometry,
24950 RingGeometry: RingGeometry,
24951 RingBufferGeometry: RingBufferGeometry,
24952 ShapeGeometry: ShapeGeometry,
24953 ShapeBufferGeometry: ShapeBufferGeometry,
24954 SphereGeometry: SphereGeometry,
24955 SphereBufferGeometry: SphereBufferGeometry,
24956 TetrahedronGeometry: TetrahedronGeometry,
24957 TetrahedronBufferGeometry: TetrahedronBufferGeometry,
24958 TextGeometry: TextGeometry,
24959 TextBufferGeometry: TextBufferGeometry,
24960 TorusGeometry: TorusGeometry,
24961 TorusBufferGeometry: TorusBufferGeometry,
24962 TorusKnotGeometry: TorusKnotGeometry,
24963 TorusKnotBufferGeometry: TorusKnotBufferGeometry,
24964 TubeGeometry: TubeGeometry,
24965 TubeBufferGeometry: TubeBufferGeometry,
24966 WireframeGeometry: WireframeGeometry
24971 * color: <THREE.Color>
24975 function ShadowMaterial(parameters) {
24976 Material.call(this);
24977 this.type = 'ShadowMaterial';
24978 this.color = new Color(0x000000);
24979 this.transparent = true;
24980 this.setValues(parameters);
24983 ShadowMaterial.prototype = Object.create(Material.prototype);
24984 ShadowMaterial.prototype.constructor = ShadowMaterial;
24985 ShadowMaterial.prototype.isShadowMaterial = true;
24987 ShadowMaterial.prototype.copy = function (source) {
24988 Material.prototype.copy.call(this, source);
24989 this.color.copy(source.color);
24993 function RawShaderMaterial(parameters) {
24994 ShaderMaterial.call(this, parameters);
24995 this.type = 'RawShaderMaterial';
24998 RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
24999 RawShaderMaterial.prototype.constructor = RawShaderMaterial;
25000 RawShaderMaterial.prototype.isRawShaderMaterial = true;
25005 * roughness: <float>,
25006 * metalness: <float>,
25007 * opacity: <float>,
25009 * map: new THREE.Texture( <Image> ),
25011 * lightMap: new THREE.Texture( <Image> ),
25012 * lightMapIntensity: <float>
25014 * aoMap: new THREE.Texture( <Image> ),
25015 * aoMapIntensity: <float>
25018 * emissiveIntensity: <float>
25019 * emissiveMap: new THREE.Texture( <Image> ),
25021 * bumpMap: new THREE.Texture( <Image> ),
25022 * bumpScale: <float>,
25024 * normalMap: new THREE.Texture( <Image> ),
25025 * normalMapType: THREE.TangentSpaceNormalMap,
25026 * normalScale: <Vector2>,
25028 * displacementMap: new THREE.Texture( <Image> ),
25029 * displacementScale: <float>,
25030 * displacementBias: <float>,
25032 * roughnessMap: new THREE.Texture( <Image> ),
25034 * metalnessMap: new THREE.Texture( <Image> ),
25036 * alphaMap: new THREE.Texture( <Image> ),
25038 * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
25039 * envMapIntensity: <float>
25041 * refractionRatio: <float>,
25043 * wireframe: <boolean>,
25044 * wireframeLinewidth: <float>,
25046 * skinning: <bool>,
25047 * morphTargets: <bool>,
25048 * morphNormals: <bool>
25052 function MeshStandardMaterial(parameters) {
25053 Material.call(this);
25057 this.type = 'MeshStandardMaterial';
25058 this.color = new Color(0xffffff); // diffuse
25060 this.roughness = 1.0;
25061 this.metalness = 0.0;
25063 this.lightMap = null;
25064 this.lightMapIntensity = 1.0;
25066 this.aoMapIntensity = 1.0;
25067 this.emissive = new Color(0x000000);
25068 this.emissiveIntensity = 1.0;
25069 this.emissiveMap = null;
25070 this.bumpMap = null;
25071 this.bumpScale = 1;
25072 this.normalMap = null;
25073 this.normalMapType = TangentSpaceNormalMap;
25074 this.normalScale = new Vector2(1, 1);
25075 this.displacementMap = null;
25076 this.displacementScale = 1;
25077 this.displacementBias = 0;
25078 this.roughnessMap = null;
25079 this.metalnessMap = null;
25080 this.alphaMap = null;
25081 this.envMap = null;
25082 this.envMapIntensity = 1.0;
25083 this.refractionRatio = 0.98;
25084 this.wireframe = false;
25085 this.wireframeLinewidth = 1;
25086 this.wireframeLinecap = 'round';
25087 this.wireframeLinejoin = 'round';
25088 this.skinning = false;
25089 this.morphTargets = false;
25090 this.morphNormals = false;
25091 this.vertexTangents = false;
25092 this.setValues(parameters);
25095 MeshStandardMaterial.prototype = Object.create(Material.prototype);
25096 MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
25097 MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
25099 MeshStandardMaterial.prototype.copy = function (source) {
25100 Material.prototype.copy.call(this, source);
25104 this.color.copy(source.color);
25105 this.roughness = source.roughness;
25106 this.metalness = source.metalness;
25107 this.map = source.map;
25108 this.lightMap = source.lightMap;
25109 this.lightMapIntensity = source.lightMapIntensity;
25110 this.aoMap = source.aoMap;
25111 this.aoMapIntensity = source.aoMapIntensity;
25112 this.emissive.copy(source.emissive);
25113 this.emissiveMap = source.emissiveMap;
25114 this.emissiveIntensity = source.emissiveIntensity;
25115 this.bumpMap = source.bumpMap;
25116 this.bumpScale = source.bumpScale;
25117 this.normalMap = source.normalMap;
25118 this.normalMapType = source.normalMapType;
25119 this.normalScale.copy(source.normalScale);
25120 this.displacementMap = source.displacementMap;
25121 this.displacementScale = source.displacementScale;
25122 this.displacementBias = source.displacementBias;
25123 this.roughnessMap = source.roughnessMap;
25124 this.metalnessMap = source.metalnessMap;
25125 this.alphaMap = source.alphaMap;
25126 this.envMap = source.envMap;
25127 this.envMapIntensity = source.envMapIntensity;
25128 this.refractionRatio = source.refractionRatio;
25129 this.wireframe = source.wireframe;
25130 this.wireframeLinewidth = source.wireframeLinewidth;
25131 this.wireframeLinecap = source.wireframeLinecap;
25132 this.wireframeLinejoin = source.wireframeLinejoin;
25133 this.skinning = source.skinning;
25134 this.morphTargets = source.morphTargets;
25135 this.morphNormals = source.morphNormals;
25136 this.vertexTangents = source.vertexTangents;
25142 * clearcoat: <float>,
25143 * clearcoatMap: new THREE.Texture( <Image> ),
25144 * clearcoatRoughness: <float>,
25145 * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
25146 * clearcoatNormalScale: <Vector2>,
25147 * clearcoatNormalMap: new THREE.Texture( <Image> ),
25149 * reflectivity: <float>,
25154 * transmission: <float>,
25155 * transmissionMap: new THREE.Texture( <Image> )
25159 function MeshPhysicalMaterial(parameters) {
25160 MeshStandardMaterial.call(this);
25165 this.type = 'MeshPhysicalMaterial';
25166 this.clearcoat = 0.0;
25167 this.clearcoatMap = null;
25168 this.clearcoatRoughness = 0.0;
25169 this.clearcoatRoughnessMap = null;
25170 this.clearcoatNormalScale = new Vector2(1, 1);
25171 this.clearcoatNormalMap = null;
25172 this.reflectivity = 0.5; // maps to F0 = 0.04
25174 Object.defineProperty(this, 'ior', {
25175 get: function get() {
25176 return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
25178 set: function set(ior) {
25179 this.reflectivity = MathUtils.clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
25182 this.sheen = null; // null will disable sheen bsdf
25184 this.transmission = 0.0;
25185 this.transmissionMap = null;
25186 this.setValues(parameters);
25189 MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
25190 MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
25191 MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
25193 MeshPhysicalMaterial.prototype.copy = function (source) {
25194 MeshStandardMaterial.prototype.copy.call(this, source);
25199 this.clearcoat = source.clearcoat;
25200 this.clearcoatMap = source.clearcoatMap;
25201 this.clearcoatRoughness = source.clearcoatRoughness;
25202 this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
25203 this.clearcoatNormalMap = source.clearcoatNormalMap;
25204 this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
25205 this.reflectivity = source.reflectivity;
25207 if (source.sheen) {
25208 this.sheen = (this.sheen || new Color()).copy(source.sheen);
25213 this.transmission = source.transmission;
25214 this.transmissionMap = source.transmissionMap;
25222 * shininess: <float>,
25223 * opacity: <float>,
25225 * map: new THREE.Texture( <Image> ),
25227 * lightMap: new THREE.Texture( <Image> ),
25228 * lightMapIntensity: <float>
25230 * aoMap: new THREE.Texture( <Image> ),
25231 * aoMapIntensity: <float>
25234 * emissiveIntensity: <float>
25235 * emissiveMap: new THREE.Texture( <Image> ),
25237 * bumpMap: new THREE.Texture( <Image> ),
25238 * bumpScale: <float>,
25240 * normalMap: new THREE.Texture( <Image> ),
25241 * normalMapType: THREE.TangentSpaceNormalMap,
25242 * normalScale: <Vector2>,
25244 * displacementMap: new THREE.Texture( <Image> ),
25245 * displacementScale: <float>,
25246 * displacementBias: <float>,
25248 * specularMap: new THREE.Texture( <Image> ),
25250 * alphaMap: new THREE.Texture( <Image> ),
25252 * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
25253 * combine: THREE.MultiplyOperation,
25254 * reflectivity: <float>,
25255 * refractionRatio: <float>,
25257 * wireframe: <boolean>,
25258 * wireframeLinewidth: <float>,
25260 * skinning: <bool>,
25261 * morphTargets: <bool>,
25262 * morphNormals: <bool>
25266 function MeshPhongMaterial(parameters) {
25267 Material.call(this);
25268 this.type = 'MeshPhongMaterial';
25269 this.color = new Color(0xffffff); // diffuse
25271 this.specular = new Color(0x111111);
25272 this.shininess = 30;
25274 this.lightMap = null;
25275 this.lightMapIntensity = 1.0;
25277 this.aoMapIntensity = 1.0;
25278 this.emissive = new Color(0x000000);
25279 this.emissiveIntensity = 1.0;
25280 this.emissiveMap = null;
25281 this.bumpMap = null;
25282 this.bumpScale = 1;
25283 this.normalMap = null;
25284 this.normalMapType = TangentSpaceNormalMap;
25285 this.normalScale = new Vector2(1, 1);
25286 this.displacementMap = null;
25287 this.displacementScale = 1;
25288 this.displacementBias = 0;
25289 this.specularMap = null;
25290 this.alphaMap = null;
25291 this.envMap = null;
25292 this.combine = MultiplyOperation;
25293 this.reflectivity = 1;
25294 this.refractionRatio = 0.98;
25295 this.wireframe = false;
25296 this.wireframeLinewidth = 1;
25297 this.wireframeLinecap = 'round';
25298 this.wireframeLinejoin = 'round';
25299 this.skinning = false;
25300 this.morphTargets = false;
25301 this.morphNormals = false;
25302 this.setValues(parameters);
25305 MeshPhongMaterial.prototype = Object.create(Material.prototype);
25306 MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
25307 MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
25309 MeshPhongMaterial.prototype.copy = function (source) {
25310 Material.prototype.copy.call(this, source);
25311 this.color.copy(source.color);
25312 this.specular.copy(source.specular);
25313 this.shininess = source.shininess;
25314 this.map = source.map;
25315 this.lightMap = source.lightMap;
25316 this.lightMapIntensity = source.lightMapIntensity;
25317 this.aoMap = source.aoMap;
25318 this.aoMapIntensity = source.aoMapIntensity;
25319 this.emissive.copy(source.emissive);
25320 this.emissiveMap = source.emissiveMap;
25321 this.emissiveIntensity = source.emissiveIntensity;
25322 this.bumpMap = source.bumpMap;
25323 this.bumpScale = source.bumpScale;
25324 this.normalMap = source.normalMap;
25325 this.normalMapType = source.normalMapType;
25326 this.normalScale.copy(source.normalScale);
25327 this.displacementMap = source.displacementMap;
25328 this.displacementScale = source.displacementScale;
25329 this.displacementBias = source.displacementBias;
25330 this.specularMap = source.specularMap;
25331 this.alphaMap = source.alphaMap;
25332 this.envMap = source.envMap;
25333 this.combine = source.combine;
25334 this.reflectivity = source.reflectivity;
25335 this.refractionRatio = source.refractionRatio;
25336 this.wireframe = source.wireframe;
25337 this.wireframeLinewidth = source.wireframeLinewidth;
25338 this.wireframeLinecap = source.wireframeLinecap;
25339 this.wireframeLinejoin = source.wireframeLinejoin;
25340 this.skinning = source.skinning;
25341 this.morphTargets = source.morphTargets;
25342 this.morphNormals = source.morphNormals;
25350 * map: new THREE.Texture( <Image> ),
25351 * gradientMap: new THREE.Texture( <Image> ),
25353 * lightMap: new THREE.Texture( <Image> ),
25354 * lightMapIntensity: <float>
25356 * aoMap: new THREE.Texture( <Image> ),
25357 * aoMapIntensity: <float>
25360 * emissiveIntensity: <float>
25361 * emissiveMap: new THREE.Texture( <Image> ),
25363 * bumpMap: new THREE.Texture( <Image> ),
25364 * bumpScale: <float>,
25366 * normalMap: new THREE.Texture( <Image> ),
25367 * normalMapType: THREE.TangentSpaceNormalMap,
25368 * normalScale: <Vector2>,
25370 * displacementMap: new THREE.Texture( <Image> ),
25371 * displacementScale: <float>,
25372 * displacementBias: <float>,
25374 * alphaMap: new THREE.Texture( <Image> ),
25376 * wireframe: <boolean>,
25377 * wireframeLinewidth: <float>,
25379 * skinning: <bool>,
25380 * morphTargets: <bool>,
25381 * morphNormals: <bool>
25385 function MeshToonMaterial(parameters) {
25386 Material.call(this);
25390 this.type = 'MeshToonMaterial';
25391 this.color = new Color(0xffffff);
25393 this.gradientMap = null;
25394 this.lightMap = null;
25395 this.lightMapIntensity = 1.0;
25397 this.aoMapIntensity = 1.0;
25398 this.emissive = new Color(0x000000);
25399 this.emissiveIntensity = 1.0;
25400 this.emissiveMap = null;
25401 this.bumpMap = null;
25402 this.bumpScale = 1;
25403 this.normalMap = null;
25404 this.normalMapType = TangentSpaceNormalMap;
25405 this.normalScale = new Vector2(1, 1);
25406 this.displacementMap = null;
25407 this.displacementScale = 1;
25408 this.displacementBias = 0;
25409 this.alphaMap = null;
25410 this.wireframe = false;
25411 this.wireframeLinewidth = 1;
25412 this.wireframeLinecap = 'round';
25413 this.wireframeLinejoin = 'round';
25414 this.skinning = false;
25415 this.morphTargets = false;
25416 this.morphNormals = false;
25417 this.setValues(parameters);
25420 MeshToonMaterial.prototype = Object.create(Material.prototype);
25421 MeshToonMaterial.prototype.constructor = MeshToonMaterial;
25422 MeshToonMaterial.prototype.isMeshToonMaterial = true;
25424 MeshToonMaterial.prototype.copy = function (source) {
25425 Material.prototype.copy.call(this, source);
25426 this.color.copy(source.color);
25427 this.map = source.map;
25428 this.gradientMap = source.gradientMap;
25429 this.lightMap = source.lightMap;
25430 this.lightMapIntensity = source.lightMapIntensity;
25431 this.aoMap = source.aoMap;
25432 this.aoMapIntensity = source.aoMapIntensity;
25433 this.emissive.copy(source.emissive);
25434 this.emissiveMap = source.emissiveMap;
25435 this.emissiveIntensity = source.emissiveIntensity;
25436 this.bumpMap = source.bumpMap;
25437 this.bumpScale = source.bumpScale;
25438 this.normalMap = source.normalMap;
25439 this.normalMapType = source.normalMapType;
25440 this.normalScale.copy(source.normalScale);
25441 this.displacementMap = source.displacementMap;
25442 this.displacementScale = source.displacementScale;
25443 this.displacementBias = source.displacementBias;
25444 this.alphaMap = source.alphaMap;
25445 this.wireframe = source.wireframe;
25446 this.wireframeLinewidth = source.wireframeLinewidth;
25447 this.wireframeLinecap = source.wireframeLinecap;
25448 this.wireframeLinejoin = source.wireframeLinejoin;
25449 this.skinning = source.skinning;
25450 this.morphTargets = source.morphTargets;
25451 this.morphNormals = source.morphNormals;
25457 * opacity: <float>,
25459 * bumpMap: new THREE.Texture( <Image> ),
25460 * bumpScale: <float>,
25462 * normalMap: new THREE.Texture( <Image> ),
25463 * normalMapType: THREE.TangentSpaceNormalMap,
25464 * normalScale: <Vector2>,
25466 * displacementMap: new THREE.Texture( <Image> ),
25467 * displacementScale: <float>,
25468 * displacementBias: <float>,
25470 * wireframe: <boolean>,
25471 * wireframeLinewidth: <float>
25473 * skinning: <bool>,
25474 * morphTargets: <bool>,
25475 * morphNormals: <bool>
25479 function MeshNormalMaterial(parameters) {
25480 Material.call(this);
25481 this.type = 'MeshNormalMaterial';
25482 this.bumpMap = null;
25483 this.bumpScale = 1;
25484 this.normalMap = null;
25485 this.normalMapType = TangentSpaceNormalMap;
25486 this.normalScale = new Vector2(1, 1);
25487 this.displacementMap = null;
25488 this.displacementScale = 1;
25489 this.displacementBias = 0;
25490 this.wireframe = false;
25491 this.wireframeLinewidth = 1;
25493 this.skinning = false;
25494 this.morphTargets = false;
25495 this.morphNormals = false;
25496 this.setValues(parameters);
25499 MeshNormalMaterial.prototype = Object.create(Material.prototype);
25500 MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
25501 MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
25503 MeshNormalMaterial.prototype.copy = function (source) {
25504 Material.prototype.copy.call(this, source);
25505 this.bumpMap = source.bumpMap;
25506 this.bumpScale = source.bumpScale;
25507 this.normalMap = source.normalMap;
25508 this.normalMapType = source.normalMapType;
25509 this.normalScale.copy(source.normalScale);
25510 this.displacementMap = source.displacementMap;
25511 this.displacementScale = source.displacementScale;
25512 this.displacementBias = source.displacementBias;
25513 this.wireframe = source.wireframe;
25514 this.wireframeLinewidth = source.wireframeLinewidth;
25515 this.skinning = source.skinning;
25516 this.morphTargets = source.morphTargets;
25517 this.morphNormals = source.morphNormals;
25524 * opacity: <float>,
25526 * map: new THREE.Texture( <Image> ),
25528 * lightMap: new THREE.Texture( <Image> ),
25529 * lightMapIntensity: <float>
25531 * aoMap: new THREE.Texture( <Image> ),
25532 * aoMapIntensity: <float>
25535 * emissiveIntensity: <float>
25536 * emissiveMap: new THREE.Texture( <Image> ),
25538 * specularMap: new THREE.Texture( <Image> ),
25540 * alphaMap: new THREE.Texture( <Image> ),
25542 * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
25543 * combine: THREE.Multiply,
25544 * reflectivity: <float>,
25545 * refractionRatio: <float>,
25547 * wireframe: <boolean>,
25548 * wireframeLinewidth: <float>,
25550 * skinning: <bool>,
25551 * morphTargets: <bool>,
25552 * morphNormals: <bool>
25556 function MeshLambertMaterial(parameters) {
25557 Material.call(this);
25558 this.type = 'MeshLambertMaterial';
25559 this.color = new Color(0xffffff); // diffuse
25562 this.lightMap = null;
25563 this.lightMapIntensity = 1.0;
25565 this.aoMapIntensity = 1.0;
25566 this.emissive = new Color(0x000000);
25567 this.emissiveIntensity = 1.0;
25568 this.emissiveMap = null;
25569 this.specularMap = null;
25570 this.alphaMap = null;
25571 this.envMap = null;
25572 this.combine = MultiplyOperation;
25573 this.reflectivity = 1;
25574 this.refractionRatio = 0.98;
25575 this.wireframe = false;
25576 this.wireframeLinewidth = 1;
25577 this.wireframeLinecap = 'round';
25578 this.wireframeLinejoin = 'round';
25579 this.skinning = false;
25580 this.morphTargets = false;
25581 this.morphNormals = false;
25582 this.setValues(parameters);
25585 MeshLambertMaterial.prototype = Object.create(Material.prototype);
25586 MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
25587 MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
25589 MeshLambertMaterial.prototype.copy = function (source) {
25590 Material.prototype.copy.call(this, source);
25591 this.color.copy(source.color);
25592 this.map = source.map;
25593 this.lightMap = source.lightMap;
25594 this.lightMapIntensity = source.lightMapIntensity;
25595 this.aoMap = source.aoMap;
25596 this.aoMapIntensity = source.aoMapIntensity;
25597 this.emissive.copy(source.emissive);
25598 this.emissiveMap = source.emissiveMap;
25599 this.emissiveIntensity = source.emissiveIntensity;
25600 this.specularMap = source.specularMap;
25601 this.alphaMap = source.alphaMap;
25602 this.envMap = source.envMap;
25603 this.combine = source.combine;
25604 this.reflectivity = source.reflectivity;
25605 this.refractionRatio = source.refractionRatio;
25606 this.wireframe = source.wireframe;
25607 this.wireframeLinewidth = source.wireframeLinewidth;
25608 this.wireframeLinecap = source.wireframeLinecap;
25609 this.wireframeLinejoin = source.wireframeLinejoin;
25610 this.skinning = source.skinning;
25611 this.morphTargets = source.morphTargets;
25612 this.morphNormals = source.morphNormals;
25619 * opacity: <float>,
25621 * matcap: new THREE.Texture( <Image> ),
25623 * map: new THREE.Texture( <Image> ),
25625 * bumpMap: new THREE.Texture( <Image> ),
25626 * bumpScale: <float>,
25628 * normalMap: new THREE.Texture( <Image> ),
25629 * normalMapType: THREE.TangentSpaceNormalMap,
25630 * normalScale: <Vector2>,
25632 * displacementMap: new THREE.Texture( <Image> ),
25633 * displacementScale: <float>,
25634 * displacementBias: <float>,
25636 * alphaMap: new THREE.Texture( <Image> ),
25638 * skinning: <bool>,
25639 * morphTargets: <bool>,
25640 * morphNormals: <bool>
25644 function MeshMatcapMaterial(parameters) {
25645 Material.call(this);
25649 this.type = 'MeshMatcapMaterial';
25650 this.color = new Color(0xffffff); // diffuse
25652 this.matcap = null;
25654 this.bumpMap = null;
25655 this.bumpScale = 1;
25656 this.normalMap = null;
25657 this.normalMapType = TangentSpaceNormalMap;
25658 this.normalScale = new Vector2(1, 1);
25659 this.displacementMap = null;
25660 this.displacementScale = 1;
25661 this.displacementBias = 0;
25662 this.alphaMap = null;
25663 this.skinning = false;
25664 this.morphTargets = false;
25665 this.morphNormals = false;
25666 this.setValues(parameters);
25669 MeshMatcapMaterial.prototype = Object.create(Material.prototype);
25670 MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
25671 MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
25673 MeshMatcapMaterial.prototype.copy = function (source) {
25674 Material.prototype.copy.call(this, source);
25678 this.color.copy(source.color);
25679 this.matcap = source.matcap;
25680 this.map = source.map;
25681 this.bumpMap = source.bumpMap;
25682 this.bumpScale = source.bumpScale;
25683 this.normalMap = source.normalMap;
25684 this.normalMapType = source.normalMapType;
25685 this.normalScale.copy(source.normalScale);
25686 this.displacementMap = source.displacementMap;
25687 this.displacementScale = source.displacementScale;
25688 this.displacementBias = source.displacementBias;
25689 this.alphaMap = source.alphaMap;
25690 this.skinning = source.skinning;
25691 this.morphTargets = source.morphTargets;
25692 this.morphNormals = source.morphNormals;
25699 * opacity: <float>,
25701 * linewidth: <float>,
25704 * dashSize: <float>,
25709 function LineDashedMaterial(parameters) {
25710 LineBasicMaterial.call(this);
25711 this.type = 'LineDashedMaterial';
25715 this.setValues(parameters);
25718 LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
25719 LineDashedMaterial.prototype.constructor = LineDashedMaterial;
25720 LineDashedMaterial.prototype.isLineDashedMaterial = true;
25722 LineDashedMaterial.prototype.copy = function (source) {
25723 LineBasicMaterial.prototype.copy.call(this, source);
25724 this.scale = source.scale;
25725 this.dashSize = source.dashSize;
25726 this.gapSize = source.gapSize;
25730 var Materials = /*#__PURE__*/Object.freeze({
25732 ShadowMaterial: ShadowMaterial,
25733 SpriteMaterial: SpriteMaterial,
25734 RawShaderMaterial: RawShaderMaterial,
25735 ShaderMaterial: ShaderMaterial,
25736 PointsMaterial: PointsMaterial,
25737 MeshPhysicalMaterial: MeshPhysicalMaterial,
25738 MeshStandardMaterial: MeshStandardMaterial,
25739 MeshPhongMaterial: MeshPhongMaterial,
25740 MeshToonMaterial: MeshToonMaterial,
25741 MeshNormalMaterial: MeshNormalMaterial,
25742 MeshLambertMaterial: MeshLambertMaterial,
25743 MeshDepthMaterial: MeshDepthMaterial,
25744 MeshDistanceMaterial: MeshDistanceMaterial,
25745 MeshBasicMaterial: MeshBasicMaterial,
25746 MeshMatcapMaterial: MeshMatcapMaterial,
25747 LineDashedMaterial: LineDashedMaterial,
25748 LineBasicMaterial: LineBasicMaterial,
25752 var AnimationUtils = {
25753 // same as Array.prototype.slice, but also works on typed arrays
25754 arraySlice: function arraySlice(array, from, to) {
25755 if (AnimationUtils.isTypedArray(array)) {
25756 // in ios9 array.subarray(from, undefined) will return empty array
25757 // but array.subarray(from) or array.subarray(from, len) is correct
25758 return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
25761 return array.slice(from, to);
25763 // converts an array to a specific type
25764 convertArray: function convertArray(array, type, forceClone) {
25765 if (!array || // let 'undefined' and 'null' pass
25766 !forceClone && array.constructor === type) return array;
25768 if (typeof type.BYTES_PER_ELEMENT === 'number') {
25769 return new type(array); // create typed array
25772 return Array.prototype.slice.call(array); // create Array
25774 isTypedArray: function isTypedArray(object) {
25775 return ArrayBuffer.isView(object) && !(object instanceof DataView);
25777 // returns an array by which times and values can be sorted
25778 getKeyframeOrder: function getKeyframeOrder(times) {
25779 function compareTime(i, j) {
25780 return times[i] - times[j];
25783 var n = times.length;
25784 var result = new Array(n);
25786 for (var i = 0; i !== n; ++i) {
25790 result.sort(compareTime);
25793 // uses the array previously returned by 'getKeyframeOrder' to sort data
25794 sortedArray: function sortedArray(values, stride, order) {
25795 var nValues = values.length;
25796 var result = new values.constructor(nValues);
25798 for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
25799 var srcOffset = order[i] * stride;
25801 for (var j = 0; j !== stride; ++j) {
25802 result[dstOffset++] = values[srcOffset + j];
25808 // function for parsing AOS keyframe formats
25809 flattenJSON: function flattenJSON(jsonKeys, times, values, valuePropertyName) {
25813 while (key !== undefined && key[valuePropertyName] === undefined) {
25814 key = jsonKeys[i++];
25817 if (key === undefined) return; // no data
25819 var value = key[valuePropertyName];
25820 if (value === undefined) return; // no data
25822 if (Array.isArray(value)) {
25824 value = key[valuePropertyName];
25826 if (value !== undefined) {
25827 times.push(key.time);
25828 values.push.apply(values, value); // push all elements
25831 key = jsonKeys[i++];
25832 } while (key !== undefined);
25833 } else if (value.toArray !== undefined) {
25834 // ...assume THREE.Math-ish
25836 value = key[valuePropertyName];
25838 if (value !== undefined) {
25839 times.push(key.time);
25840 value.toArray(values, values.length);
25843 key = jsonKeys[i++];
25844 } while (key !== undefined);
25846 // otherwise push as-is
25848 value = key[valuePropertyName];
25850 if (value !== undefined) {
25851 times.push(key.time);
25852 values.push(value);
25855 key = jsonKeys[i++];
25856 } while (key !== undefined);
25859 subclip: function subclip(sourceClip, name, startFrame, endFrame, fps) {
25860 if (fps === void 0) {
25864 var clip = sourceClip.clone();
25868 for (var i = 0; i < clip.tracks.length; ++i) {
25869 var track = clip.tracks[i];
25870 var valueSize = track.getValueSize();
25874 for (var j = 0; j < track.times.length; ++j) {
25875 var frame = track.times[j] * fps;
25876 if (frame < startFrame || frame >= endFrame) continue;
25877 times.push(track.times[j]);
25879 for (var k = 0; k < valueSize; ++k) {
25880 values.push(track.values[j * valueSize + k]);
25884 if (times.length === 0) continue;
25885 track.times = AnimationUtils.convertArray(times, track.times.constructor);
25886 track.values = AnimationUtils.convertArray(values, track.values.constructor);
25887 tracks.push(track);
25890 clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
25892 var minStartTime = Infinity;
25894 for (var _i = 0; _i < clip.tracks.length; ++_i) {
25895 if (minStartTime > clip.tracks[_i].times[0]) {
25896 minStartTime = clip.tracks[_i].times[0];
25898 } // shift all tracks such that clip begins at t=0
25901 for (var _i2 = 0; _i2 < clip.tracks.length; ++_i2) {
25902 clip.tracks[_i2].shift(-1 * minStartTime);
25905 clip.resetDuration();
25908 makeClipAdditive: function makeClipAdditive(targetClip, referenceFrame, referenceClip, fps) {
25909 if (referenceFrame === void 0) {
25910 referenceFrame = 0;
25913 if (referenceClip === void 0) {
25914 referenceClip = targetClip;
25917 if (fps === void 0) {
25921 if (fps <= 0) fps = 30;
25922 var numTracks = referenceClip.tracks.length;
25923 var referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
25925 var _loop = function _loop(i) {
25926 var referenceTrack = referenceClip.tracks[i];
25927 var referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
25929 if (referenceTrackType === 'bool' || referenceTrackType === 'string') return "continue"; // Find the track in the target clip whose name and type matches the reference track
25931 var targetTrack = targetClip.tracks.find(function (track) {
25932 return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
25934 if (targetTrack === undefined) return "continue";
25935 var referenceOffset = 0;
25936 var referenceValueSize = referenceTrack.getValueSize();
25938 if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
25939 referenceOffset = referenceValueSize / 3;
25942 var targetOffset = 0;
25943 var targetValueSize = targetTrack.getValueSize();
25945 if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
25946 targetOffset = targetValueSize / 3;
25949 var lastIndex = referenceTrack.times.length - 1;
25950 var referenceValue = void 0; // Find the value to subtract out of the track
25952 if (referenceTime <= referenceTrack.times[0]) {
25953 // Reference frame is earlier than the first keyframe, so just use the first keyframe
25954 var startIndex = referenceOffset;
25955 var endIndex = referenceValueSize - referenceOffset;
25956 referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
25957 } else if (referenceTime >= referenceTrack.times[lastIndex]) {
25958 // Reference frame is after the last keyframe, so just use the last keyframe
25959 var _startIndex = lastIndex * referenceValueSize + referenceOffset;
25961 var _endIndex = _startIndex + referenceValueSize - referenceOffset;
25963 referenceValue = AnimationUtils.arraySlice(referenceTrack.values, _startIndex, _endIndex);
25965 // Interpolate to the reference value
25966 var interpolant = referenceTrack.createInterpolant();
25967 var _startIndex2 = referenceOffset;
25969 var _endIndex2 = referenceValueSize - referenceOffset;
25971 interpolant.evaluate(referenceTime);
25972 referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, _startIndex2, _endIndex2);
25973 } // Conjugate the quaternion
25976 if (referenceTrackType === 'quaternion') {
25977 var referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
25978 referenceQuat.toArray(referenceValue);
25979 } // Subtract the reference value from all of the track values
25982 var numTimes = targetTrack.times.length;
25984 for (var j = 0; j < numTimes; ++j) {
25985 var valueStart = j * targetValueSize + targetOffset;
25987 if (referenceTrackType === 'quaternion') {
25988 // Multiply the conjugate for quaternion track types
25989 Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
25991 var valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
25993 for (var k = 0; k < valueEnd; ++k) {
25994 targetTrack.values[valueStart + k] -= referenceValue[k];
26000 for (var i = 0; i < numTracks; ++i) {
26001 var _ret = _loop(i);
26003 if (_ret === "continue") continue;
26006 targetClip.blendMode = AdditiveAnimationBlendMode;
26012 * Abstract base class of interpolants over parametric samples.
26014 * The parameter domain is one dimensional, typically the time or a path
26015 * along a curve defined by the data.
26017 * The sample values can have any dimensionality and derived classes may
26018 * apply special interpretations to the data.
26020 * This class provides the interval seek in a Template Method, deferring
26021 * the actual interpolation to derived classes.
26023 * Time complexity is O(1) for linear access crossing at most two points
26024 * and O(log N) for random access, where N is the number of positions.
26028 * http://www.oodesign.com/template-method-pattern.html
26031 function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
26032 this.parameterPositions = parameterPositions;
26033 this._cachedIndex = 0;
26034 this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
26035 this.sampleValues = sampleValues;
26036 this.valueSize = sampleSize;
26039 Object.assign(Interpolant.prototype, {
26040 evaluate: function evaluate(t) {
26041 var pp = this.parameterPositions;
26042 var i1 = this._cachedIndex,
26046 validate_interval: {
26051 //- See http://jsperf.com/comparison-to-undefined/3
26054 //- if ( t >= t1 || t1 === undefined ) {
26055 forward_scan: if (!(t < t1)) {
26056 for (var giveUpAt = i1 + 2;;) {
26057 if (t1 === undefined) {
26058 if (t < t0) break forward_scan; // after end
26061 this._cachedIndex = i1;
26062 return this.afterEnd_(i1 - 1, t, t0);
26065 if (i1 === giveUpAt) break; // this loop
26071 // we have arrived at the sought interval
26074 } // prepare binary search on the right side of the index
26080 //- if ( t < t0 || t0 === undefined ) {
26085 var t1global = pp[1];
26087 if (t < t1global) {
26088 i1 = 2; // + 1, using the scan for the details
26091 } // linear reverse scan
26094 for (var _giveUpAt = i1 - 2;;) {
26095 if (t0 === undefined) {
26097 this._cachedIndex = 0;
26098 return this.beforeStart_(0, t, t1);
26101 if (i1 === _giveUpAt) break; // this loop
26107 // we have arrived at the sought interval
26110 } // prepare binary search on the left side of the index
26116 } // the interval is valid
26119 break validate_interval;
26124 while (i1 < right) {
26125 var mid = i1 + right >>> 1;
26135 t0 = pp[i1 - 1]; // check boundary cases, again
26137 if (t0 === undefined) {
26138 this._cachedIndex = 0;
26139 return this.beforeStart_(0, t, t1);
26142 if (t1 === undefined) {
26144 this._cachedIndex = i1;
26145 return this.afterEnd_(i1 - 1, t0, t);
26150 this._cachedIndex = i1;
26151 this.intervalChanged_(i1, t0, t1);
26152 } // validate_interval
26155 return this.interpolate_(i1, t0, t, t1);
26158 // optional, subclass-specific settings structure
26159 // Note: The indirection allows central control of many interpolants.
26160 // --- Protected interface
26161 DefaultSettings_: {},
26162 getSettings_: function getSettings_() {
26163 return this.settings || this.DefaultSettings_;
26165 copySampleValue_: function copySampleValue_(index) {
26166 // copies a sample value to the result buffer
26167 var result = this.resultBuffer,
26168 values = this.sampleValues,
26169 stride = this.valueSize,
26170 offset = index * stride;
26172 for (var i = 0; i !== stride; ++i) {
26173 result[i] = values[offset + i];
26178 // Template methods for derived classes:
26179 interpolate_: function interpolate_()
26180 /* i1, t0, t, t1 */
26182 throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
26184 intervalChanged_: function intervalChanged_()
26188 }); // DECLARE ALIAS AFTER assign prototype
26190 Object.assign(Interpolant.prototype, {
26191 //( 0, t, t0 ), returns this.resultBuffer
26192 beforeStart_: Interpolant.prototype.copySampleValue_,
26193 //( N-1, tN-1, t ), returns this.resultBuffer
26194 afterEnd_: Interpolant.prototype.copySampleValue_
26198 * Fast and simple cubic spline interpolant.
26200 * It was derived from a Hermitian construction setting the first derivative
26201 * at each sample position to the linear slope between neighboring positions
26202 * over their parameter interval.
26205 function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
26206 Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
26207 this._weightPrev = -0;
26208 this._offsetPrev = -0;
26209 this._weightNext = -0;
26210 this._offsetNext = -0;
26213 CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
26214 constructor: CubicInterpolant,
26215 DefaultSettings_: {
26216 endingStart: ZeroCurvatureEnding,
26217 endingEnd: ZeroCurvatureEnding
26219 intervalChanged_: function intervalChanged_(i1, t0, t1) {
26220 var pp = this.parameterPositions;
26221 var iPrev = i1 - 2,
26226 if (tPrev === undefined) {
26227 switch (this.getSettings_().endingStart) {
26228 case ZeroSlopeEnding:
26231 tPrev = 2 * t0 - t1;
26234 case WrapAroundEnding:
26235 // use the other end of the curve
26236 iPrev = pp.length - 2;
26237 tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
26241 // ZeroCurvatureEnding
26242 // f''(t0) = 0 a.k.a. Natural Spline
26248 if (tNext === undefined) {
26249 switch (this.getSettings_().endingEnd) {
26250 case ZeroSlopeEnding:
26253 tNext = 2 * t1 - t0;
26256 case WrapAroundEnding:
26257 // use the other end of the curve
26259 tNext = t1 + pp[1] - pp[0];
26263 // ZeroCurvatureEnding
26264 // f''(tN) = 0, a.k.a. Natural Spline
26270 var halfDt = (t1 - t0) * 0.5,
26271 stride = this.valueSize;
26272 this._weightPrev = halfDt / (t0 - tPrev);
26273 this._weightNext = halfDt / (tNext - t1);
26274 this._offsetPrev = iPrev * stride;
26275 this._offsetNext = iNext * stride;
26277 interpolate_: function interpolate_(i1, t0, t, t1) {
26278 var result = this.resultBuffer,
26279 values = this.sampleValues,
26280 stride = this.valueSize,
26283 oP = this._offsetPrev,
26284 oN = this._offsetNext,
26285 wP = this._weightPrev,
26286 wN = this._weightNext,
26287 p = (t - t0) / (t1 - t0),
26289 ppp = pp * p; // evaluate polynomials
26291 var sP = -wP * ppp + 2 * wP * pp - wP * p;
26292 var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
26293 var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
26294 var sN = wN * ppp - wN * pp; // combine data linearly
26296 for (var i = 0; i !== stride; ++i) {
26297 result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
26304 function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
26305 Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
26308 LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
26309 constructor: LinearInterpolant,
26310 interpolate_: function interpolate_(i1, t0, t, t1) {
26311 var result = this.resultBuffer,
26312 values = this.sampleValues,
26313 stride = this.valueSize,
26314 offset1 = i1 * stride,
26315 offset0 = offset1 - stride,
26316 weight1 = (t - t0) / (t1 - t0),
26317 weight0 = 1 - weight1;
26319 for (var i = 0; i !== stride; ++i) {
26320 result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
26329 * Interpolant that evaluates to the sample value at the position preceeding
26333 function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
26334 Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
26337 DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
26338 constructor: DiscreteInterpolant,
26339 interpolate_: function interpolate_(i1
26342 return this.copySampleValue_(i1 - 1);
26346 function KeyframeTrack(name, times, values, interpolation) {
26347 if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
26348 if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
26350 this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
26351 this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
26352 this.setInterpolation(interpolation || this.DefaultInterpolation);
26353 } // Static methods
26356 Object.assign(KeyframeTrack, {
26357 // Serialization (in static context, because of constructor invocation
26358 // and automatic invocation of .toJSON):
26359 toJSON: function toJSON(track) {
26360 var trackType = track.constructor;
26361 var json; // derived classes can define a static toJSON method
26363 if (trackType.toJSON !== undefined) {
26364 json = trackType.toJSON(track);
26366 // by default, we assume the data can be serialized as-is
26368 'name': track.name,
26369 'times': AnimationUtils.convertArray(track.times, Array),
26370 'values': AnimationUtils.convertArray(track.values, Array)
26372 var interpolation = track.getInterpolation();
26374 if (interpolation !== track.DefaultInterpolation) {
26375 json.interpolation = interpolation;
26379 json.type = track.ValueTypeName; // mandatory
26384 Object.assign(KeyframeTrack.prototype, {
26385 constructor: KeyframeTrack,
26386 TimeBufferType: Float32Array,
26387 ValueBufferType: Float32Array,
26388 DefaultInterpolation: InterpolateLinear,
26389 InterpolantFactoryMethodDiscrete: function InterpolantFactoryMethodDiscrete(result) {
26390 return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
26392 InterpolantFactoryMethodLinear: function InterpolantFactoryMethodLinear(result) {
26393 return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
26395 InterpolantFactoryMethodSmooth: function InterpolantFactoryMethodSmooth(result) {
26396 return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
26398 setInterpolation: function setInterpolation(interpolation) {
26401 switch (interpolation) {
26402 case InterpolateDiscrete:
26403 factoryMethod = this.InterpolantFactoryMethodDiscrete;
26406 case InterpolateLinear:
26407 factoryMethod = this.InterpolantFactoryMethodLinear;
26410 case InterpolateSmooth:
26411 factoryMethod = this.InterpolantFactoryMethodSmooth;
26415 if (factoryMethod === undefined) {
26416 var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
26418 if (this.createInterpolant === undefined) {
26419 // fall back to default, unless the default itself is messed up
26420 if (interpolation !== this.DefaultInterpolation) {
26421 this.setInterpolation(this.DefaultInterpolation);
26423 throw new Error(message); // fatal, in this case
26427 console.warn('THREE.KeyframeTrack:', message);
26431 this.createInterpolant = factoryMethod;
26434 getInterpolation: function getInterpolation() {
26435 switch (this.createInterpolant) {
26436 case this.InterpolantFactoryMethodDiscrete:
26437 return InterpolateDiscrete;
26439 case this.InterpolantFactoryMethodLinear:
26440 return InterpolateLinear;
26442 case this.InterpolantFactoryMethodSmooth:
26443 return InterpolateSmooth;
26446 getValueSize: function getValueSize() {
26447 return this.values.length / this.times.length;
26449 // move all keyframes either forwards or backwards in time
26450 shift: function shift(timeOffset) {
26451 if (timeOffset !== 0.0) {
26452 var times = this.times;
26454 for (var i = 0, n = times.length; i !== n; ++i) {
26455 times[i] += timeOffset;
26461 // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
26462 scale: function scale(timeScale) {
26463 if (timeScale !== 1.0) {
26464 var times = this.times;
26466 for (var i = 0, n = times.length; i !== n; ++i) {
26467 times[i] *= timeScale;
26473 // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
26474 // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
26475 trim: function trim(startTime, endTime) {
26476 var times = this.times,
26477 nKeys = times.length;
26481 while (from !== nKeys && times[from] < startTime) {
26485 while (to !== -1 && times[to] > endTime) {
26489 ++to; // inclusive -> exclusive bound
26491 if (from !== 0 || to !== nKeys) {
26492 // empty tracks are forbidden, so keep at least one keyframe
26494 to = Math.max(to, 1);
26498 var stride = this.getValueSize();
26499 this.times = AnimationUtils.arraySlice(times, from, to);
26500 this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
26505 // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
26506 validate: function validate() {
26508 var valueSize = this.getValueSize();
26510 if (valueSize - Math.floor(valueSize) !== 0) {
26511 console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
26515 var times = this.times,
26516 values = this.values,
26517 nKeys = times.length;
26520 console.error('THREE.KeyframeTrack: Track is empty.', this);
26524 var prevTime = null;
26526 for (var i = 0; i !== nKeys; i++) {
26527 var currTime = times[i];
26529 if (typeof currTime === 'number' && isNaN(currTime)) {
26530 console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
26535 if (prevTime !== null && prevTime > currTime) {
26536 console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
26541 prevTime = currTime;
26544 if (values !== undefined) {
26545 if (AnimationUtils.isTypedArray(values)) {
26546 for (var _i = 0, n = values.length; _i !== n; ++_i) {
26547 var value = values[_i];
26549 if (isNaN(value)) {
26550 console.error('THREE.KeyframeTrack: Value is not a valid number.', this, _i, value);
26560 // removes equivalent sequential keys as common in morph target sequences
26561 // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
26562 optimize: function optimize() {
26563 // times or values may be shared with other tracks, so overwriting is unsafe
26564 var times = AnimationUtils.arraySlice(this.times),
26565 values = AnimationUtils.arraySlice(this.values),
26566 stride = this.getValueSize(),
26567 smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
26568 lastIndex = times.length - 1;
26569 var writeIndex = 1;
26571 for (var i = 1; i < lastIndex; ++i) {
26573 var time = times[i];
26574 var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
26576 if (time !== timeNext && (i !== 1 || time !== time[0])) {
26577 if (!smoothInterpolation) {
26578 // remove unnecessary keyframes same as their neighbors
26579 var offset = i * stride,
26580 offsetP = offset - stride,
26581 offsetN = offset + stride;
26583 for (var j = 0; j !== stride; ++j) {
26584 var value = values[offset + j];
26586 if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
26594 } // in-place compaction
26598 if (i !== writeIndex) {
26599 times[writeIndex] = times[i];
26600 var readOffset = i * stride,
26601 writeOffset = writeIndex * stride;
26603 for (var _j = 0; _j !== stride; ++_j) {
26604 values[writeOffset + _j] = values[readOffset + _j];
26610 } // flush last keyframe (compaction looks ahead)
26613 if (lastIndex > 0) {
26614 times[writeIndex] = times[lastIndex];
26616 for (var _readOffset = lastIndex * stride, _writeOffset = writeIndex * stride, _j2 = 0; _j2 !== stride; ++_j2) {
26617 values[_writeOffset + _j2] = values[_readOffset + _j2];
26623 if (writeIndex !== times.length) {
26624 this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
26625 this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
26627 this.times = times;
26628 this.values = values;
26633 clone: function clone() {
26634 var times = AnimationUtils.arraySlice(this.times, 0);
26635 var values = AnimationUtils.arraySlice(this.values, 0);
26636 var TypedKeyframeTrack = this.constructor;
26637 var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
26639 track.createInterpolant = this.createInterpolant;
26645 * A Track of Boolean keyframe values.
26648 function BooleanKeyframeTrack(name, times, values) {
26649 KeyframeTrack.call(this, name, times, values);
26652 BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
26653 constructor: BooleanKeyframeTrack,
26654 ValueTypeName: 'bool',
26655 ValueBufferType: Array,
26656 DefaultInterpolation: InterpolateDiscrete,
26657 InterpolantFactoryMethodLinear: undefined,
26658 InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
26659 // representation of a single value and a custom interpolant that
26660 // computes "firstValue ^ isOdd( index )".
26665 * A Track of keyframe values that represent color.
26668 function ColorKeyframeTrack(name, times, values, interpolation) {
26669 KeyframeTrack.call(this, name, times, values, interpolation);
26672 ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
26673 constructor: ColorKeyframeTrack,
26674 ValueTypeName: 'color' // ValueBufferType is inherited
26675 // DefaultInterpolation is inherited
26676 // Note: Very basic implementation and nothing special yet.
26677 // However, this is the place for color space parameterization.
26682 * A Track of numeric keyframe values.
26685 function NumberKeyframeTrack(name, times, values, interpolation) {
26686 KeyframeTrack.call(this, name, times, values, interpolation);
26689 NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
26690 constructor: NumberKeyframeTrack,
26691 ValueTypeName: 'number' // ValueBufferType is inherited
26692 // DefaultInterpolation is inherited
26697 * Spherical linear unit quaternion interpolant.
26700 function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
26701 Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
26704 QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
26705 constructor: QuaternionLinearInterpolant,
26706 interpolate_: function interpolate_(i1, t0, t, t1) {
26707 var result = this.resultBuffer,
26708 values = this.sampleValues,
26709 stride = this.valueSize,
26710 alpha = (t - t0) / (t1 - t0);
26711 var offset = i1 * stride;
26713 for (var end = offset + stride; offset !== end; offset += 4) {
26714 Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
26722 * A Track of quaternion keyframe values.
26725 function QuaternionKeyframeTrack(name, times, values, interpolation) {
26726 KeyframeTrack.call(this, name, times, values, interpolation);
26729 QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
26730 constructor: QuaternionKeyframeTrack,
26731 ValueTypeName: 'quaternion',
26732 // ValueBufferType is inherited
26733 DefaultInterpolation: InterpolateLinear,
26734 InterpolantFactoryMethodLinear: function InterpolantFactoryMethodLinear(result) {
26735 return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
26737 InterpolantFactoryMethodSmooth: undefined // not yet implemented
26742 * A Track that interpolates Strings
26745 function StringKeyframeTrack(name, times, values, interpolation) {
26746 KeyframeTrack.call(this, name, times, values, interpolation);
26749 StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
26750 constructor: StringKeyframeTrack,
26751 ValueTypeName: 'string',
26752 ValueBufferType: Array,
26753 DefaultInterpolation: InterpolateDiscrete,
26754 InterpolantFactoryMethodLinear: undefined,
26755 InterpolantFactoryMethodSmooth: undefined
26759 * A Track of vectored keyframe values.
26762 function VectorKeyframeTrack(name, times, values, interpolation) {
26763 KeyframeTrack.call(this, name, times, values, interpolation);
26766 VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
26767 constructor: VectorKeyframeTrack,
26768 ValueTypeName: 'vector' // ValueBufferType is inherited
26769 // DefaultInterpolation is inherited
26773 function AnimationClip(name, duration, tracks, blendMode) {
26775 this.tracks = tracks;
26776 this.duration = duration !== undefined ? duration : -1;
26777 this.blendMode = blendMode !== undefined ? blendMode : NormalAnimationBlendMode;
26778 this.uuid = MathUtils.generateUUID(); // this means it should figure out its duration by scanning the tracks
26780 if (this.duration < 0) {
26781 this.resetDuration();
26785 function getTrackTypeForValueTypeName(typeName) {
26786 switch (typeName.toLowerCase()) {
26792 return NumberKeyframeTrack;
26798 return VectorKeyframeTrack;
26801 return ColorKeyframeTrack;
26804 return QuaternionKeyframeTrack;
26808 return BooleanKeyframeTrack;
26811 return StringKeyframeTrack;
26814 throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
26817 function parseKeyframeTrack(json) {
26818 if (json.type === undefined) {
26819 throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
26822 var trackType = getTrackTypeForValueTypeName(json.type);
26824 if (json.times === undefined) {
26827 AnimationUtils.flattenJSON(json.keys, times, values, 'value');
26828 json.times = times;
26829 json.values = values;
26830 } // derived classes can define a static parse method
26833 if (trackType.parse !== undefined) {
26834 return trackType.parse(json);
26836 // by default, we assume a constructor compatible with the base
26837 return new trackType(json.name, json.times, json.values, json.interpolation);
26841 Object.assign(AnimationClip, {
26842 parse: function parse(json) {
26844 jsonTracks = json.tracks,
26845 frameTime = 1.0 / (json.fps || 1.0);
26847 for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
26848 tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
26851 var clip = new AnimationClip(json.name, json.duration, tracks, json.blendMode);
26852 clip.uuid = json.uuid;
26855 toJSON: function toJSON(clip) {
26857 clipTracks = clip.tracks;
26860 'duration': clip.duration,
26863 'blendMode': clip.blendMode
26866 for (var i = 0, n = clipTracks.length; i !== n; ++i) {
26867 tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
26872 CreateFromMorphTargetSequence: function CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
26873 var numMorphTargets = morphTargetSequence.length;
26876 for (var i = 0; i < numMorphTargets; i++) {
26879 times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
26880 values.push(0, 1, 0);
26881 var order = AnimationUtils.getKeyframeOrder(times);
26882 times = AnimationUtils.sortedArray(times, 1, order);
26883 values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
26884 // last frame as well for perfect loop.
26886 if (!noLoop && times[0] === 0) {
26887 times.push(numMorphTargets);
26888 values.push(values[0]);
26891 tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
26894 return new AnimationClip(name, -1, tracks);
26896 findByName: function findByName(objectOrClipArray, name) {
26897 var clipArray = objectOrClipArray;
26899 if (!Array.isArray(objectOrClipArray)) {
26900 var o = objectOrClipArray;
26901 clipArray = o.geometry && o.geometry.animations || o.animations;
26904 for (var i = 0; i < clipArray.length; i++) {
26905 if (clipArray[i].name === name) {
26906 return clipArray[i];
26912 CreateClipsFromMorphTargetSequences: function CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
26913 var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
26914 // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
26916 var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
26917 // patterns like Walk_001, Walk_002, Run_001, Run_002
26919 for (var i = 0, il = morphTargets.length; i < il; i++) {
26920 var morphTarget = morphTargets[i];
26921 var parts = morphTarget.name.match(pattern);
26923 if (parts && parts.length > 1) {
26924 var name = parts[1];
26925 var animationMorphTargets = animationToMorphTargets[name];
26927 if (!animationMorphTargets) {
26928 animationToMorphTargets[name] = animationMorphTargets = [];
26931 animationMorphTargets.push(morphTarget);
26937 for (var _name in animationToMorphTargets) {
26938 clips.push(AnimationClip.CreateFromMorphTargetSequence(_name, animationToMorphTargets[_name], fps, noLoop));
26943 // parse the animation.hierarchy format
26944 parseAnimation: function parseAnimation(animation, bones) {
26946 console.error('THREE.AnimationClip: No animation in JSONLoader data.');
26950 var addNonemptyTrack = function addNonemptyTrack(trackType, trackName, animationKeys, propertyName, destTracks) {
26951 // only return track if there are actually keys.
26952 if (animationKeys.length !== 0) {
26955 AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
26957 if (times.length !== 0) {
26958 destTracks.push(new trackType(trackName, times, values));
26964 var clipName = animation.name || 'default';
26965 var fps = animation.fps || 30;
26966 var blendMode = animation.blendMode; // automatic length determination in AnimationClip.
26968 var duration = animation.length || -1;
26969 var hierarchyTracks = animation.hierarchy || [];
26971 for (var h = 0; h < hierarchyTracks.length; h++) {
26972 var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
26974 if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
26976 if (animationKeys[0].morphTargets) {
26977 // figure out all morph targets used in this track
26978 var morphTargetNames = {};
26981 for (k = 0; k < animationKeys.length; k++) {
26982 if (animationKeys[k].morphTargets) {
26983 for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
26984 morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
26987 } // create a track for each morph target with all zero
26988 // morphTargetInfluences except for the keys in which
26989 // the morphTarget is named.
26992 for (var morphTargetName in morphTargetNames) {
26996 for (var _m = 0; _m !== animationKeys[k].morphTargets.length; ++_m) {
26997 var animationKey = animationKeys[k];
26998 times.push(animationKey.time);
26999 values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
27002 tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
27005 duration = morphTargetNames.length * (fps || 1.0);
27007 // ...assume skeletal animation
27008 var boneName = '.bones[' + bones[h].name + ']';
27009 addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
27010 addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
27011 addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
27015 if (tracks.length === 0) {
27019 var clip = new AnimationClip(clipName, duration, tracks, blendMode);
27023 Object.assign(AnimationClip.prototype, {
27024 resetDuration: function resetDuration() {
27025 var tracks = this.tracks;
27028 for (var i = 0, n = tracks.length; i !== n; ++i) {
27029 var track = this.tracks[i];
27030 duration = Math.max(duration, track.times[track.times.length - 1]);
27033 this.duration = duration;
27036 trim: function trim() {
27037 for (var i = 0; i < this.tracks.length; i++) {
27038 this.tracks[i].trim(0, this.duration);
27043 validate: function validate() {
27046 for (var i = 0; i < this.tracks.length; i++) {
27047 valid = valid && this.tracks[i].validate();
27052 optimize: function optimize() {
27053 for (var i = 0; i < this.tracks.length; i++) {
27054 this.tracks[i].optimize();
27059 clone: function clone() {
27062 for (var i = 0; i < this.tracks.length; i++) {
27063 tracks.push(this.tracks[i].clone());
27066 return new AnimationClip(this.name, this.duration, tracks, this.blendMode);
27068 toJSON: function toJSON() {
27069 return AnimationClip.toJSON(this);
27076 add: function add(key, file) {
27077 if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
27079 this.files[key] = file;
27081 get: function get(key) {
27082 if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
27084 return this.files[key];
27086 remove: function remove(key) {
27087 delete this.files[key];
27089 clear: function clear() {
27094 function LoadingManager(onLoad, onProgress, onError) {
27096 var isLoading = false;
27097 var itemsLoaded = 0;
27098 var itemsTotal = 0;
27099 var urlModifier = undefined;
27100 var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
27101 // in the constructor
27103 this.onStart = undefined;
27104 this.onLoad = onLoad;
27105 this.onProgress = onProgress;
27106 this.onError = onError;
27108 this.itemStart = function (url) {
27111 if (isLoading === false) {
27112 if (scope.onStart !== undefined) {
27113 scope.onStart(url, itemsLoaded, itemsTotal);
27120 this.itemEnd = function (url) {
27123 if (scope.onProgress !== undefined) {
27124 scope.onProgress(url, itemsLoaded, itemsTotal);
27127 if (itemsLoaded === itemsTotal) {
27130 if (scope.onLoad !== undefined) {
27136 this.itemError = function (url) {
27137 if (scope.onError !== undefined) {
27138 scope.onError(url);
27142 this.resolveURL = function (url) {
27144 return urlModifier(url);
27150 this.setURLModifier = function (transform) {
27151 urlModifier = transform;
27155 this.addHandler = function (regex, loader) {
27156 handlers.push(regex, loader);
27160 this.removeHandler = function (regex) {
27161 var index = handlers.indexOf(regex);
27163 if (index !== -1) {
27164 handlers.splice(index, 2);
27170 this.getHandler = function (file) {
27171 for (var i = 0, l = handlers.length; i < l; i += 2) {
27172 var regex = handlers[i];
27173 var loader = handlers[i + 1];
27174 if (regex.global) regex.lastIndex = 0; // see #17920
27176 if (regex.test(file)) {
27185 var DefaultLoadingManager = new LoadingManager();
27187 function Loader(manager) {
27188 this.manager = manager !== undefined ? manager : DefaultLoadingManager;
27189 this.crossOrigin = 'anonymous';
27190 this.withCredentials = false;
27192 this.resourcePath = '';
27193 this.requestHeader = {};
27196 Object.assign(Loader.prototype, {
27197 load: function load()
27198 /* url, onLoad, onProgress, onError */
27200 loadAsync: function loadAsync(url, onProgress) {
27202 return new Promise(function (resolve, reject) {
27203 scope.load(url, resolve, onProgress, reject);
27206 parse: function parse()
27209 setCrossOrigin: function setCrossOrigin(crossOrigin) {
27210 this.crossOrigin = crossOrigin;
27213 setWithCredentials: function setWithCredentials(value) {
27214 this.withCredentials = value;
27217 setPath: function setPath(path) {
27221 setResourcePath: function setResourcePath(resourcePath) {
27222 this.resourcePath = resourcePath;
27225 setRequestHeader: function setRequestHeader(requestHeader) {
27226 this.requestHeader = requestHeader;
27233 function FileLoader(manager) {
27234 Loader.call(this, manager);
27237 FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
27238 constructor: FileLoader,
27239 load: function load(url, onLoad, onProgress, onError) {
27240 if (url === undefined) url = '';
27241 if (this.path !== undefined) url = this.path + url;
27242 url = this.manager.resolveURL(url);
27244 var cached = Cache.get(url);
27246 if (cached !== undefined) {
27247 scope.manager.itemStart(url);
27248 setTimeout(function () {
27249 if (onLoad) onLoad(cached);
27250 scope.manager.itemEnd(url);
27253 } // Check if request is duplicate
27256 if (loading[url] !== undefined) {
27257 loading[url].push({
27259 onProgress: onProgress,
27263 } // Check for data: URI
27266 var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
27267 var dataUriRegexResult = url.match(dataUriRegex);
27268 var request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
27270 if (dataUriRegexResult) {
27271 var mimeType = dataUriRegexResult[1];
27272 var isBase64 = !!dataUriRegexResult[2];
27273 var data = dataUriRegexResult[3];
27274 data = decodeURIComponent(data);
27275 if (isBase64) data = atob(data);
27279 var responseType = (this.responseType || '').toLowerCase();
27281 switch (responseType) {
27282 case 'arraybuffer':
27284 var view = new Uint8Array(data.length);
27286 for (var i = 0; i < data.length; i++) {
27287 view[i] = data.charCodeAt(i);
27290 if (responseType === 'blob') {
27291 response = new Blob([view.buffer], {
27295 response = view.buffer;
27301 var parser = new DOMParser();
27302 response = parser.parseFromString(data, mimeType);
27306 response = JSON.parse(data);
27313 } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
27316 setTimeout(function () {
27317 if (onLoad) onLoad(response);
27318 scope.manager.itemEnd(url);
27321 // Wait for next browser tick like standard XMLHttpRequest event dispatching does
27322 setTimeout(function () {
27323 if (onError) onError(error);
27324 scope.manager.itemError(url);
27325 scope.manager.itemEnd(url);
27329 // Initialise array for duplicate requests
27331 loading[url].push({
27333 onProgress: onProgress,
27336 request = new XMLHttpRequest();
27337 request.open('GET', url, true);
27338 request.addEventListener('load', function (event) {
27339 var response = this.response;
27340 var callbacks = loading[url];
27341 delete loading[url];
27343 if (this.status === 200 || this.status === 0) {
27344 // Some browsers return HTTP Status 0 when using non-http protocol
27345 // e.g. 'file://' or 'data://'. Handle as success.
27346 if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.'); // Add to cache only on HTTP success, so that we do not cache
27347 // error response bodies as proper responses to requests.
27349 Cache.add(url, response);
27351 for (var _i = 0, il = callbacks.length; _i < il; _i++) {
27352 var callback = callbacks[_i];
27353 if (callback.onLoad) callback.onLoad(response);
27356 scope.manager.itemEnd(url);
27358 for (var _i2 = 0, _il = callbacks.length; _i2 < _il; _i2++) {
27359 var _callback = callbacks[_i2];
27360 if (_callback.onError) _callback.onError(event);
27363 scope.manager.itemError(url);
27364 scope.manager.itemEnd(url);
27367 request.addEventListener('progress', function (event) {
27368 var callbacks = loading[url];
27370 for (var _i3 = 0, il = callbacks.length; _i3 < il; _i3++) {
27371 var callback = callbacks[_i3];
27372 if (callback.onProgress) callback.onProgress(event);
27375 request.addEventListener('error', function (event) {
27376 var callbacks = loading[url];
27377 delete loading[url];
27379 for (var _i4 = 0, il = callbacks.length; _i4 < il; _i4++) {
27380 var callback = callbacks[_i4];
27381 if (callback.onError) callback.onError(event);
27384 scope.manager.itemError(url);
27385 scope.manager.itemEnd(url);
27387 request.addEventListener('abort', function (event) {
27388 var callbacks = loading[url];
27389 delete loading[url];
27391 for (var _i5 = 0, il = callbacks.length; _i5 < il; _i5++) {
27392 var callback = callbacks[_i5];
27393 if (callback.onError) callback.onError(event);
27396 scope.manager.itemError(url);
27397 scope.manager.itemEnd(url);
27399 if (this.responseType !== undefined) request.responseType = this.responseType;
27400 if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
27401 if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
27403 for (var header in this.requestHeader) {
27404 request.setRequestHeader(header, this.requestHeader[header]);
27407 request.send(null);
27410 scope.manager.itemStart(url);
27413 setResponseType: function setResponseType(value) {
27414 this.responseType = value;
27417 setMimeType: function setMimeType(value) {
27418 this.mimeType = value;
27423 function AnimationLoader(manager) {
27424 Loader.call(this, manager);
27427 AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
27428 constructor: AnimationLoader,
27429 load: function load(url, onLoad, onProgress, onError) {
27431 var loader = new FileLoader(scope.manager);
27432 loader.setPath(scope.path);
27433 loader.setRequestHeader(scope.requestHeader);
27434 loader.setWithCredentials(scope.withCredentials);
27435 loader.load(url, function (text) {
27437 onLoad(scope.parse(JSON.parse(text)));
27445 scope.manager.itemError(url);
27447 }, onProgress, onError);
27449 parse: function parse(json) {
27450 var animations = [];
27452 for (var i = 0; i < json.length; i++) {
27453 var clip = AnimationClip.parse(json[i]);
27454 animations.push(clip);
27462 * Abstract Base class to block based textures loader (dds, pvr, ...)
27464 * Sub classes have to implement the parse() method which will be used in load().
27467 function CompressedTextureLoader(manager) {
27468 Loader.call(this, manager);
27471 CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
27472 constructor: CompressedTextureLoader,
27473 load: function load(url, onLoad, onProgress, onError) {
27476 var texture = new CompressedTexture();
27477 texture.image = images;
27478 var loader = new FileLoader(this.manager);
27479 loader.setPath(this.path);
27480 loader.setResponseType('arraybuffer');
27481 loader.setRequestHeader(this.requestHeader);
27482 loader.setWithCredentials(scope.withCredentials);
27485 function loadTexture(i) {
27486 loader.load(url[i], function (buffer) {
27487 var texDatas = scope.parse(buffer, true);
27489 width: texDatas.width,
27490 height: texDatas.height,
27491 format: texDatas.format,
27492 mipmaps: texDatas.mipmaps
27496 if (loaded === 6) {
27497 if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
27498 texture.format = texDatas.format;
27499 texture.needsUpdate = true;
27500 if (onLoad) onLoad(texture);
27502 }, onProgress, onError);
27505 if (Array.isArray(url)) {
27506 for (var i = 0, il = url.length; i < il; ++i) {
27510 // compressed cubemap texture stored in a single DDS file
27511 loader.load(url, function (buffer) {
27512 var texDatas = scope.parse(buffer, true);
27514 if (texDatas.isCubemap) {
27515 var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
27517 for (var f = 0; f < faces; f++) {
27522 for (var _i = 0; _i < texDatas.mipmapCount; _i++) {
27523 images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + _i]);
27524 images[f].format = texDatas.format;
27525 images[f].width = texDatas.width;
27526 images[f].height = texDatas.height;
27530 texture.image.width = texDatas.width;
27531 texture.image.height = texDatas.height;
27532 texture.mipmaps = texDatas.mipmaps;
27535 if (texDatas.mipmapCount === 1) {
27536 texture.minFilter = LinearFilter;
27539 texture.format = texDatas.format;
27540 texture.needsUpdate = true;
27541 if (onLoad) onLoad(texture);
27542 }, onProgress, onError);
27549 function ImageLoader(manager) {
27550 Loader.call(this, manager);
27553 ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
27554 constructor: ImageLoader,
27555 load: function load(url, onLoad, onProgress, onError) {
27556 if (this.path !== undefined) url = this.path + url;
27557 url = this.manager.resolveURL(url);
27559 var cached = Cache.get(url);
27561 if (cached !== undefined) {
27562 scope.manager.itemStart(url);
27563 setTimeout(function () {
27564 if (onLoad) onLoad(cached);
27565 scope.manager.itemEnd(url);
27570 var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
27572 function onImageLoad() {
27573 image.removeEventListener('load', onImageLoad, false);
27574 image.removeEventListener('error', onImageError, false);
27575 Cache.add(url, this);
27576 if (onLoad) onLoad(this);
27577 scope.manager.itemEnd(url);
27580 function onImageError(event) {
27581 image.removeEventListener('load', onImageLoad, false);
27582 image.removeEventListener('error', onImageError, false);
27583 if (onError) onError(event);
27584 scope.manager.itemError(url);
27585 scope.manager.itemEnd(url);
27588 image.addEventListener('load', onImageLoad, false);
27589 image.addEventListener('error', onImageError, false);
27591 if (url.substr(0, 5) !== 'data:') {
27592 if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
27595 scope.manager.itemStart(url);
27601 function CubeTextureLoader(manager) {
27602 Loader.call(this, manager);
27605 CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
27606 constructor: CubeTextureLoader,
27607 load: function load(urls, onLoad, onProgress, onError) {
27608 var texture = new CubeTexture();
27609 var loader = new ImageLoader(this.manager);
27610 loader.setCrossOrigin(this.crossOrigin);
27611 loader.setPath(this.path);
27614 function loadTexture(i) {
27615 loader.load(urls[i], function (image) {
27616 texture.images[i] = image;
27619 if (loaded === 6) {
27620 texture.needsUpdate = true;
27621 if (onLoad) onLoad(texture);
27623 }, undefined, onError);
27626 for (var i = 0; i < urls.length; ++i) {
27635 * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
27637 * Sub classes have to implement the parse() method which will be used in load().
27640 function DataTextureLoader(manager) {
27641 Loader.call(this, manager);
27644 DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
27645 constructor: DataTextureLoader,
27646 load: function load(url, onLoad, onProgress, onError) {
27648 var texture = new DataTexture();
27649 var loader = new FileLoader(this.manager);
27650 loader.setResponseType('arraybuffer');
27651 loader.setRequestHeader(this.requestHeader);
27652 loader.setPath(this.path);
27653 loader.setWithCredentials(scope.withCredentials);
27654 loader.load(url, function (buffer) {
27655 var texData = scope.parse(buffer);
27656 if (!texData) return;
27658 if (texData.image !== undefined) {
27659 texture.image = texData.image;
27660 } else if (texData.data !== undefined) {
27661 texture.image.width = texData.width;
27662 texture.image.height = texData.height;
27663 texture.image.data = texData.data;
27666 texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
27667 texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
27668 texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
27669 texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
27670 texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
27672 if (texData.format !== undefined) {
27673 texture.format = texData.format;
27676 if (texData.type !== undefined) {
27677 texture.type = texData.type;
27680 if (texData.mipmaps !== undefined) {
27681 texture.mipmaps = texData.mipmaps;
27682 texture.minFilter = LinearMipmapLinearFilter; // presumably...
27685 if (texData.mipmapCount === 1) {
27686 texture.minFilter = LinearFilter;
27689 texture.needsUpdate = true;
27690 if (onLoad) onLoad(texture, texData);
27691 }, onProgress, onError);
27696 function TextureLoader(manager) {
27697 Loader.call(this, manager);
27700 TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
27701 constructor: TextureLoader,
27702 load: function load(url, onLoad, onProgress, onError) {
27703 var texture = new Texture();
27704 var loader = new ImageLoader(this.manager);
27705 loader.setCrossOrigin(this.crossOrigin);
27706 loader.setPath(this.path);
27707 loader.load(url, function (image) {
27708 texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
27710 var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
27711 texture.format = isJPEG ? RGBFormat : RGBAFormat;
27712 texture.needsUpdate = true;
27714 if (onLoad !== undefined) {
27717 }, onProgress, onError);
27723 * Extensible curve object.
27725 * Some common of curve methods:
27726 * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
27727 * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
27728 * .getPoints(), .getSpacedPoints()
27730 * .updateArcLengths()
27732 * This following curves inherit from THREE.Curve:
27736 * THREE.CubicBezierCurve
27737 * THREE.EllipseCurve
27739 * THREE.QuadraticBezierCurve
27740 * THREE.SplineCurve
27743 * THREE.CatmullRomCurve3
27744 * THREE.CubicBezierCurve3
27746 * THREE.QuadraticBezierCurve3
27748 * A series of curves can be represented as a THREE.CurvePath.
27753 this.type = 'Curve';
27754 this.arcLengthDivisions = 200;
27757 Object.assign(Curve.prototype, {
27758 // Virtual base class method to overwrite and implement in subclasses
27760 getPoint: function getPoint()
27761 /* t, optionalTarget */
27763 console.warn('THREE.Curve: .getPoint() not implemented.');
27766 // Get point at relative position in curve according to arc length
27768 getPointAt: function getPointAt(u, optionalTarget) {
27769 var t = this.getUtoTmapping(u);
27770 return this.getPoint(t, optionalTarget);
27772 // Get sequence of points using getPoint( t )
27773 getPoints: function getPoints(divisions) {
27774 if (divisions === void 0) {
27780 for (var d = 0; d <= divisions; d++) {
27781 points.push(this.getPoint(d / divisions));
27786 // Get sequence of points using getPointAt( u )
27787 getSpacedPoints: function getSpacedPoints(divisions) {
27788 if (divisions === void 0) {
27794 for (var d = 0; d <= divisions; d++) {
27795 points.push(this.getPointAt(d / divisions));
27800 // Get total curve arc length
27801 getLength: function getLength() {
27802 var lengths = this.getLengths();
27803 return lengths[lengths.length - 1];
27805 // Get list of cumulative segment lengths
27806 getLengths: function getLengths(divisions) {
27807 if (divisions === undefined) divisions = this.arcLengthDivisions;
27809 if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
27810 return this.cacheArcLengths;
27813 this.needsUpdate = false;
27816 last = this.getPoint(0);
27820 for (var p = 1; p <= divisions; p++) {
27821 current = this.getPoint(p / divisions);
27822 sum += current.distanceTo(last);
27827 this.cacheArcLengths = cache;
27828 return cache; // { sums: cache, sum: sum }; Sum is in the last element.
27830 updateArcLengths: function updateArcLengths() {
27831 this.needsUpdate = true;
27834 // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
27835 getUtoTmapping: function getUtoTmapping(u, distance) {
27836 var arcLengths = this.getLengths();
27838 var il = arcLengths.length;
27839 var targetArcLength; // The targeted u distance value to get
27842 targetArcLength = distance;
27844 targetArcLength = u * arcLengths[il - 1];
27845 } // binary search for the index with largest value smaller than target u distance
27852 while (low <= high) {
27853 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
27855 comparison = arcLengths[i] - targetArcLength;
27857 if (comparison < 0) {
27859 } else if (comparison > 0) {
27869 if (arcLengths[i] === targetArcLength) {
27870 return i / (il - 1);
27871 } // we could get finer grain at lengths, or use simple interpolation between two points
27874 var lengthBefore = arcLengths[i];
27875 var lengthAfter = arcLengths[i + 1];
27876 var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
27878 var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
27880 var t = (i + segmentFraction) / (il - 1);
27883 // Returns a unit vector tangent at t
27884 // In case any sub curve does not implement its tangent derivation,
27885 // 2 points a small delta apart will be used to find its gradient
27886 // which seems to give a reasonable approximation
27887 getTangent: function getTangent(t, optionalTarget) {
27888 var delta = 0.0001;
27889 var t1 = t - delta;
27890 var t2 = t + delta; // Capping in case of danger
27892 if (t1 < 0) t1 = 0;
27893 if (t2 > 1) t2 = 1;
27894 var pt1 = this.getPoint(t1);
27895 var pt2 = this.getPoint(t2);
27896 var tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
27897 tangent.copy(pt2).sub(pt1).normalize();
27900 getTangentAt: function getTangentAt(u, optionalTarget) {
27901 var t = this.getUtoTmapping(u);
27902 return this.getTangent(t, optionalTarget);
27904 computeFrenetFrames: function computeFrenetFrames(segments, closed) {
27905 // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
27906 var normal = new Vector3();
27909 var binormals = [];
27910 var vec = new Vector3();
27911 var mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
27913 for (var i = 0; i <= segments; i++) {
27914 var u = i / segments;
27915 tangents[i] = this.getTangentAt(u, new Vector3());
27916 tangents[i].normalize();
27917 } // select an initial normal vector perpendicular to the first tangent vector,
27918 // and in the direction of the minimum tangent xyz component
27921 normals[0] = new Vector3();
27922 binormals[0] = new Vector3();
27923 var min = Number.MAX_VALUE;
27924 var tx = Math.abs(tangents[0].x);
27925 var ty = Math.abs(tangents[0].y);
27926 var tz = Math.abs(tangents[0].z);
27930 normal.set(1, 0, 0);
27935 normal.set(0, 1, 0);
27939 normal.set(0, 0, 1);
27942 vec.crossVectors(tangents[0], normal).normalize();
27943 normals[0].crossVectors(tangents[0], vec);
27944 binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
27946 for (var _i = 1; _i <= segments; _i++) {
27947 normals[_i] = normals[_i - 1].clone();
27948 binormals[_i] = binormals[_i - 1].clone();
27949 vec.crossVectors(tangents[_i - 1], tangents[_i]);
27951 if (vec.length() > Number.EPSILON) {
27953 var theta = Math.acos(MathUtils.clamp(tangents[_i - 1].dot(tangents[_i]), -1, 1)); // clamp for floating pt errors
27955 normals[_i].applyMatrix4(mat.makeRotationAxis(vec, theta));
27958 binormals[_i].crossVectors(tangents[_i], normals[_i]);
27959 } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
27962 if (closed === true) {
27963 var _theta = Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]), -1, 1));
27965 _theta /= segments;
27967 if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
27971 for (var _i2 = 1; _i2 <= segments; _i2++) {
27972 // twist a little...
27973 normals[_i2].applyMatrix4(mat.makeRotationAxis(tangents[_i2], _theta * _i2));
27975 binormals[_i2].crossVectors(tangents[_i2], normals[_i2]);
27980 tangents: tangents,
27982 binormals: binormals
27985 clone: function clone() {
27986 return new this.constructor().copy(this);
27988 copy: function copy(source) {
27989 this.arcLengthDivisions = source.arcLengthDivisions;
27992 toJSON: function toJSON() {
27997 generator: 'Curve.toJSON'
28000 data.arcLengthDivisions = this.arcLengthDivisions;
28001 data.type = this.type;
28004 fromJSON: function fromJSON(json) {
28005 this.arcLengthDivisions = json.arcLengthDivisions;
28010 function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
28012 this.type = 'EllipseCurve';
28015 this.xRadius = xRadius || 1;
28016 this.yRadius = yRadius || 1;
28017 this.aStartAngle = aStartAngle || 0;
28018 this.aEndAngle = aEndAngle || 2 * Math.PI;
28019 this.aClockwise = aClockwise || false;
28020 this.aRotation = aRotation || 0;
28023 EllipseCurve.prototype = Object.create(Curve.prototype);
28024 EllipseCurve.prototype.constructor = EllipseCurve;
28025 EllipseCurve.prototype.isEllipseCurve = true;
28027 EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
28028 var point = optionalTarget || new Vector2();
28029 var twoPi = Math.PI * 2;
28030 var deltaAngle = this.aEndAngle - this.aStartAngle;
28031 var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
28033 while (deltaAngle < 0) {
28034 deltaAngle += twoPi;
28037 while (deltaAngle > twoPi) {
28038 deltaAngle -= twoPi;
28041 if (deltaAngle < Number.EPSILON) {
28045 deltaAngle = twoPi;
28049 if (this.aClockwise === true && !samePoints) {
28050 if (deltaAngle === twoPi) {
28051 deltaAngle = -twoPi;
28053 deltaAngle = deltaAngle - twoPi;
28057 var angle = this.aStartAngle + t * deltaAngle;
28058 var x = this.aX + this.xRadius * Math.cos(angle);
28059 var y = this.aY + this.yRadius * Math.sin(angle);
28061 if (this.aRotation !== 0) {
28062 var cos = Math.cos(this.aRotation);
28063 var sin = Math.sin(this.aRotation);
28064 var tx = x - this.aX;
28065 var ty = y - this.aY; // Rotate the point about the center of the ellipse.
28067 x = tx * cos - ty * sin + this.aX;
28068 y = tx * sin + ty * cos + this.aY;
28071 return point.set(x, y);
28074 EllipseCurve.prototype.copy = function (source) {
28075 Curve.prototype.copy.call(this, source);
28076 this.aX = source.aX;
28077 this.aY = source.aY;
28078 this.xRadius = source.xRadius;
28079 this.yRadius = source.yRadius;
28080 this.aStartAngle = source.aStartAngle;
28081 this.aEndAngle = source.aEndAngle;
28082 this.aClockwise = source.aClockwise;
28083 this.aRotation = source.aRotation;
28087 EllipseCurve.prototype.toJSON = function () {
28088 var data = Curve.prototype.toJSON.call(this);
28091 data.xRadius = this.xRadius;
28092 data.yRadius = this.yRadius;
28093 data.aStartAngle = this.aStartAngle;
28094 data.aEndAngle = this.aEndAngle;
28095 data.aClockwise = this.aClockwise;
28096 data.aRotation = this.aRotation;
28100 EllipseCurve.prototype.fromJSON = function (json) {
28101 Curve.prototype.fromJSON.call(this, json);
28104 this.xRadius = json.xRadius;
28105 this.yRadius = json.yRadius;
28106 this.aStartAngle = json.aStartAngle;
28107 this.aEndAngle = json.aEndAngle;
28108 this.aClockwise = json.aClockwise;
28109 this.aRotation = json.aRotation;
28113 function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
28114 EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
28115 this.type = 'ArcCurve';
28118 ArcCurve.prototype = Object.create(EllipseCurve.prototype);
28119 ArcCurve.prototype.constructor = ArcCurve;
28120 ArcCurve.prototype.isArcCurve = true;
28123 * Centripetal CatmullRom Curve - which is useful for avoiding
28124 * cusps and self-intersections in non-uniform catmull rom curves.
28125 * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
28127 * curve.type accepts centripetal(default), chordal and catmullrom
28128 * curve.tension is used for catmullrom which defaults to 0.5
28132 Based on an optimized c++ solution in
28133 - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
28134 - http://ideone.com/NoEbVM
28136 This CubicPoly class could be used for reusing some variables and calculations,
28137 but for three.js curve use, it could be possible inlined and flatten into a single function call
28138 which can be placed in CurveUtils.
28141 function CubicPoly() {
28147 * Compute coefficients for a cubic polynomial
28148 * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
28150 * p(0) = x0, p(1) = x1
28152 * p'(0) = t0, p'(1) = t1.
28155 function init(x0, x1, t0, t1) {
28158 c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
28159 c3 = 2 * x0 - 2 * x1 + t0 + t1;
28163 initCatmullRom: function initCatmullRom(x0, x1, x2, x3, tension) {
28164 init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
28166 initNonuniformCatmullRom: function initNonuniformCatmullRom(x0, x1, x2, x3, dt0, dt1, dt2) {
28167 // compute tangents when parameterized in [t1,t2]
28168 var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
28169 var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
28173 init(x1, x2, t1, t2);
28175 calc: function calc(t) {
28178 return c0 + c1 * t + c2 * t2 + c3 * t3;
28184 var tmp = new Vector3();
28185 var px = new CubicPoly(),
28186 py = new CubicPoly(),
28187 pz = new CubicPoly();
28189 function CatmullRomCurve3(points, closed, curveType, tension) {
28190 if (points === void 0) {
28194 if (closed === void 0) {
28198 if (curveType === void 0) {
28199 curveType = 'centripetal';
28202 if (tension === void 0) {
28207 this.type = 'CatmullRomCurve3';
28208 this.points = points;
28209 this.closed = closed;
28210 this.curveType = curveType;
28211 this.tension = tension;
28214 CatmullRomCurve3.prototype = Object.create(Curve.prototype);
28215 CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
28216 CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
28218 CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
28219 if (optionalTarget === void 0) {
28220 optionalTarget = new Vector3();
28223 var point = optionalTarget;
28224 var points = this.points;
28225 var l = points.length;
28226 var p = (l - (this.closed ? 0 : 1)) * t;
28227 var intPoint = Math.floor(p);
28228 var weight = p - intPoint;
28231 intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
28232 } else if (weight === 0 && intPoint === l - 1) {
28237 var p0, p3; // 4 points (p1 & p2 defined below)
28239 if (this.closed || intPoint > 0) {
28240 p0 = points[(intPoint - 1) % l];
28242 // extrapolate first point
28243 tmp.subVectors(points[0], points[1]).add(points[0]);
28247 var p1 = points[intPoint % l];
28248 var p2 = points[(intPoint + 1) % l];
28250 if (this.closed || intPoint + 2 < l) {
28251 p3 = points[(intPoint + 2) % l];
28253 // extrapolate last point
28254 tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
28258 if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
28259 // init Centripetal / Chordal Catmull-Rom
28260 var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
28261 var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
28262 var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
28263 var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
28265 if (dt1 < 1e-4) dt1 = 1.0;
28266 if (dt0 < 1e-4) dt0 = dt1;
28267 if (dt2 < 1e-4) dt2 = dt1;
28268 px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
28269 py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
28270 pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
28271 } else if (this.curveType === 'catmullrom') {
28272 px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
28273 py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
28274 pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
28277 point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
28281 CatmullRomCurve3.prototype.copy = function (source) {
28282 Curve.prototype.copy.call(this, source);
28285 for (var i = 0, l = source.points.length; i < l; i++) {
28286 var point = source.points[i];
28287 this.points.push(point.clone());
28290 this.closed = source.closed;
28291 this.curveType = source.curveType;
28292 this.tension = source.tension;
28296 CatmullRomCurve3.prototype.toJSON = function () {
28297 var data = Curve.prototype.toJSON.call(this);
28300 for (var i = 0, l = this.points.length; i < l; i++) {
28301 var point = this.points[i];
28302 data.points.push(point.toArray());
28305 data.closed = this.closed;
28306 data.curveType = this.curveType;
28307 data.tension = this.tension;
28311 CatmullRomCurve3.prototype.fromJSON = function (json) {
28312 Curve.prototype.fromJSON.call(this, json);
28315 for (var i = 0, l = json.points.length; i < l; i++) {
28316 var point = json.points[i];
28317 this.points.push(new Vector3().fromArray(point));
28320 this.closed = json.closed;
28321 this.curveType = json.curveType;
28322 this.tension = json.tension;
28327 * Bezier Curves formulas obtained from
28328 * http://en.wikipedia.org/wiki/Bézier_curve
28330 function CatmullRom(t, p0, p1, p2, p3) {
28331 var v0 = (p2 - p0) * 0.5;
28332 var v1 = (p3 - p1) * 0.5;
28335 return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
28339 function QuadraticBezierP0(t, p) {
28344 function QuadraticBezierP1(t, p) {
28345 return 2 * (1 - t) * t * p;
28348 function QuadraticBezierP2(t, p) {
28352 function QuadraticBezier(t, p0, p1, p2) {
28353 return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
28357 function CubicBezierP0(t, p) {
28359 return k * k * k * p;
28362 function CubicBezierP1(t, p) {
28364 return 3 * k * k * t * p;
28367 function CubicBezierP2(t, p) {
28368 return 3 * (1 - t) * t * t * p;
28371 function CubicBezierP3(t, p) {
28372 return t * t * t * p;
28375 function CubicBezier(t, p0, p1, p2, p3) {
28376 return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
28379 function CubicBezierCurve(v0, v1, v2, v3) {
28380 if (v0 === void 0) {
28381 v0 = new Vector2();
28384 if (v1 === void 0) {
28385 v1 = new Vector2();
28388 if (v2 === void 0) {
28389 v2 = new Vector2();
28392 if (v3 === void 0) {
28393 v3 = new Vector2();
28397 this.type = 'CubicBezierCurve';
28404 CubicBezierCurve.prototype = Object.create(Curve.prototype);
28405 CubicBezierCurve.prototype.constructor = CubicBezierCurve;
28406 CubicBezierCurve.prototype.isCubicBezierCurve = true;
28408 CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
28409 if (optionalTarget === void 0) {
28410 optionalTarget = new Vector2();
28413 var point = optionalTarget;
28418 point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
28422 CubicBezierCurve.prototype.copy = function (source) {
28423 Curve.prototype.copy.call(this, source);
28424 this.v0.copy(source.v0);
28425 this.v1.copy(source.v1);
28426 this.v2.copy(source.v2);
28427 this.v3.copy(source.v3);
28431 CubicBezierCurve.prototype.toJSON = function () {
28432 var data = Curve.prototype.toJSON.call(this);
28433 data.v0 = this.v0.toArray();
28434 data.v1 = this.v1.toArray();
28435 data.v2 = this.v2.toArray();
28436 data.v3 = this.v3.toArray();
28440 CubicBezierCurve.prototype.fromJSON = function (json) {
28441 Curve.prototype.fromJSON.call(this, json);
28442 this.v0.fromArray(json.v0);
28443 this.v1.fromArray(json.v1);
28444 this.v2.fromArray(json.v2);
28445 this.v3.fromArray(json.v3);
28449 function CubicBezierCurve3(v0, v1, v2, v3) {
28450 if (v0 === void 0) {
28451 v0 = new Vector3();
28454 if (v1 === void 0) {
28455 v1 = new Vector3();
28458 if (v2 === void 0) {
28459 v2 = new Vector3();
28462 if (v3 === void 0) {
28463 v3 = new Vector3();
28467 this.type = 'CubicBezierCurve3';
28474 CubicBezierCurve3.prototype = Object.create(Curve.prototype);
28475 CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
28476 CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
28478 CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
28479 if (optionalTarget === void 0) {
28480 optionalTarget = new Vector3();
28483 var point = optionalTarget;
28488 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));
28492 CubicBezierCurve3.prototype.copy = function (source) {
28493 Curve.prototype.copy.call(this, source);
28494 this.v0.copy(source.v0);
28495 this.v1.copy(source.v1);
28496 this.v2.copy(source.v2);
28497 this.v3.copy(source.v3);
28501 CubicBezierCurve3.prototype.toJSON = function () {
28502 var data = Curve.prototype.toJSON.call(this);
28503 data.v0 = this.v0.toArray();
28504 data.v1 = this.v1.toArray();
28505 data.v2 = this.v2.toArray();
28506 data.v3 = this.v3.toArray();
28510 CubicBezierCurve3.prototype.fromJSON = function (json) {
28511 Curve.prototype.fromJSON.call(this, json);
28512 this.v0.fromArray(json.v0);
28513 this.v1.fromArray(json.v1);
28514 this.v2.fromArray(json.v2);
28515 this.v3.fromArray(json.v3);
28519 function LineCurve(v1, v2) {
28520 if (v1 === void 0) {
28521 v1 = new Vector2();
28524 if (v2 === void 0) {
28525 v2 = new Vector2();
28529 this.type = 'LineCurve';
28534 LineCurve.prototype = Object.create(Curve.prototype);
28535 LineCurve.prototype.constructor = LineCurve;
28536 LineCurve.prototype.isLineCurve = true;
28538 LineCurve.prototype.getPoint = function (t, optionalTarget) {
28539 if (optionalTarget === void 0) {
28540 optionalTarget = new Vector2();
28543 var point = optionalTarget;
28546 point.copy(this.v2);
28548 point.copy(this.v2).sub(this.v1);
28549 point.multiplyScalar(t).add(this.v1);
28553 }; // Line curve is linear, so we can overwrite default getPointAt
28556 LineCurve.prototype.getPointAt = function (u, optionalTarget) {
28557 return this.getPoint(u, optionalTarget);
28560 LineCurve.prototype.getTangent = function (t, optionalTarget) {
28561 var tangent = optionalTarget || new Vector2();
28562 tangent.copy(this.v2).sub(this.v1).normalize();
28566 LineCurve.prototype.copy = function (source) {
28567 Curve.prototype.copy.call(this, source);
28568 this.v1.copy(source.v1);
28569 this.v2.copy(source.v2);
28573 LineCurve.prototype.toJSON = function () {
28574 var data = Curve.prototype.toJSON.call(this);
28575 data.v1 = this.v1.toArray();
28576 data.v2 = this.v2.toArray();
28580 LineCurve.prototype.fromJSON = function (json) {
28581 Curve.prototype.fromJSON.call(this, json);
28582 this.v1.fromArray(json.v1);
28583 this.v2.fromArray(json.v2);
28587 function LineCurve3(v1, v2) {
28588 if (v1 === void 0) {
28589 v1 = new Vector3();
28592 if (v2 === void 0) {
28593 v2 = new Vector3();
28597 this.type = 'LineCurve3';
28602 LineCurve3.prototype = Object.create(Curve.prototype);
28603 LineCurve3.prototype.constructor = LineCurve3;
28604 LineCurve3.prototype.isLineCurve3 = true;
28606 LineCurve3.prototype.getPoint = function (t, optionalTarget) {
28607 if (optionalTarget === void 0) {
28608 optionalTarget = new Vector3();
28611 var point = optionalTarget;
28614 point.copy(this.v2);
28616 point.copy(this.v2).sub(this.v1);
28617 point.multiplyScalar(t).add(this.v1);
28621 }; // Line curve is linear, so we can overwrite default getPointAt
28624 LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
28625 return this.getPoint(u, optionalTarget);
28628 LineCurve3.prototype.copy = function (source) {
28629 Curve.prototype.copy.call(this, source);
28630 this.v1.copy(source.v1);
28631 this.v2.copy(source.v2);
28635 LineCurve3.prototype.toJSON = function () {
28636 var data = Curve.prototype.toJSON.call(this);
28637 data.v1 = this.v1.toArray();
28638 data.v2 = this.v2.toArray();
28642 LineCurve3.prototype.fromJSON = function (json) {
28643 Curve.prototype.fromJSON.call(this, json);
28644 this.v1.fromArray(json.v1);
28645 this.v2.fromArray(json.v2);
28649 function QuadraticBezierCurve(v0, v1, v2) {
28650 if (v0 === void 0) {
28651 v0 = new Vector2();
28654 if (v1 === void 0) {
28655 v1 = new Vector2();
28658 if (v2 === void 0) {
28659 v2 = new Vector2();
28663 this.type = 'QuadraticBezierCurve';
28669 QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
28670 QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
28671 QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
28673 QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
28674 if (optionalTarget === void 0) {
28675 optionalTarget = new Vector2();
28678 var point = optionalTarget;
28682 point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
28686 QuadraticBezierCurve.prototype.copy = function (source) {
28687 Curve.prototype.copy.call(this, source);
28688 this.v0.copy(source.v0);
28689 this.v1.copy(source.v1);
28690 this.v2.copy(source.v2);
28694 QuadraticBezierCurve.prototype.toJSON = function () {
28695 var data = Curve.prototype.toJSON.call(this);
28696 data.v0 = this.v0.toArray();
28697 data.v1 = this.v1.toArray();
28698 data.v2 = this.v2.toArray();
28702 QuadraticBezierCurve.prototype.fromJSON = function (json) {
28703 Curve.prototype.fromJSON.call(this, json);
28704 this.v0.fromArray(json.v0);
28705 this.v1.fromArray(json.v1);
28706 this.v2.fromArray(json.v2);
28710 function QuadraticBezierCurve3(v0, v1, v2) {
28711 if (v0 === void 0) {
28712 v0 = new Vector3();
28715 if (v1 === void 0) {
28716 v1 = new Vector3();
28719 if (v2 === void 0) {
28720 v2 = new Vector3();
28724 this.type = 'QuadraticBezierCurve3';
28730 QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
28731 QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
28732 QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
28734 QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
28735 if (optionalTarget === void 0) {
28736 optionalTarget = new Vector3();
28739 var point = optionalTarget;
28743 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));
28747 QuadraticBezierCurve3.prototype.copy = function (source) {
28748 Curve.prototype.copy.call(this, source);
28749 this.v0.copy(source.v0);
28750 this.v1.copy(source.v1);
28751 this.v2.copy(source.v2);
28755 QuadraticBezierCurve3.prototype.toJSON = function () {
28756 var data = Curve.prototype.toJSON.call(this);
28757 data.v0 = this.v0.toArray();
28758 data.v1 = this.v1.toArray();
28759 data.v2 = this.v2.toArray();
28763 QuadraticBezierCurve3.prototype.fromJSON = function (json) {
28764 Curve.prototype.fromJSON.call(this, json);
28765 this.v0.fromArray(json.v0);
28766 this.v1.fromArray(json.v1);
28767 this.v2.fromArray(json.v2);
28771 function SplineCurve(points) {
28772 if (points === void 0) {
28777 this.type = 'SplineCurve';
28778 this.points = points;
28781 SplineCurve.prototype = Object.create(Curve.prototype);
28782 SplineCurve.prototype.constructor = SplineCurve;
28783 SplineCurve.prototype.isSplineCurve = true;
28785 SplineCurve.prototype.getPoint = function (t, optionalTarget) {
28786 if (optionalTarget === void 0) {
28787 optionalTarget = new Vector2();
28790 var point = optionalTarget;
28791 var points = this.points;
28792 var p = (points.length - 1) * t;
28793 var intPoint = Math.floor(p);
28794 var weight = p - intPoint;
28795 var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
28796 var p1 = points[intPoint];
28797 var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
28798 var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
28799 point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
28803 SplineCurve.prototype.copy = function (source) {
28804 Curve.prototype.copy.call(this, source);
28807 for (var i = 0, l = source.points.length; i < l; i++) {
28808 var point = source.points[i];
28809 this.points.push(point.clone());
28815 SplineCurve.prototype.toJSON = function () {
28816 var data = Curve.prototype.toJSON.call(this);
28819 for (var i = 0, l = this.points.length; i < l; i++) {
28820 var point = this.points[i];
28821 data.points.push(point.toArray());
28827 SplineCurve.prototype.fromJSON = function (json) {
28828 Curve.prototype.fromJSON.call(this, json);
28831 for (var i = 0, l = json.points.length; i < l; i++) {
28832 var point = json.points[i];
28833 this.points.push(new Vector2().fromArray(point));
28839 var Curves = /*#__PURE__*/Object.freeze({
28841 ArcCurve: ArcCurve,
28842 CatmullRomCurve3: CatmullRomCurve3,
28843 CubicBezierCurve: CubicBezierCurve,
28844 CubicBezierCurve3: CubicBezierCurve3,
28845 EllipseCurve: EllipseCurve,
28846 LineCurve: LineCurve,
28847 LineCurve3: LineCurve3,
28848 QuadraticBezierCurve: QuadraticBezierCurve,
28849 QuadraticBezierCurve3: QuadraticBezierCurve3,
28850 SplineCurve: SplineCurve
28853 /**************************************************************
28854 * Curved Path - a curve path is simply a array of connected
28855 * curves, but retains the api of a curve
28856 **************************************************************/
28858 function CurvePath() {
28860 this.type = 'CurvePath';
28862 this.autoClose = false; // Automatically closes the path
28865 CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
28866 constructor: CurvePath,
28867 add: function add(curve) {
28868 this.curves.push(curve);
28870 closePath: function closePath() {
28871 // Add a line curve if start and end of lines are not connected
28872 var startPoint = this.curves[0].getPoint(0);
28873 var endPoint = this.curves[this.curves.length - 1].getPoint(1);
28875 if (!startPoint.equals(endPoint)) {
28876 this.curves.push(new LineCurve(endPoint, startPoint));
28879 // To get accurate point with reference to
28880 // entire path distance at time t,
28881 // following has to be done:
28882 // 1. Length of each sub path have to be known
28883 // 2. Locate and identify type of curve
28884 // 3. Get t for the curve
28885 // 4. Return curve.getPointAt(t')
28886 getPoint: function getPoint(t) {
28887 var d = t * this.getLength();
28888 var curveLengths = this.getCurveLengths();
28889 var i = 0; // To think about boundaries points.
28891 while (i < curveLengths.length) {
28892 if (curveLengths[i] >= d) {
28893 var diff = curveLengths[i] - d;
28894 var curve = this.curves[i];
28895 var segmentLength = curve.getLength();
28896 var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
28897 return curve.getPointAt(u);
28903 return null; // loop where sum != 0, sum > d , sum+1 <d
28905 // We cannot use the default THREE.Curve getPoint() with getLength() because in
28906 // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
28907 // getPoint() depends on getLength
28908 getLength: function getLength() {
28909 var lens = this.getCurveLengths();
28910 return lens[lens.length - 1];
28912 // cacheLengths must be recalculated.
28913 updateArcLengths: function updateArcLengths() {
28914 this.needsUpdate = true;
28915 this.cacheLengths = null;
28916 this.getCurveLengths();
28918 // Compute lengths and cache them
28919 // We cannot overwrite getLengths() because UtoT mapping uses it.
28920 getCurveLengths: function getCurveLengths() {
28921 // We use cache values if curves and cache array are same length
28922 if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
28923 return this.cacheLengths;
28924 } // Get length of sub-curve
28925 // Push sums into cached array
28931 for (var i = 0, l = this.curves.length; i < l; i++) {
28932 sums += this.curves[i].getLength();
28933 lengths.push(sums);
28936 this.cacheLengths = lengths;
28939 getSpacedPoints: function getSpacedPoints(divisions) {
28940 if (divisions === void 0) {
28946 for (var i = 0; i <= divisions; i++) {
28947 points.push(this.getPoint(i / divisions));
28950 if (this.autoClose) {
28951 points.push(points[0]);
28956 getPoints: function getPoints(divisions) {
28957 if (divisions === void 0) {
28964 for (var i = 0, curves = this.curves; i < curves.length; i++) {
28965 var curve = curves[i];
28966 var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
28967 var pts = curve.getPoints(resolution);
28969 for (var j = 0; j < pts.length; j++) {
28970 var point = pts[j];
28971 if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
28973 points.push(point);
28978 if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
28979 points.push(points[0]);
28984 copy: function copy(source) {
28985 Curve.prototype.copy.call(this, source);
28988 for (var i = 0, l = source.curves.length; i < l; i++) {
28989 var curve = source.curves[i];
28990 this.curves.push(curve.clone());
28993 this.autoClose = source.autoClose;
28996 toJSON: function toJSON() {
28997 var data = Curve.prototype.toJSON.call(this);
28998 data.autoClose = this.autoClose;
29001 for (var i = 0, l = this.curves.length; i < l; i++) {
29002 var curve = this.curves[i];
29003 data.curves.push(curve.toJSON());
29008 fromJSON: function fromJSON(json) {
29009 Curve.prototype.fromJSON.call(this, json);
29010 this.autoClose = json.autoClose;
29013 for (var i = 0, l = json.curves.length; i < l; i++) {
29014 var curve = json.curves[i];
29015 this.curves.push(new Curves[curve.type]().fromJSON(curve));
29022 function Path(points) {
29023 CurvePath.call(this);
29024 this.type = 'Path';
29025 this.currentPoint = new Vector2();
29028 this.setFromPoints(points);
29032 Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
29034 setFromPoints: function setFromPoints(points) {
29035 this.moveTo(points[0].x, points[0].y);
29037 for (var i = 1, l = points.length; i < l; i++) {
29038 this.lineTo(points[i].x, points[i].y);
29043 moveTo: function moveTo(x, y) {
29044 this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
29048 lineTo: function lineTo(x, y) {
29049 var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
29050 this.curves.push(curve);
29051 this.currentPoint.set(x, y);
29054 quadraticCurveTo: function quadraticCurveTo(aCPx, aCPy, aX, aY) {
29055 var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
29056 this.curves.push(curve);
29057 this.currentPoint.set(aX, aY);
29060 bezierCurveTo: function bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
29061 var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
29062 this.curves.push(curve);
29063 this.currentPoint.set(aX, aY);
29066 splineThru: function splineThru(pts
29067 /*Array of Vector*/
29069 var npts = [this.currentPoint.clone()].concat(pts);
29070 var curve = new SplineCurve(npts);
29071 this.curves.push(curve);
29072 this.currentPoint.copy(pts[pts.length - 1]);
29075 arc: function arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
29076 var x0 = this.currentPoint.x;
29077 var y0 = this.currentPoint.y;
29078 this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
29081 absarc: function absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
29082 this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
29085 ellipse: function ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
29086 var x0 = this.currentPoint.x;
29087 var y0 = this.currentPoint.y;
29088 this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
29091 absellipse: function absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
29092 var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
29094 if (this.curves.length > 0) {
29095 // if a previous curve is present, attempt to join
29096 var firstPoint = curve.getPoint(0);
29098 if (!firstPoint.equals(this.currentPoint)) {
29099 this.lineTo(firstPoint.x, firstPoint.y);
29103 this.curves.push(curve);
29104 var lastPoint = curve.getPoint(1);
29105 this.currentPoint.copy(lastPoint);
29108 copy: function copy(source) {
29109 CurvePath.prototype.copy.call(this, source);
29110 this.currentPoint.copy(source.currentPoint);
29113 toJSON: function toJSON() {
29114 var data = CurvePath.prototype.toJSON.call(this);
29115 data.currentPoint = this.currentPoint.toArray();
29118 fromJSON: function fromJSON(json) {
29119 CurvePath.prototype.fromJSON.call(this, json);
29120 this.currentPoint.fromArray(json.currentPoint);
29125 function Shape(points) {
29126 Path.call(this, points);
29127 this.uuid = MathUtils.generateUUID();
29128 this.type = 'Shape';
29132 Shape.prototype = Object.assign(Object.create(Path.prototype), {
29133 constructor: Shape,
29134 getPointsHoles: function getPointsHoles(divisions) {
29137 for (var i = 0, l = this.holes.length; i < l; i++) {
29138 holesPts[i] = this.holes[i].getPoints(divisions);
29143 // get points of shape and holes (keypoints based on segments parameter)
29144 extractPoints: function extractPoints(divisions) {
29146 shape: this.getPoints(divisions),
29147 holes: this.getPointsHoles(divisions)
29150 copy: function copy(source) {
29151 Path.prototype.copy.call(this, source);
29154 for (var i = 0, l = source.holes.length; i < l; i++) {
29155 var hole = source.holes[i];
29156 this.holes.push(hole.clone());
29161 toJSON: function toJSON() {
29162 var data = Path.prototype.toJSON.call(this);
29163 data.uuid = this.uuid;
29166 for (var i = 0, l = this.holes.length; i < l; i++) {
29167 var hole = this.holes[i];
29168 data.holes.push(hole.toJSON());
29173 fromJSON: function fromJSON(json) {
29174 Path.prototype.fromJSON.call(this, json);
29175 this.uuid = json.uuid;
29178 for (var i = 0, l = json.holes.length; i < l; i++) {
29179 var hole = json.holes[i];
29180 this.holes.push(new Path().fromJSON(hole));
29187 function Light(color, intensity) {
29188 if (intensity === void 0) {
29192 Object3D.call(this);
29193 this.type = 'Light';
29194 this.color = new Color(color);
29195 this.intensity = intensity;
29198 Light.prototype = Object.assign(Object.create(Object3D.prototype), {
29199 constructor: Light,
29201 copy: function copy(source) {
29202 Object3D.prototype.copy.call(this, source);
29203 this.color.copy(source.color);
29204 this.intensity = source.intensity;
29207 toJSON: function toJSON(meta) {
29208 var data = Object3D.prototype.toJSON.call(this, meta);
29209 data.object.color = this.color.getHex();
29210 data.object.intensity = this.intensity;
29211 if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
29212 if (this.distance !== undefined) data.object.distance = this.distance;
29213 if (this.angle !== undefined) data.object.angle = this.angle;
29214 if (this.decay !== undefined) data.object.decay = this.decay;
29215 if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
29216 if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
29221 function HemisphereLight(skyColor, groundColor, intensity) {
29222 Light.call(this, skyColor, intensity);
29223 this.type = 'HemisphereLight';
29224 this.position.copy(Object3D.DefaultUp);
29225 this.updateMatrix();
29226 this.groundColor = new Color(groundColor);
29229 HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
29230 constructor: HemisphereLight,
29231 isHemisphereLight: true,
29232 copy: function copy(source) {
29233 Light.prototype.copy.call(this, source);
29234 this.groundColor.copy(source.groundColor);
29239 function LightShadow(camera) {
29240 this.camera = camera;
29242 this.normalBias = 0;
29244 this.mapSize = new Vector2(512, 512);
29246 this.mapPass = null;
29247 this.matrix = new Matrix4();
29248 this.autoUpdate = true;
29249 this.needsUpdate = false;
29250 this._frustum = new Frustum();
29251 this._frameExtents = new Vector2(1, 1);
29252 this._viewportCount = 1;
29253 this._viewports = [new Vector4(0, 0, 1, 1)];
29256 Object.assign(LightShadow.prototype, {
29257 _projScreenMatrix: new Matrix4(),
29258 _lightPositionWorld: new Vector3(),
29259 _lookTarget: new Vector3(),
29260 getViewportCount: function getViewportCount() {
29261 return this._viewportCount;
29263 getFrustum: function getFrustum() {
29264 return this._frustum;
29266 updateMatrices: function updateMatrices(light) {
29267 var shadowCamera = this.camera,
29268 shadowMatrix = this.matrix,
29269 projScreenMatrix = this._projScreenMatrix,
29270 lookTarget = this._lookTarget,
29271 lightPositionWorld = this._lightPositionWorld;
29272 lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
29273 shadowCamera.position.copy(lightPositionWorld);
29274 lookTarget.setFromMatrixPosition(light.target.matrixWorld);
29275 shadowCamera.lookAt(lookTarget);
29276 shadowCamera.updateMatrixWorld();
29277 projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
29279 this._frustum.setFromProjectionMatrix(projScreenMatrix);
29281 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);
29282 shadowMatrix.multiply(shadowCamera.projectionMatrix);
29283 shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
29285 getViewport: function getViewport(viewportIndex) {
29286 return this._viewports[viewportIndex];
29288 getFrameExtents: function getFrameExtents() {
29289 return this._frameExtents;
29291 copy: function copy(source) {
29292 this.camera = source.camera.clone();
29293 this.bias = source.bias;
29294 this.radius = source.radius;
29295 this.mapSize.copy(source.mapSize);
29298 clone: function clone() {
29299 return new this.constructor().copy(this);
29301 toJSON: function toJSON() {
29303 if (this.bias !== 0) object.bias = this.bias;
29304 if (this.normalBias !== 0) object.normalBias = this.normalBias;
29305 if (this.radius !== 1) object.radius = this.radius;
29306 if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
29307 object.camera = this.camera.toJSON(false).object;
29308 delete object.camera.matrix;
29313 function SpotLightShadow() {
29314 LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
29318 SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
29319 constructor: SpotLightShadow,
29320 isSpotLightShadow: true,
29321 updateMatrices: function updateMatrices(light) {
29322 var camera = this.camera;
29323 var fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
29324 var aspect = this.mapSize.width / this.mapSize.height;
29325 var far = light.distance || camera.far;
29327 if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
29329 camera.aspect = aspect;
29331 camera.updateProjectionMatrix();
29334 LightShadow.prototype.updateMatrices.call(this, light);
29338 function SpotLight(color, intensity, distance, angle, penumbra, decay) {
29339 Light.call(this, color, intensity);
29340 this.type = 'SpotLight';
29341 this.position.copy(Object3D.DefaultUp);
29342 this.updateMatrix();
29343 this.target = new Object3D();
29344 Object.defineProperty(this, 'power', {
29345 get: function get() {
29346 // intensity = power per solid angle.
29347 // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
29348 return this.intensity * Math.PI;
29350 set: function set(power) {
29351 // intensity = power per solid angle.
29352 // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
29353 this.intensity = power / Math.PI;
29356 this.distance = distance !== undefined ? distance : 0;
29357 this.angle = angle !== undefined ? angle : Math.PI / 3;
29358 this.penumbra = penumbra !== undefined ? penumbra : 0;
29359 this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
29361 this.shadow = new SpotLightShadow();
29364 SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
29365 constructor: SpotLight,
29367 copy: function copy(source) {
29368 Light.prototype.copy.call(this, source);
29369 this.distance = source.distance;
29370 this.angle = source.angle;
29371 this.penumbra = source.penumbra;
29372 this.decay = source.decay;
29373 this.target = source.target.clone();
29374 this.shadow = source.shadow.clone();
29379 function PointLightShadow() {
29380 LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
29381 this._frameExtents = new Vector2(4, 2);
29382 this._viewportCount = 6;
29383 this._viewports = [// These viewports map a cube-map onto a 2D texture with the
29384 // following orientation:
29389 // X - Positive x direction
29390 // x - Negative x direction
29391 // Y - Positive y direction
29392 // y - Negative y direction
29393 // Z - Positive z direction
29394 // z - Negative z direction
29396 new Vector4(2, 1, 1, 1), // negative X
29397 new Vector4(0, 1, 1, 1), // positive Z
29398 new Vector4(3, 1, 1, 1), // negative Z
29399 new Vector4(1, 1, 1, 1), // positive Y
29400 new Vector4(3, 0, 1, 1), // negative Y
29401 new Vector4(1, 0, 1, 1)];
29402 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)];
29403 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)];
29406 PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
29407 constructor: PointLightShadow,
29408 isPointLightShadow: true,
29409 updateMatrices: function updateMatrices(light, viewportIndex) {
29410 if (viewportIndex === void 0) {
29414 var camera = this.camera,
29415 shadowMatrix = this.matrix,
29416 lightPositionWorld = this._lightPositionWorld,
29417 lookTarget = this._lookTarget,
29418 projScreenMatrix = this._projScreenMatrix;
29419 lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
29420 camera.position.copy(lightPositionWorld);
29421 lookTarget.copy(camera.position);
29422 lookTarget.add(this._cubeDirections[viewportIndex]);
29423 camera.up.copy(this._cubeUps[viewportIndex]);
29424 camera.lookAt(lookTarget);
29425 camera.updateMatrixWorld();
29426 shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
29427 projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
29429 this._frustum.setFromProjectionMatrix(projScreenMatrix);
29433 function PointLight(color, intensity, distance, decay) {
29434 Light.call(this, color, intensity);
29435 this.type = 'PointLight';
29436 Object.defineProperty(this, 'power', {
29437 get: function get() {
29438 // intensity = power per solid angle.
29439 // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
29440 return this.intensity * 4 * Math.PI;
29442 set: function set(power) {
29443 // intensity = power per solid angle.
29444 // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
29445 this.intensity = power / (4 * Math.PI);
29448 this.distance = distance !== undefined ? distance : 0;
29449 this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
29451 this.shadow = new PointLightShadow();
29454 PointLight.prototype = Object.assign(Object.create(Light.prototype), {
29455 constructor: PointLight,
29456 isPointLight: true,
29457 copy: function copy(source) {
29458 Light.prototype.copy.call(this, source);
29459 this.distance = source.distance;
29460 this.decay = source.decay;
29461 this.shadow = source.shadow.clone();
29466 function OrthographicCamera(left, right, top, bottom, near, far) {
29468 this.type = 'OrthographicCamera';
29471 this.left = left !== undefined ? left : -1;
29472 this.right = right !== undefined ? right : 1;
29473 this.top = top !== undefined ? top : 1;
29474 this.bottom = bottom !== undefined ? bottom : -1;
29475 this.near = near !== undefined ? near : 0.1;
29476 this.far = far !== undefined ? far : 2000;
29477 this.updateProjectionMatrix();
29480 OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
29481 constructor: OrthographicCamera,
29482 isOrthographicCamera: true,
29483 copy: function copy(source, recursive) {
29484 Camera.prototype.copy.call(this, source, recursive);
29485 this.left = source.left;
29486 this.right = source.right;
29487 this.top = source.top;
29488 this.bottom = source.bottom;
29489 this.near = source.near;
29490 this.far = source.far;
29491 this.zoom = source.zoom;
29492 this.view = source.view === null ? null : Object.assign({}, source.view);
29495 setViewOffset: function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
29496 if (this.view === null) {
29508 this.view.enabled = true;
29509 this.view.fullWidth = fullWidth;
29510 this.view.fullHeight = fullHeight;
29511 this.view.offsetX = x;
29512 this.view.offsetY = y;
29513 this.view.width = width;
29514 this.view.height = height;
29515 this.updateProjectionMatrix();
29517 clearViewOffset: function clearViewOffset() {
29518 if (this.view !== null) {
29519 this.view.enabled = false;
29522 this.updateProjectionMatrix();
29524 updateProjectionMatrix: function updateProjectionMatrix() {
29525 var dx = (this.right - this.left) / (2 * this.zoom);
29526 var dy = (this.top - this.bottom) / (2 * this.zoom);
29527 var cx = (this.right + this.left) / 2;
29528 var cy = (this.top + this.bottom) / 2;
29529 var left = cx - dx;
29530 var right = cx + dx;
29532 var bottom = cy - dy;
29534 if (this.view !== null && this.view.enabled) {
29535 var scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
29536 var scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
29537 left += scaleW * this.view.offsetX;
29538 right = left + scaleW * this.view.width;
29539 top -= scaleH * this.view.offsetY;
29540 bottom = top - scaleH * this.view.height;
29543 this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
29544 this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
29546 toJSON: function toJSON(meta) {
29547 var data = Object3D.prototype.toJSON.call(this, meta);
29548 data.object.zoom = this.zoom;
29549 data.object.left = this.left;
29550 data.object.right = this.right;
29551 data.object.top = this.top;
29552 data.object.bottom = this.bottom;
29553 data.object.near = this.near;
29554 data.object.far = this.far;
29555 if (this.view !== null) data.object.view = Object.assign({}, this.view);
29560 function DirectionalLightShadow() {
29561 LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
29564 DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
29565 constructor: DirectionalLightShadow,
29566 isDirectionalLightShadow: true,
29567 updateMatrices: function updateMatrices(light) {
29568 LightShadow.prototype.updateMatrices.call(this, light);
29572 function DirectionalLight(color, intensity) {
29573 Light.call(this, color, intensity);
29574 this.type = 'DirectionalLight';
29575 this.position.copy(Object3D.DefaultUp);
29576 this.updateMatrix();
29577 this.target = new Object3D();
29578 this.shadow = new DirectionalLightShadow();
29581 DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
29582 constructor: DirectionalLight,
29583 isDirectionalLight: true,
29584 copy: function copy(source) {
29585 Light.prototype.copy.call(this, source);
29586 this.target = source.target.clone();
29587 this.shadow = source.shadow.clone();
29592 function AmbientLight(color, intensity) {
29593 Light.call(this, color, intensity);
29594 this.type = 'AmbientLight';
29597 AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
29598 constructor: AmbientLight,
29599 isAmbientLight: true
29602 function RectAreaLight(color, intensity, width, height) {
29603 Light.call(this, color, intensity);
29604 this.type = 'RectAreaLight';
29605 this.width = width !== undefined ? width : 10;
29606 this.height = height !== undefined ? height : 10;
29609 RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
29610 constructor: RectAreaLight,
29611 isRectAreaLight: true,
29612 copy: function copy(source) {
29613 Light.prototype.copy.call(this, source);
29614 this.width = source.width;
29615 this.height = source.height;
29618 toJSON: function toJSON(meta) {
29619 var data = Light.prototype.toJSON.call(this, meta);
29620 data.object.width = this.width;
29621 data.object.height = this.height;
29627 * Primary reference:
29628 * https://graphics.stanford.edu/papers/envmap/envmap.pdf
29630 * Secondary reference:
29631 * https://www.ppsloan.org/publications/StupidSH36.pdf
29633 // 3-band SH defined by 9 coefficients
29635 var SphericalHarmonics3 = /*#__PURE__*/function () {
29636 function SphericalHarmonics3() {
29637 Object.defineProperty(this, 'isSphericalHarmonics3', {
29640 this.coefficients = [];
29642 for (var i = 0; i < 9; i++) {
29643 this.coefficients.push(new Vector3());
29647 var _proto = SphericalHarmonics3.prototype;
29649 _proto.set = function set(coefficients) {
29650 for (var i = 0; i < 9; i++) {
29651 this.coefficients[i].copy(coefficients[i]);
29657 _proto.zero = function zero() {
29658 for (var i = 0; i < 9; i++) {
29659 this.coefficients[i].set(0, 0, 0);
29663 } // get the radiance in the direction of the normal
29664 // target is a Vector3
29667 _proto.getAt = function getAt(normal, target) {
29668 // normal is assumed to be unit length
29672 var coeff = this.coefficients; // band 0
29674 target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
29676 target.addScaledVector(coeff[1], 0.488603 * y);
29677 target.addScaledVector(coeff[2], 0.488603 * z);
29678 target.addScaledVector(coeff[3], 0.488603 * x); // band 2
29680 target.addScaledVector(coeff[4], 1.092548 * (x * y));
29681 target.addScaledVector(coeff[5], 1.092548 * (y * z));
29682 target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
29683 target.addScaledVector(coeff[7], 1.092548 * (x * z));
29684 target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
29686 } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
29687 // target is a Vector3
29688 // https://graphics.stanford.edu/papers/envmap/envmap.pdf
29691 _proto.getIrradianceAt = function getIrradianceAt(normal, target) {
29692 // normal is assumed to be unit length
29696 var coeff = this.coefficients; // band 0
29698 target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
29701 target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
29703 target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
29704 target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
29706 target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
29708 target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
29709 target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
29711 target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
29712 target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
29717 _proto.add = function add(sh) {
29718 for (var i = 0; i < 9; i++) {
29719 this.coefficients[i].add(sh.coefficients[i]);
29725 _proto.addScaledSH = function addScaledSH(sh, s) {
29726 for (var i = 0; i < 9; i++) {
29727 this.coefficients[i].addScaledVector(sh.coefficients[i], s);
29733 _proto.scale = function scale(s) {
29734 for (var i = 0; i < 9; i++) {
29735 this.coefficients[i].multiplyScalar(s);
29741 _proto.lerp = function lerp(sh, alpha) {
29742 for (var i = 0; i < 9; i++) {
29743 this.coefficients[i].lerp(sh.coefficients[i], alpha);
29749 _proto.equals = function equals(sh) {
29750 for (var i = 0; i < 9; i++) {
29751 if (!this.coefficients[i].equals(sh.coefficients[i])) {
29759 _proto.copy = function copy(sh) {
29760 return this.set(sh.coefficients);
29763 _proto.clone = function clone() {
29764 return new this.constructor().copy(this);
29767 _proto.fromArray = function fromArray(array, offset) {
29768 if (offset === void 0) {
29772 var coefficients = this.coefficients;
29774 for (var i = 0; i < 9; i++) {
29775 coefficients[i].fromArray(array, offset + i * 3);
29781 _proto.toArray = function toArray(array, offset) {
29782 if (array === void 0) {
29786 if (offset === void 0) {
29790 var coefficients = this.coefficients;
29792 for (var i = 0; i < 9; i++) {
29793 coefficients[i].toArray(array, offset + i * 3);
29797 } // evaluate the basis functions
29798 // shBasis is an Array[ 9 ]
29801 SphericalHarmonics3.getBasisAt = function getBasisAt(normal, shBasis) {
29802 // normal is assumed to be unit length
29805 z = normal.z; // band 0
29807 shBasis[0] = 0.282095; // band 1
29809 shBasis[1] = 0.488603 * y;
29810 shBasis[2] = 0.488603 * z;
29811 shBasis[3] = 0.488603 * x; // band 2
29813 shBasis[4] = 1.092548 * x * y;
29814 shBasis[5] = 1.092548 * y * z;
29815 shBasis[6] = 0.315392 * (3 * z * z - 1);
29816 shBasis[7] = 1.092548 * x * z;
29817 shBasis[8] = 0.546274 * (x * x - y * y);
29820 return SphericalHarmonics3;
29823 function LightProbe(sh, intensity) {
29824 Light.call(this, undefined, intensity);
29825 this.type = 'LightProbe';
29826 this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
29829 LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
29830 constructor: LightProbe,
29831 isLightProbe: true,
29832 copy: function copy(source) {
29833 Light.prototype.copy.call(this, source);
29834 this.sh.copy(source.sh);
29837 fromJSON: function fromJSON(json) {
29838 this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
29840 this.sh.fromArray(json.sh);
29843 toJSON: function toJSON(meta) {
29844 var data = Light.prototype.toJSON.call(this, meta);
29845 data.object.sh = this.sh.toArray();
29850 function MaterialLoader(manager) {
29851 Loader.call(this, manager);
29852 this.textures = {};
29855 MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
29856 constructor: MaterialLoader,
29857 load: function load(url, onLoad, onProgress, onError) {
29859 var loader = new FileLoader(scope.manager);
29860 loader.setPath(scope.path);
29861 loader.setRequestHeader(scope.requestHeader);
29862 loader.setWithCredentials(scope.withCredentials);
29863 loader.load(url, function (text) {
29865 onLoad(scope.parse(JSON.parse(text)));
29873 scope.manager.itemError(url);
29875 }, onProgress, onError);
29877 parse: function parse(json) {
29878 var textures = this.textures;
29880 function getTexture(name) {
29881 if (textures[name] === undefined) {
29882 console.warn('THREE.MaterialLoader: Undefined texture', name);
29885 return textures[name];
29888 var material = new Materials[json.type]();
29889 if (json.uuid !== undefined) material.uuid = json.uuid;
29890 if (json.name !== undefined) material.name = json.name;
29891 if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
29892 if (json.roughness !== undefined) material.roughness = json.roughness;
29893 if (json.metalness !== undefined) material.metalness = json.metalness;
29894 if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
29895 if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
29896 if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
29897 if (json.shininess !== undefined) material.shininess = json.shininess;
29898 if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
29899 if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
29900 if (json.fog !== undefined) material.fog = json.fog;
29901 if (json.flatShading !== undefined) material.flatShading = json.flatShading;
29902 if (json.blending !== undefined) material.blending = json.blending;
29903 if (json.combine !== undefined) material.combine = json.combine;
29904 if (json.side !== undefined) material.side = json.side;
29905 if (json.opacity !== undefined) material.opacity = json.opacity;
29906 if (json.transparent !== undefined) material.transparent = json.transparent;
29907 if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
29908 if (json.depthTest !== undefined) material.depthTest = json.depthTest;
29909 if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
29910 if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
29911 if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
29912 if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
29913 if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
29914 if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
29915 if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
29916 if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
29917 if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
29918 if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
29919 if (json.wireframe !== undefined) material.wireframe = json.wireframe;
29920 if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
29921 if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
29922 if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
29923 if (json.rotation !== undefined) material.rotation = json.rotation;
29924 if (json.linewidth !== 1) material.linewidth = json.linewidth;
29925 if (json.dashSize !== undefined) material.dashSize = json.dashSize;
29926 if (json.gapSize !== undefined) material.gapSize = json.gapSize;
29927 if (json.scale !== undefined) material.scale = json.scale;
29928 if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
29929 if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
29930 if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
29931 if (json.skinning !== undefined) material.skinning = json.skinning;
29932 if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
29933 if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
29934 if (json.dithering !== undefined) material.dithering = json.dithering;
29935 if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
29936 if (json.visible !== undefined) material.visible = json.visible;
29937 if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
29938 if (json.userData !== undefined) material.userData = json.userData;
29940 if (json.vertexColors !== undefined) {
29941 if (typeof json.vertexColors === 'number') {
29942 material.vertexColors = json.vertexColors > 0 ? true : false;
29944 material.vertexColors = json.vertexColors;
29946 } // Shader Material
29949 if (json.uniforms !== undefined) {
29950 for (var name in json.uniforms) {
29951 var uniform = json.uniforms[name];
29952 material.uniforms[name] = {};
29954 switch (uniform.type) {
29956 material.uniforms[name].value = getTexture(uniform.value);
29960 material.uniforms[name].value = new Color().setHex(uniform.value);
29964 material.uniforms[name].value = new Vector2().fromArray(uniform.value);
29968 material.uniforms[name].value = new Vector3().fromArray(uniform.value);
29972 material.uniforms[name].value = new Vector4().fromArray(uniform.value);
29976 material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
29980 material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
29984 material.uniforms[name].value = uniform.value;
29989 if (json.defines !== undefined) material.defines = json.defines;
29990 if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
29991 if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
29993 if (json.extensions !== undefined) {
29994 for (var key in json.extensions) {
29995 material.extensions[key] = json.extensions[key];
30000 if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
30001 // for PointsMaterial
30003 if (json.size !== undefined) material.size = json.size;
30004 if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
30006 if (json.map !== undefined) material.map = getTexture(json.map);
30007 if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
30008 if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
30009 if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
30010 if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
30011 if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
30012 if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
30014 if (json.normalScale !== undefined) {
30015 var normalScale = json.normalScale;
30017 if (Array.isArray(normalScale) === false) {
30018 // Blender exporter used to export a scalar. See #7459
30019 normalScale = [normalScale, normalScale];
30022 material.normalScale = new Vector2().fromArray(normalScale);
30025 if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
30026 if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
30027 if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
30028 if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
30029 if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
30030 if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
30031 if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
30032 if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
30033 if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
30034 if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
30035 if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
30036 if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
30037 if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
30038 if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
30039 if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
30040 if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
30041 if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
30042 if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
30043 if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
30044 if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
30045 if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
30046 if (json.transmission !== undefined) material.transmission = json.transmission;
30047 if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
30050 setTextures: function setTextures(value) {
30051 this.textures = value;
30056 var LoaderUtils = {
30057 decodeText: function decodeText(array) {
30058 if (typeof TextDecoder !== 'undefined') {
30059 return new TextDecoder().decode(array);
30060 } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
30061 // throws a "maximum call stack size exceeded" error for large arrays.
30066 for (var i = 0, il = array.length; i < il; i++) {
30067 // Implicitly assumes little-endian.
30068 s += String.fromCharCode(array[i]);
30072 // merges multi-byte utf-8 characters.
30073 return decodeURIComponent(escape(s));
30079 extractUrlBase: function extractUrlBase(url) {
30080 var index = url.lastIndexOf('/');
30081 if (index === -1) return './';
30082 return url.substr(0, index + 1);
30086 function InstancedBufferGeometry() {
30087 BufferGeometry.call(this);
30088 this.type = 'InstancedBufferGeometry';
30089 this.instanceCount = Infinity;
30092 InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
30093 constructor: InstancedBufferGeometry,
30094 isInstancedBufferGeometry: true,
30095 copy: function copy(source) {
30096 BufferGeometry.prototype.copy.call(this, source);
30097 this.instanceCount = source.instanceCount;
30100 clone: function clone() {
30101 return new this.constructor().copy(this);
30103 toJSON: function toJSON() {
30104 var data = BufferGeometry.prototype.toJSON.call(this);
30105 data.instanceCount = this.instanceCount;
30106 data.isInstancedBufferGeometry = true;
30111 function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
30112 if (typeof normalized === 'number') {
30113 meshPerAttribute = normalized;
30114 normalized = false;
30115 console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
30118 BufferAttribute.call(this, array, itemSize, normalized);
30119 this.meshPerAttribute = meshPerAttribute || 1;
30122 InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
30123 constructor: InstancedBufferAttribute,
30124 isInstancedBufferAttribute: true,
30125 copy: function copy(source) {
30126 BufferAttribute.prototype.copy.call(this, source);
30127 this.meshPerAttribute = source.meshPerAttribute;
30130 toJSON: function toJSON() {
30131 var data = BufferAttribute.prototype.toJSON.call(this);
30132 data.meshPerAttribute = this.meshPerAttribute;
30133 data.isInstancedBufferAttribute = true;
30138 function BufferGeometryLoader(manager) {
30139 Loader.call(this, manager);
30142 BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
30143 constructor: BufferGeometryLoader,
30144 load: function load(url, onLoad, onProgress, onError) {
30146 var loader = new FileLoader(scope.manager);
30147 loader.setPath(scope.path);
30148 loader.setRequestHeader(scope.requestHeader);
30149 loader.setWithCredentials(scope.withCredentials);
30150 loader.load(url, function (text) {
30152 onLoad(scope.parse(JSON.parse(text)));
30160 scope.manager.itemError(url);
30162 }, onProgress, onError);
30164 parse: function parse(json) {
30165 var interleavedBufferMap = {};
30166 var arrayBufferMap = {};
30168 function getInterleavedBuffer(json, uuid) {
30169 if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
30170 var interleavedBuffers = json.interleavedBuffers;
30171 var interleavedBuffer = interleavedBuffers[uuid];
30172 var buffer = getArrayBuffer(json, interleavedBuffer.buffer);
30173 var array = getTypedArray(interleavedBuffer.type, buffer);
30174 var ib = new InterleavedBuffer(array, interleavedBuffer.stride);
30175 ib.uuid = interleavedBuffer.uuid;
30176 interleavedBufferMap[uuid] = ib;
30180 function getArrayBuffer(json, uuid) {
30181 if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
30182 var arrayBuffers = json.arrayBuffers;
30183 var arrayBuffer = arrayBuffers[uuid];
30184 var ab = new Uint32Array(arrayBuffer).buffer;
30185 arrayBufferMap[uuid] = ab;
30189 var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
30190 var index = json.data.index;
30192 if (index !== undefined) {
30193 var typedArray = getTypedArray(index.type, index.array);
30194 geometry.setIndex(new BufferAttribute(typedArray, 1));
30197 var attributes = json.data.attributes;
30199 for (var key in attributes) {
30200 var attribute = attributes[key];
30201 var bufferAttribute = void 0;
30203 if (attribute.isInterleavedBufferAttribute) {
30204 var interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
30205 bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
30207 var _typedArray = getTypedArray(attribute.type, attribute.array);
30209 var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
30210 bufferAttribute = new bufferAttributeConstr(_typedArray, attribute.itemSize, attribute.normalized);
30213 if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
30214 geometry.setAttribute(key, bufferAttribute);
30217 var morphAttributes = json.data.morphAttributes;
30219 if (morphAttributes) {
30220 for (var _key in morphAttributes) {
30221 var attributeArray = morphAttributes[_key];
30224 for (var i = 0, il = attributeArray.length; i < il; i++) {
30225 var _attribute = attributeArray[i];
30227 var _bufferAttribute = void 0;
30229 if (_attribute.isInterleavedBufferAttribute) {
30230 var _interleavedBuffer = getInterleavedBuffer(json.data, _attribute.data);
30232 _bufferAttribute = new InterleavedBufferAttribute(_interleavedBuffer, _attribute.itemSize, _attribute.offset, _attribute.normalized);
30234 var _typedArray2 = getTypedArray(_attribute.type, _attribute.array);
30236 _bufferAttribute = new BufferAttribute(_typedArray2, _attribute.itemSize, _attribute.normalized);
30239 if (_attribute.name !== undefined) _bufferAttribute.name = _attribute.name;
30240 array.push(_bufferAttribute);
30243 geometry.morphAttributes[_key] = array;
30247 var morphTargetsRelative = json.data.morphTargetsRelative;
30249 if (morphTargetsRelative) {
30250 geometry.morphTargetsRelative = true;
30253 var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
30255 if (groups !== undefined) {
30256 for (var _i = 0, n = groups.length; _i !== n; ++_i) {
30257 var group = groups[_i];
30258 geometry.addGroup(group.start, group.count, group.materialIndex);
30262 var boundingSphere = json.data.boundingSphere;
30264 if (boundingSphere !== undefined) {
30265 var center = new Vector3();
30267 if (boundingSphere.center !== undefined) {
30268 center.fromArray(boundingSphere.center);
30271 geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
30274 if (json.name) geometry.name = json.name;
30275 if (json.userData) geometry.userData = json.userData;
30280 var ObjectLoader = /*#__PURE__*/function (_Loader) {
30281 _inheritsLoose(ObjectLoader, _Loader);
30283 function ObjectLoader(manager) {
30284 return _Loader.call(this, manager) || this;
30287 var _proto = ObjectLoader.prototype;
30289 _proto.load = function load(url, onLoad, onProgress, onError) {
30291 var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
30292 this.resourcePath = this.resourcePath || path;
30293 var loader = new FileLoader(this.manager);
30294 loader.setPath(this.path);
30295 loader.setRequestHeader(this.requestHeader);
30296 loader.setWithCredentials(this.withCredentials);
30297 loader.load(url, function (text) {
30301 json = JSON.parse(text);
30303 if (onError !== undefined) onError(error);
30304 console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
30308 var metadata = json.metadata;
30310 if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
30311 console.error('THREE.ObjectLoader: Can\'t load ' + url);
30315 scope.parse(json, onLoad);
30316 }, onProgress, onError);
30319 _proto.parse = function parse(json, onLoad) {
30320 var animations = this.parseAnimations(json.animations);
30321 var shapes = this.parseShapes(json.shapes);
30322 var geometries = this.parseGeometries(json.geometries, shapes);
30323 var images = this.parseImages(json.images, function () {
30324 if (onLoad !== undefined) onLoad(object);
30326 var textures = this.parseTextures(json.textures, images);
30327 var materials = this.parseMaterials(json.materials, textures);
30328 var object = this.parseObject(json.object, geometries, materials, animations);
30329 var skeletons = this.parseSkeletons(json.skeletons, object);
30330 this.bindSkeletons(object, skeletons); //
30332 if (onLoad !== undefined) {
30333 var hasImages = false;
30335 for (var uuid in images) {
30336 if (images[uuid] instanceof HTMLImageElement) {
30342 if (hasImages === false) onLoad(object);
30348 _proto.parseShapes = function parseShapes(json) {
30351 if (json !== undefined) {
30352 for (var i = 0, l = json.length; i < l; i++) {
30353 var shape = new Shape().fromJSON(json[i]);
30354 shapes[shape.uuid] = shape;
30361 _proto.parseSkeletons = function parseSkeletons(json, object) {
30362 var skeletons = {};
30363 var bones = {}; // generate bone lookup table
30365 object.traverse(function (child) {
30366 if (child.isBone) bones[child.uuid] = child;
30367 }); // create skeletons
30369 if (json !== undefined) {
30370 for (var i = 0, l = json.length; i < l; i++) {
30371 var skeleton = new Skeleton().fromJSON(json[i], bones);
30372 skeletons[skeleton.uuid] = skeleton;
30379 _proto.parseGeometries = function parseGeometries(json, shapes) {
30380 var geometries = {};
30381 var geometryShapes;
30383 if (json !== undefined) {
30384 var bufferGeometryLoader = new BufferGeometryLoader();
30386 for (var i = 0, l = json.length; i < l; i++) {
30387 var geometry = void 0;
30388 var data = json[i];
30390 switch (data.type) {
30391 case 'PlaneGeometry':
30392 case 'PlaneBufferGeometry':
30393 geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
30396 case 'BoxGeometry':
30397 case 'BoxBufferGeometry':
30398 case 'CubeGeometry':
30399 // backwards compatible
30400 geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
30403 case 'CircleGeometry':
30404 case 'CircleBufferGeometry':
30405 geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
30408 case 'CylinderGeometry':
30409 case 'CylinderBufferGeometry':
30410 geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
30413 case 'ConeGeometry':
30414 case 'ConeBufferGeometry':
30415 geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
30418 case 'SphereGeometry':
30419 case 'SphereBufferGeometry':
30420 geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
30423 case 'DodecahedronGeometry':
30424 case 'DodecahedronBufferGeometry':
30425 case 'IcosahedronGeometry':
30426 case 'IcosahedronBufferGeometry':
30427 case 'OctahedronGeometry':
30428 case 'OctahedronBufferGeometry':
30429 case 'TetrahedronGeometry':
30430 case 'TetrahedronBufferGeometry':
30431 geometry = new Geometries[data.type](data.radius, data.detail);
30434 case 'RingGeometry':
30435 case 'RingBufferGeometry':
30436 geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
30439 case 'TorusGeometry':
30440 case 'TorusBufferGeometry':
30441 geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
30444 case 'TorusKnotGeometry':
30445 case 'TorusKnotBufferGeometry':
30446 geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
30449 case 'TubeGeometry':
30450 case 'TubeBufferGeometry':
30451 // This only works for built-in curves (e.g. CatmullRomCurve3).
30452 // User defined curves or instances of CurvePath will not be deserialized.
30453 geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
30456 case 'LatheGeometry':
30457 case 'LatheBufferGeometry':
30458 geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
30461 case 'PolyhedronGeometry':
30462 case 'PolyhedronBufferGeometry':
30463 geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
30466 case 'ShapeGeometry':
30467 case 'ShapeBufferGeometry':
30468 geometryShapes = [];
30470 for (var j = 0, jl = data.shapes.length; j < jl; j++) {
30471 var shape = shapes[data.shapes[j]];
30472 geometryShapes.push(shape);
30475 geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
30478 case 'ExtrudeGeometry':
30479 case 'ExtrudeBufferGeometry':
30480 geometryShapes = [];
30482 for (var _j = 0, _jl = data.shapes.length; _j < _jl; _j++) {
30483 var _shape = shapes[data.shapes[_j]];
30484 geometryShapes.push(_shape);
30487 var extrudePath = data.options.extrudePath;
30489 if (extrudePath !== undefined) {
30490 data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
30493 geometry = new Geometries[data.type](geometryShapes, data.options);
30496 case 'BufferGeometry':
30497 case 'InstancedBufferGeometry':
30498 geometry = bufferGeometryLoader.parse(data);
30502 console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
30506 console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
30510 geometry.uuid = data.uuid;
30511 if (data.name !== undefined) geometry.name = data.name;
30512 if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
30513 geometries[data.uuid] = geometry;
30520 _proto.parseMaterials = function parseMaterials(json, textures) {
30521 var cache = {}; // MultiMaterial
30523 var materials = {};
30525 if (json !== undefined) {
30526 var loader = new MaterialLoader();
30527 loader.setTextures(textures);
30529 for (var i = 0, l = json.length; i < l; i++) {
30530 var data = json[i];
30532 if (data.type === 'MultiMaterial') {
30536 for (var j = 0; j < data.materials.length; j++) {
30537 var material = data.materials[j];
30539 if (cache[material.uuid] === undefined) {
30540 cache[material.uuid] = loader.parse(material);
30543 array.push(cache[material.uuid]);
30546 materials[data.uuid] = array;
30548 if (cache[data.uuid] === undefined) {
30549 cache[data.uuid] = loader.parse(data);
30552 materials[data.uuid] = cache[data.uuid];
30560 _proto.parseAnimations = function parseAnimations(json) {
30561 var animations = {};
30563 if (json !== undefined) {
30564 for (var i = 0; i < json.length; i++) {
30565 var data = json[i];
30566 var clip = AnimationClip.parse(data);
30567 animations[clip.uuid] = clip;
30574 _proto.parseImages = function parseImages(json, onLoad) {
30579 function loadImage(url) {
30580 scope.manager.itemStart(url);
30581 return loader.load(url, function () {
30582 scope.manager.itemEnd(url);
30583 }, undefined, function () {
30584 scope.manager.itemError(url);
30585 scope.manager.itemEnd(url);
30589 function deserializeImage(image) {
30590 if (typeof image === 'string') {
30592 var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
30593 return loadImage(path);
30597 data: getTypedArray(image.type, image.data),
30598 width: image.width,
30599 height: image.height
30607 if (json !== undefined && json.length > 0) {
30608 var manager = new LoadingManager(onLoad);
30609 loader = new ImageLoader(manager);
30610 loader.setCrossOrigin(this.crossOrigin);
30612 for (var i = 0, il = json.length; i < il; i++) {
30613 var image = json[i];
30614 var url = image.url;
30616 if (Array.isArray(url)) {
30617 // load array of images e.g CubeTexture
30618 images[image.uuid] = [];
30620 for (var j = 0, jl = url.length; j < jl; j++) {
30621 var currentUrl = url[j];
30622 var deserializedImage = deserializeImage(currentUrl);
30624 if (deserializedImage !== null) {
30625 if (deserializedImage instanceof HTMLImageElement) {
30626 images[image.uuid].push(deserializedImage);
30628 // special case: handle array of data textures for cube textures
30629 images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
30634 // load single image
30635 var _deserializedImage = deserializeImage(image.url);
30637 if (_deserializedImage !== null) {
30638 images[image.uuid] = _deserializedImage;
30647 _proto.parseTextures = function parseTextures(json, images) {
30648 function parseConstant(value, type) {
30649 if (typeof value === 'number') return value;
30650 console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
30651 return type[value];
30656 if (json !== undefined) {
30657 for (var i = 0, l = json.length; i < l; i++) {
30658 var data = json[i];
30660 if (data.image === undefined) {
30661 console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
30664 if (images[data.image] === undefined) {
30665 console.warn('THREE.ObjectLoader: Undefined image', data.image);
30668 var texture = void 0;
30669 var image = images[data.image];
30671 if (Array.isArray(image)) {
30672 texture = new CubeTexture(image);
30673 if (image.length === 6) texture.needsUpdate = true;
30675 if (image && image.data) {
30676 texture = new DataTexture(image.data, image.width, image.height);
30678 texture = new Texture(image);
30681 if (image) texture.needsUpdate = true; // textures can have undefined image data
30684 texture.uuid = data.uuid;
30685 if (data.name !== undefined) texture.name = data.name;
30686 if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
30687 if (data.offset !== undefined) texture.offset.fromArray(data.offset);
30688 if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
30689 if (data.center !== undefined) texture.center.fromArray(data.center);
30690 if (data.rotation !== undefined) texture.rotation = data.rotation;
30692 if (data.wrap !== undefined) {
30693 texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
30694 texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
30697 if (data.format !== undefined) texture.format = data.format;
30698 if (data.type !== undefined) texture.type = data.type;
30699 if (data.encoding !== undefined) texture.encoding = data.encoding;
30700 if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
30701 if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
30702 if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
30703 if (data.flipY !== undefined) texture.flipY = data.flipY;
30704 if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
30705 if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
30706 textures[data.uuid] = texture;
30713 _proto.parseObject = function parseObject(data, geometries, materials, animations) {
30716 function getGeometry(name) {
30717 if (geometries[name] === undefined) {
30718 console.warn('THREE.ObjectLoader: Undefined geometry', name);
30721 return geometries[name];
30724 function getMaterial(name) {
30725 if (name === undefined) return undefined;
30727 if (Array.isArray(name)) {
30730 for (var i = 0, l = name.length; i < l; i++) {
30731 var uuid = name[i];
30733 if (materials[uuid] === undefined) {
30734 console.warn('THREE.ObjectLoader: Undefined material', uuid);
30737 array.push(materials[uuid]);
30743 if (materials[name] === undefined) {
30744 console.warn('THREE.ObjectLoader: Undefined material', name);
30747 return materials[name];
30750 var geometry, material;
30752 switch (data.type) {
30754 object = new Scene();
30756 if (data.background !== undefined) {
30757 if (Number.isInteger(data.background)) {
30758 object.background = new Color(data.background);
30762 if (data.fog !== undefined) {
30763 if (data.fog.type === 'Fog') {
30764 object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
30765 } else if (data.fog.type === 'FogExp2') {
30766 object.fog = new FogExp2(data.fog.color, data.fog.density);
30772 case 'PerspectiveCamera':
30773 object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
30774 if (data.focus !== undefined) object.focus = data.focus;
30775 if (data.zoom !== undefined) object.zoom = data.zoom;
30776 if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
30777 if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
30778 if (data.view !== undefined) object.view = Object.assign({}, data.view);
30781 case 'OrthographicCamera':
30782 object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
30783 if (data.zoom !== undefined) object.zoom = data.zoom;
30784 if (data.view !== undefined) object.view = Object.assign({}, data.view);
30787 case 'AmbientLight':
30788 object = new AmbientLight(data.color, data.intensity);
30791 case 'DirectionalLight':
30792 object = new DirectionalLight(data.color, data.intensity);
30796 object = new PointLight(data.color, data.intensity, data.distance, data.decay);
30799 case 'RectAreaLight':
30800 object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
30804 object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
30807 case 'HemisphereLight':
30808 object = new HemisphereLight(data.color, data.groundColor, data.intensity);
30812 object = new LightProbe().fromJSON(data);
30815 case 'SkinnedMesh':
30816 geometry = getGeometry(data.geometry);
30817 material = getMaterial(data.material);
30818 object = new SkinnedMesh(geometry, material);
30819 if (data.bindMode !== undefined) object.bindMode = data.bindMode;
30820 if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
30821 if (data.skeleton !== undefined) object.skeleton = data.skeleton;
30825 geometry = getGeometry(data.geometry);
30826 material = getMaterial(data.material);
30827 object = new Mesh(geometry, material);
30830 case 'InstancedMesh':
30831 geometry = getGeometry(data.geometry);
30832 material = getMaterial(data.material);
30833 var count = data.count;
30834 var instanceMatrix = data.instanceMatrix;
30835 object = new InstancedMesh(geometry, material, count);
30836 object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
30840 object = new LOD();
30844 object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
30848 object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
30851 case 'LineSegments':
30852 object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
30857 object = new Points(getGeometry(data.geometry), getMaterial(data.material));
30861 object = new Sprite(getMaterial(data.material));
30865 object = new Group();
30869 object = new Bone();
30873 object = new Object3D();
30876 object.uuid = data.uuid;
30877 if (data.name !== undefined) object.name = data.name;
30879 if (data.matrix !== undefined) {
30880 object.matrix.fromArray(data.matrix);
30881 if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
30882 if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
30884 if (data.position !== undefined) object.position.fromArray(data.position);
30885 if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
30886 if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
30887 if (data.scale !== undefined) object.scale.fromArray(data.scale);
30890 if (data.castShadow !== undefined) object.castShadow = data.castShadow;
30891 if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
30894 if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
30895 if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
30896 if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
30897 if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
30898 if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
30901 if (data.visible !== undefined) object.visible = data.visible;
30902 if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
30903 if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
30904 if (data.userData !== undefined) object.userData = data.userData;
30905 if (data.layers !== undefined) object.layers.mask = data.layers;
30907 if (data.children !== undefined) {
30908 var children = data.children;
30910 for (var i = 0; i < children.length; i++) {
30911 object.add(this.parseObject(children[i], geometries, materials, animations));
30915 if (data.animations !== undefined) {
30916 var objectAnimations = data.animations;
30918 for (var _i = 0; _i < objectAnimations.length; _i++) {
30919 var uuid = objectAnimations[_i];
30920 object.animations.push(animations[uuid]);
30924 if (data.type === 'LOD') {
30925 if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
30926 var levels = data.levels;
30928 for (var l = 0; l < levels.length; l++) {
30929 var level = levels[l];
30930 var child = object.getObjectByProperty('uuid', level.object);
30932 if (child !== undefined) {
30933 object.addLevel(child, level.distance);
30941 _proto.bindSkeletons = function bindSkeletons(object, skeletons) {
30942 if (Object.keys(skeletons).length === 0) return;
30943 object.traverse(function (child) {
30944 if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
30945 var skeleton = skeletons[child.skeleton];
30947 if (skeleton === undefined) {
30948 console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
30950 child.bind(skeleton, child.bindMatrix);
30958 _proto.setTexturePath = function setTexturePath(value) {
30959 console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
30960 return this.setResourcePath(value);
30963 return ObjectLoader;
30966 var TEXTURE_MAPPING = {
30967 UVMapping: UVMapping,
30968 CubeReflectionMapping: CubeReflectionMapping,
30969 CubeRefractionMapping: CubeRefractionMapping,
30970 EquirectangularReflectionMapping: EquirectangularReflectionMapping,
30971 EquirectangularRefractionMapping: EquirectangularRefractionMapping,
30972 CubeUVReflectionMapping: CubeUVReflectionMapping,
30973 CubeUVRefractionMapping: CubeUVRefractionMapping
30975 var TEXTURE_WRAPPING = {
30976 RepeatWrapping: RepeatWrapping,
30977 ClampToEdgeWrapping: ClampToEdgeWrapping,
30978 MirroredRepeatWrapping: MirroredRepeatWrapping
30980 var TEXTURE_FILTER = {
30981 NearestFilter: NearestFilter,
30982 NearestMipmapNearestFilter: NearestMipmapNearestFilter,
30983 NearestMipmapLinearFilter: NearestMipmapLinearFilter,
30984 LinearFilter: LinearFilter,
30985 LinearMipmapNearestFilter: LinearMipmapNearestFilter,
30986 LinearMipmapLinearFilter: LinearMipmapLinearFilter
30989 function ImageBitmapLoader(manager) {
30990 if (typeof createImageBitmap === 'undefined') {
30991 console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
30994 if (typeof fetch === 'undefined') {
30995 console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
30998 Loader.call(this, manager);
31000 premultiplyAlpha: 'none'
31004 ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
31005 constructor: ImageBitmapLoader,
31006 isImageBitmapLoader: true,
31007 setOptions: function setOptions(options) {
31008 this.options = options;
31011 load: function load(url, onLoad, onProgress, onError) {
31012 if (url === undefined) url = '';
31013 if (this.path !== undefined) url = this.path + url;
31014 url = this.manager.resolveURL(url);
31016 var cached = Cache.get(url);
31018 if (cached !== undefined) {
31019 scope.manager.itemStart(url);
31020 setTimeout(function () {
31021 if (onLoad) onLoad(cached);
31022 scope.manager.itemEnd(url);
31027 var fetchOptions = {};
31028 fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
31029 fetch(url, fetchOptions).then(function (res) {
31031 }).then(function (blob) {
31032 return createImageBitmap(blob, scope.options);
31033 }).then(function (imageBitmap) {
31034 Cache.add(url, imageBitmap);
31035 if (onLoad) onLoad(imageBitmap);
31036 scope.manager.itemEnd(url);
31037 }).catch(function (e) {
31038 if (onError) onError(e);
31039 scope.manager.itemError(url);
31040 scope.manager.itemEnd(url);
31042 scope.manager.itemStart(url);
31046 function ShapePath() {
31047 this.type = 'ShapePath';
31048 this.color = new Color();
31049 this.subPaths = [];
31050 this.currentPath = null;
31053 Object.assign(ShapePath.prototype, {
31054 moveTo: function moveTo(x, y) {
31055 this.currentPath = new Path();
31056 this.subPaths.push(this.currentPath);
31057 this.currentPath.moveTo(x, y);
31060 lineTo: function lineTo(x, y) {
31061 this.currentPath.lineTo(x, y);
31064 quadraticCurveTo: function quadraticCurveTo(aCPx, aCPy, aX, aY) {
31065 this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
31068 bezierCurveTo: function bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
31069 this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
31072 splineThru: function splineThru(pts) {
31073 this.currentPath.splineThru(pts);
31076 toShapes: function toShapes(isCCW, noHoles) {
31077 function toShapesNoHoles(inSubpaths) {
31080 for (var i = 0, l = inSubpaths.length; i < l; i++) {
31081 var _tmpPath = inSubpaths[i];
31083 var _tmpShape = new Shape();
31085 _tmpShape.curves = _tmpPath.curves;
31086 shapes.push(_tmpShape);
31092 function isPointInsidePolygon(inPt, inPolygon) {
31093 var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
31094 // toggling of inside/outside at every single! intersection point of an edge
31095 // with the horizontal line through inPt, left of inPt
31096 // not counting lowerY endpoints of edges and whole edges on that line
31098 var inside = false;
31100 for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
31101 var edgeLowPt = inPolygon[p];
31102 var edgeHighPt = inPolygon[q];
31103 var edgeDx = edgeHighPt.x - edgeLowPt.x;
31104 var edgeDy = edgeHighPt.y - edgeLowPt.y;
31106 if (Math.abs(edgeDy) > Number.EPSILON) {
31109 edgeLowPt = inPolygon[q];
31111 edgeHighPt = inPolygon[p];
31115 if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
31117 if (inPt.y === edgeLowPt.y) {
31118 if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
31119 // continue; // no intersection or edgeLowPt => doesn't count !!!
31121 var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
31122 if (perpEdge === 0) return true; // inPt is on contour ?
31124 if (perpEdge < 0) continue;
31125 inside = !inside; // true intersection left of inPt
31128 // parallel or collinear
31129 if (inPt.y !== edgeLowPt.y) continue; // parallel
31130 // edge lies on the same horizontal line as inPt
31132 if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
31140 var isClockWise = ShapeUtils.isClockWise;
31141 var subPaths = this.subPaths;
31142 if (subPaths.length === 0) return [];
31143 if (noHoles === true) return toShapesNoHoles(subPaths);
31144 var solid, tmpPath, tmpShape;
31147 if (subPaths.length === 1) {
31148 tmpPath = subPaths[0];
31149 tmpShape = new Shape();
31150 tmpShape.curves = tmpPath.curves;
31151 shapes.push(tmpShape);
31155 var holesFirst = !isClockWise(subPaths[0].getPoints());
31156 holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
31158 var betterShapeHoles = [];
31159 var newShapes = [];
31160 var newShapeHoles = [];
31163 newShapes[mainIdx] = undefined;
31164 newShapeHoles[mainIdx] = [];
31166 for (var i = 0, l = subPaths.length; i < l; i++) {
31167 tmpPath = subPaths[i];
31168 tmpPoints = tmpPath.getPoints();
31169 solid = isClockWise(tmpPoints);
31170 solid = isCCW ? !solid : solid;
31173 if (!holesFirst && newShapes[mainIdx]) mainIdx++;
31174 newShapes[mainIdx] = {
31178 newShapes[mainIdx].s.curves = tmpPath.curves;
31179 if (holesFirst) mainIdx++;
31180 newShapeHoles[mainIdx] = []; //console.log('cw', i);
31182 newShapeHoles[mainIdx].push({
31185 }); //console.log('ccw', i);
31187 } // only Holes? -> probably all Shapes with wrong orientation
31190 if (!newShapes[0]) return toShapesNoHoles(subPaths);
31192 if (newShapes.length > 1) {
31193 var ambiguous = false;
31196 for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
31197 betterShapeHoles[sIdx] = [];
31200 for (var _sIdx = 0, _sLen = newShapes.length; _sIdx < _sLen; _sIdx++) {
31201 var sho = newShapeHoles[_sIdx];
31203 for (var hIdx = 0; hIdx < sho.length; hIdx++) {
31204 var ho = sho[hIdx];
31205 var hole_unassigned = true;
31207 for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
31208 if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
31209 if (_sIdx !== s2Idx) toChange.push({
31215 if (hole_unassigned) {
31216 hole_unassigned = false;
31217 betterShapeHoles[s2Idx].push(ho);
31224 if (hole_unassigned) {
31225 betterShapeHoles[_sIdx].push(ho);
31228 } // console.log("ambiguous: ", ambiguous);
31231 if (toChange.length > 0) {
31232 // console.log("to change: ", toChange);
31233 if (!ambiguous) newShapeHoles = betterShapeHoles;
31239 for (var _i = 0, il = newShapes.length; _i < il; _i++) {
31240 tmpShape = newShapes[_i].s;
31241 shapes.push(tmpShape);
31242 tmpHoles = newShapeHoles[_i];
31244 for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
31245 tmpShape.holes.push(tmpHoles[j].h);
31247 } //console.log("shape", shapes);
31254 function Font(data) {
31255 this.type = 'Font';
31259 Object.assign(Font.prototype, {
31261 generateShapes: function generateShapes(text, size) {
31262 if (size === void 0) {
31267 var paths = createPaths(text, size, this.data);
31269 for (var p = 0, pl = paths.length; p < pl; p++) {
31270 Array.prototype.push.apply(shapes, paths[p].toShapes());
31277 function createPaths(text, size, data) {
31278 var chars = Array.from ? Array.from(text) : String(text).split(''); // workaround for IE11, see #13988
31280 var scale = size / data.resolution;
31281 var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
31286 for (var i = 0; i < chars.length; i++) {
31287 var char = chars[i];
31289 if (char === '\n') {
31291 offsetY -= line_height;
31293 var ret = createPath(char, scale, offsetX, offsetY, data);
31294 offsetX += ret.offsetX;
31295 paths.push(ret.path);
31302 function createPath(char, scale, offsetX, offsetY, data) {
31303 var glyph = data.glyphs[char] || data.glyphs['?'];
31306 console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
31310 var path = new ShapePath();
31311 var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
31314 var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
31316 for (var i = 0, l = outline.length; i < l;) {
31317 var action = outline[i++];
31322 x = outline[i++] * scale + offsetX;
31323 y = outline[i++] * scale + offsetY;
31329 x = outline[i++] * scale + offsetX;
31330 y = outline[i++] * scale + offsetY;
31335 // quadraticCurveTo
31336 cpx = outline[i++] * scale + offsetX;
31337 cpy = outline[i++] * scale + offsetY;
31338 cpx1 = outline[i++] * scale + offsetX;
31339 cpy1 = outline[i++] * scale + offsetY;
31340 path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
31345 cpx = outline[i++] * scale + offsetX;
31346 cpy = outline[i++] * scale + offsetY;
31347 cpx1 = outline[i++] * scale + offsetX;
31348 cpy1 = outline[i++] * scale + offsetY;
31349 cpx2 = outline[i++] * scale + offsetX;
31350 cpy2 = outline[i++] * scale + offsetY;
31351 path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
31358 offsetX: glyph.ha * scale,
31363 function FontLoader(manager) {
31364 Loader.call(this, manager);
31367 FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
31368 constructor: FontLoader,
31369 load: function load(url, onLoad, onProgress, onError) {
31371 var loader = new FileLoader(this.manager);
31372 loader.setPath(this.path);
31373 loader.setRequestHeader(this.requestHeader);
31374 loader.setWithCredentials(scope.withCredentials);
31375 loader.load(url, function (text) {
31379 json = JSON.parse(text);
31381 console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
31382 json = JSON.parse(text.substring(65, text.length - 2));
31385 var font = scope.parse(json);
31386 if (onLoad) onLoad(font);
31387 }, onProgress, onError);
31389 parse: function parse(json) {
31390 return new Font(json);
31396 var AudioContext = {
31397 getContext: function getContext() {
31398 if (_context === undefined) {
31399 _context = new (window.AudioContext || window.webkitAudioContext)();
31404 setContext: function setContext(value) {
31409 function AudioLoader(manager) {
31410 Loader.call(this, manager);
31413 AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
31414 constructor: AudioLoader,
31415 load: function load(url, onLoad, onProgress, onError) {
31417 var loader = new FileLoader(scope.manager);
31418 loader.setResponseType('arraybuffer');
31419 loader.setPath(scope.path);
31420 loader.setRequestHeader(scope.requestHeader);
31421 loader.setWithCredentials(scope.withCredentials);
31422 loader.load(url, function (buffer) {
31424 // Create a copy of the buffer. The `decodeAudioData` method
31425 // detaches the buffer when complete, preventing reuse.
31426 var bufferCopy = buffer.slice(0);
31427 var context = AudioContext.getContext();
31428 context.decodeAudioData(bufferCopy, function (audioBuffer) {
31429 onLoad(audioBuffer);
31438 scope.manager.itemError(url);
31440 }, onProgress, onError);
31444 function HemisphereLightProbe(skyColor, groundColor, intensity) {
31445 LightProbe.call(this, undefined, intensity);
31446 var color1 = new Color().set(skyColor);
31447 var color2 = new Color().set(groundColor);
31448 var sky = new Vector3(color1.r, color1.g, color1.b);
31449 var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
31451 var c0 = Math.sqrt(Math.PI);
31452 var c1 = c0 * Math.sqrt(0.75);
31453 this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
31454 this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
31457 HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
31458 constructor: HemisphereLightProbe,
31459 isHemisphereLightProbe: true,
31460 copy: function copy(source) {
31461 // modifying colors not currently supported
31462 LightProbe.prototype.copy.call(this, source);
31465 toJSON: function toJSON(meta) {
31466 var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
31472 function AmbientLightProbe(color, intensity) {
31473 LightProbe.call(this, undefined, intensity);
31474 var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
31476 this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
31479 AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
31480 constructor: AmbientLightProbe,
31481 isAmbientLightProbe: true,
31482 copy: function copy(source) {
31483 // modifying color not currently supported
31484 LightProbe.prototype.copy.call(this, source);
31487 toJSON: function toJSON(meta) {
31488 var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
31494 var _eyeRight = new Matrix4();
31496 var _eyeLeft = new Matrix4();
31498 function StereoCamera() {
31499 this.type = 'StereoCamera';
31501 this.eyeSep = 0.064;
31502 this.cameraL = new PerspectiveCamera();
31503 this.cameraL.layers.enable(1);
31504 this.cameraL.matrixAutoUpdate = false;
31505 this.cameraR = new PerspectiveCamera();
31506 this.cameraR.layers.enable(2);
31507 this.cameraR.matrixAutoUpdate = false;
31519 Object.assign(StereoCamera.prototype, {
31520 update: function update(camera) {
31521 var cache = this._cache;
31522 var 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;
31525 cache.focus = camera.focus;
31526 cache.fov = camera.fov;
31527 cache.aspect = camera.aspect * this.aspect;
31528 cache.near = camera.near;
31529 cache.far = camera.far;
31530 cache.zoom = camera.zoom;
31531 cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
31532 // http://paulbourke.net/stereographics/stereorender/
31534 var projectionMatrix = camera.projectionMatrix.clone();
31535 var eyeSepHalf = cache.eyeSep / 2;
31536 var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
31537 var ymax = cache.near * Math.tan(MathUtils.DEG2RAD * cache.fov * 0.5) / cache.zoom;
31538 var xmin, xmax; // translate xOffset
31540 _eyeLeft.elements[12] = -eyeSepHalf;
31541 _eyeRight.elements[12] = eyeSepHalf; // for left eye
31543 xmin = -ymax * cache.aspect + eyeSepOnProjection;
31544 xmax = ymax * cache.aspect + eyeSepOnProjection;
31545 projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
31546 projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
31547 this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
31549 xmin = -ymax * cache.aspect - eyeSepOnProjection;
31550 xmax = ymax * cache.aspect - eyeSepOnProjection;
31551 projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
31552 projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
31553 this.cameraR.projectionMatrix.copy(projectionMatrix);
31556 this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
31557 this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
31561 var Clock = /*#__PURE__*/function () {
31562 function Clock(autoStart) {
31563 this.autoStart = autoStart !== undefined ? autoStart : true;
31564 this.startTime = 0;
31566 this.elapsedTime = 0;
31567 this.running = false;
31570 var _proto = Clock.prototype;
31572 _proto.start = function start() {
31573 this.startTime = now();
31574 this.oldTime = this.startTime;
31575 this.elapsedTime = 0;
31576 this.running = true;
31579 _proto.stop = function stop() {
31580 this.getElapsedTime();
31581 this.running = false;
31582 this.autoStart = false;
31585 _proto.getElapsedTime = function getElapsedTime() {
31587 return this.elapsedTime;
31590 _proto.getDelta = function getDelta() {
31593 if (this.autoStart && !this.running) {
31598 if (this.running) {
31599 var newTime = now();
31600 diff = (newTime - this.oldTime) / 1000;
31601 this.oldTime = newTime;
31602 this.elapsedTime += diff;
31612 return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
31615 var _position$2 = /*@__PURE__*/new Vector3();
31617 var _quaternion$3 = /*@__PURE__*/new Quaternion();
31619 var _scale$1 = /*@__PURE__*/new Vector3();
31621 var _orientation = /*@__PURE__*/new Vector3();
31623 var AudioListener = /*#__PURE__*/function (_Object3D) {
31624 _inheritsLoose(AudioListener, _Object3D);
31626 function AudioListener() {
31629 _this = _Object3D.call(this) || this;
31630 _this.type = 'AudioListener';
31631 _this.context = AudioContext.getContext();
31632 _this.gain = _this.context.createGain();
31634 _this.gain.connect(_this.context.destination);
31636 _this.filter = null;
31637 _this.timeDelta = 0; // private
31639 _this._clock = new Clock();
31643 var _proto = AudioListener.prototype;
31645 _proto.getInput = function getInput() {
31649 _proto.removeFilter = function removeFilter() {
31650 if (this.filter !== null) {
31651 this.gain.disconnect(this.filter);
31652 this.filter.disconnect(this.context.destination);
31653 this.gain.connect(this.context.destination);
31654 this.filter = null;
31660 _proto.getFilter = function getFilter() {
31661 return this.filter;
31664 _proto.setFilter = function setFilter(value) {
31665 if (this.filter !== null) {
31666 this.gain.disconnect(this.filter);
31667 this.filter.disconnect(this.context.destination);
31669 this.gain.disconnect(this.context.destination);
31672 this.filter = value;
31673 this.gain.connect(this.filter);
31674 this.filter.connect(this.context.destination);
31678 _proto.getMasterVolume = function getMasterVolume() {
31679 return this.gain.gain.value;
31682 _proto.setMasterVolume = function setMasterVolume(value) {
31683 this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
31687 _proto.updateMatrixWorld = function updateMatrixWorld(force) {
31688 _Object3D.prototype.updateMatrixWorld.call(this, force);
31690 var listener = this.context.listener;
31692 this.timeDelta = this._clock.getDelta();
31693 this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
31695 _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
31697 if (listener.positionX) {
31698 // code path for Chrome (see #14393)
31699 var endTime = this.context.currentTime + this.timeDelta;
31700 listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
31701 listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
31702 listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
31703 listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
31704 listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
31705 listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
31706 listener.upX.linearRampToValueAtTime(up.x, endTime);
31707 listener.upY.linearRampToValueAtTime(up.y, endTime);
31708 listener.upZ.linearRampToValueAtTime(up.z, endTime);
31710 listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
31711 listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
31715 return AudioListener;
31718 var Audio = /*#__PURE__*/function (_Object3D) {
31719 _inheritsLoose(Audio, _Object3D);
31721 function Audio(listener) {
31724 _this = _Object3D.call(this) || this;
31725 _this.type = 'Audio';
31726 _this.listener = listener;
31727 _this.context = listener.context;
31728 _this.gain = _this.context.createGain();
31730 _this.gain.connect(listener.getInput());
31732 _this.autoplay = false;
31733 _this.buffer = null;
31735 _this.loop = false;
31736 _this.loopStart = 0;
31739 _this.duration = undefined;
31740 _this.playbackRate = 1;
31741 _this.isPlaying = false;
31742 _this.hasPlaybackControl = true;
31743 _this.source = null;
31744 _this.sourceType = 'empty';
31745 _this._startedAt = 0;
31746 _this._progress = 0;
31747 _this._connected = false;
31748 _this.filters = [];
31752 var _proto = Audio.prototype;
31754 _proto.getOutput = function getOutput() {
31758 _proto.setNodeSource = function setNodeSource(audioNode) {
31759 this.hasPlaybackControl = false;
31760 this.sourceType = 'audioNode';
31761 this.source = audioNode;
31766 _proto.setMediaElementSource = function setMediaElementSource(mediaElement) {
31767 this.hasPlaybackControl = false;
31768 this.sourceType = 'mediaNode';
31769 this.source = this.context.createMediaElementSource(mediaElement);
31774 _proto.setMediaStreamSource = function setMediaStreamSource(mediaStream) {
31775 this.hasPlaybackControl = false;
31776 this.sourceType = 'mediaStreamNode';
31777 this.source = this.context.createMediaStreamSource(mediaStream);
31782 _proto.setBuffer = function setBuffer(audioBuffer) {
31783 this.buffer = audioBuffer;
31784 this.sourceType = 'buffer';
31785 if (this.autoplay) this.play();
31789 _proto.play = function play(delay) {
31790 if (delay === void 0) {
31794 if (this.isPlaying === true) {
31795 console.warn('THREE.Audio: Audio is already playing.');
31799 if (this.hasPlaybackControl === false) {
31800 console.warn('THREE.Audio: this Audio has no playback control.');
31804 this._startedAt = this.context.currentTime + delay;
31805 var source = this.context.createBufferSource();
31806 source.buffer = this.buffer;
31807 source.loop = this.loop;
31808 source.loopStart = this.loopStart;
31809 source.loopEnd = this.loopEnd;
31810 source.onended = this.onEnded.bind(this);
31811 source.start(this._startedAt, this._progress + this.offset, this.duration);
31812 this.isPlaying = true;
31813 this.source = source;
31814 this.setDetune(this.detune);
31815 this.setPlaybackRate(this.playbackRate);
31816 return this.connect();
31819 _proto.pause = function pause() {
31820 if (this.hasPlaybackControl === false) {
31821 console.warn('THREE.Audio: this Audio has no playback control.');
31825 if (this.isPlaying === true) {
31826 // update current progress
31827 this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
31829 if (this.loop === true) {
31830 // ensure _progress does not exceed duration with looped audios
31831 this._progress = this._progress % (this.duration || this.buffer.duration);
31834 this.source.stop();
31835 this.source.onended = null;
31836 this.isPlaying = false;
31842 _proto.stop = function stop() {
31843 if (this.hasPlaybackControl === false) {
31844 console.warn('THREE.Audio: this Audio has no playback control.');
31848 this._progress = 0;
31849 this.source.stop();
31850 this.source.onended = null;
31851 this.isPlaying = false;
31855 _proto.connect = function connect() {
31856 if (this.filters.length > 0) {
31857 this.source.connect(this.filters[0]);
31859 for (var i = 1, l = this.filters.length; i < l; i++) {
31860 this.filters[i - 1].connect(this.filters[i]);
31863 this.filters[this.filters.length - 1].connect(this.getOutput());
31865 this.source.connect(this.getOutput());
31868 this._connected = true;
31872 _proto.disconnect = function disconnect() {
31873 if (this.filters.length > 0) {
31874 this.source.disconnect(this.filters[0]);
31876 for (var i = 1, l = this.filters.length; i < l; i++) {
31877 this.filters[i - 1].disconnect(this.filters[i]);
31880 this.filters[this.filters.length - 1].disconnect(this.getOutput());
31882 this.source.disconnect(this.getOutput());
31885 this._connected = false;
31889 _proto.getFilters = function getFilters() {
31890 return this.filters;
31893 _proto.setFilters = function setFilters(value) {
31894 if (!value) value = [];
31896 if (this._connected === true) {
31898 this.filters = value.slice();
31901 this.filters = value.slice();
31907 _proto.setDetune = function setDetune(value) {
31908 this.detune = value;
31909 if (this.source.detune === undefined) return; // only set detune when available
31911 if (this.isPlaying === true) {
31912 this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
31918 _proto.getDetune = function getDetune() {
31919 return this.detune;
31922 _proto.getFilter = function getFilter() {
31923 return this.getFilters()[0];
31926 _proto.setFilter = function setFilter(filter) {
31927 return this.setFilters(filter ? [filter] : []);
31930 _proto.setPlaybackRate = function setPlaybackRate(value) {
31931 if (this.hasPlaybackControl === false) {
31932 console.warn('THREE.Audio: this Audio has no playback control.');
31936 this.playbackRate = value;
31938 if (this.isPlaying === true) {
31939 this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
31945 _proto.getPlaybackRate = function getPlaybackRate() {
31946 return this.playbackRate;
31949 _proto.onEnded = function onEnded() {
31950 this.isPlaying = false;
31953 _proto.getLoop = function getLoop() {
31954 if (this.hasPlaybackControl === false) {
31955 console.warn('THREE.Audio: this Audio has no playback control.');
31962 _proto.setLoop = function setLoop(value) {
31963 if (this.hasPlaybackControl === false) {
31964 console.warn('THREE.Audio: this Audio has no playback control.');
31970 if (this.isPlaying === true) {
31971 this.source.loop = this.loop;
31977 _proto.setLoopStart = function setLoopStart(value) {
31978 this.loopStart = value;
31982 _proto.setLoopEnd = function setLoopEnd(value) {
31983 this.loopEnd = value;
31987 _proto.getVolume = function getVolume() {
31988 return this.gain.gain.value;
31991 _proto.setVolume = function setVolume(value) {
31992 this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
31999 var _position$3 = /*@__PURE__*/new Vector3();
32001 var _quaternion$4 = /*@__PURE__*/new Quaternion();
32003 var _scale$2 = /*@__PURE__*/new Vector3();
32005 var _orientation$1 = /*@__PURE__*/new Vector3();
32007 var PositionalAudio = /*#__PURE__*/function (_Audio) {
32008 _inheritsLoose(PositionalAudio, _Audio);
32010 function PositionalAudio(listener) {
32013 _this = _Audio.call(this, listener) || this;
32014 _this.panner = _this.context.createPanner();
32015 _this.panner.panningModel = 'HRTF';
32017 _this.panner.connect(_this.gain);
32022 var _proto = PositionalAudio.prototype;
32024 _proto.getOutput = function getOutput() {
32025 return this.panner;
32028 _proto.getRefDistance = function getRefDistance() {
32029 return this.panner.refDistance;
32032 _proto.setRefDistance = function setRefDistance(value) {
32033 this.panner.refDistance = value;
32037 _proto.getRolloffFactor = function getRolloffFactor() {
32038 return this.panner.rolloffFactor;
32041 _proto.setRolloffFactor = function setRolloffFactor(value) {
32042 this.panner.rolloffFactor = value;
32046 _proto.getDistanceModel = function getDistanceModel() {
32047 return this.panner.distanceModel;
32050 _proto.setDistanceModel = function setDistanceModel(value) {
32051 this.panner.distanceModel = value;
32055 _proto.getMaxDistance = function getMaxDistance() {
32056 return this.panner.maxDistance;
32059 _proto.setMaxDistance = function setMaxDistance(value) {
32060 this.panner.maxDistance = value;
32064 _proto.setDirectionalCone = function setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
32065 this.panner.coneInnerAngle = coneInnerAngle;
32066 this.panner.coneOuterAngle = coneOuterAngle;
32067 this.panner.coneOuterGain = coneOuterGain;
32071 _proto.updateMatrixWorld = function updateMatrixWorld(force) {
32072 _Audio.prototype.updateMatrixWorld.call(this, force);
32074 if (this.hasPlaybackControl === true && this.isPlaying === false) return;
32075 this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
32077 _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
32079 var panner = this.panner;
32081 if (panner.positionX) {
32082 // code path for Chrome and Firefox (see #14393)
32083 var endTime = this.context.currentTime + this.listener.timeDelta;
32084 panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
32085 panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
32086 panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
32087 panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
32088 panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
32089 panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
32091 panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
32092 panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
32096 return PositionalAudio;
32099 var AudioAnalyser = /*#__PURE__*/function () {
32100 function AudioAnalyser(audio, fftSize) {
32101 if (fftSize === void 0) {
32105 this.analyser = audio.context.createAnalyser();
32106 this.analyser.fftSize = fftSize;
32107 this.data = new Uint8Array(this.analyser.frequencyBinCount);
32108 audio.getOutput().connect(this.analyser);
32111 var _proto = AudioAnalyser.prototype;
32113 _proto.getFrequencyData = function getFrequencyData() {
32114 this.analyser.getByteFrequencyData(this.data);
32118 _proto.getAverageFrequency = function getAverageFrequency() {
32120 var data = this.getFrequencyData();
32122 for (var i = 0; i < data.length; i++) {
32126 return value / data.length;
32129 return AudioAnalyser;
32132 function PropertyMixer(binding, typeName, valueSize) {
32133 this.binding = binding;
32134 this.valueSize = valueSize;
32135 var mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
32137 // interpolators can use .buffer as their .result
32138 // the data then goes to 'incoming'
32140 // 'accu0' and 'accu1' are used frame-interleaved for
32141 // the cumulative result and are compared to detect
32144 // 'orig' stores the original state of the property
32146 // 'add' is used for additive cumulative results
32148 // 'work' is optional and is only present for quaternion types. It is used
32149 // to store intermediate quaternion multiplication results
32151 switch (typeName) {
32153 mixFunction = this._slerp;
32154 mixFunctionAdditive = this._slerpAdditive;
32155 setIdentity = this._setAdditiveIdentityQuaternion;
32156 this.buffer = new Float64Array(valueSize * 6);
32157 this._workIndex = 5;
32162 mixFunction = this._select; // Use the regular mix function and for additive on these types,
32163 // additive is not relevant for non-numeric types
32165 mixFunctionAdditive = this._select;
32166 setIdentity = this._setAdditiveIdentityOther;
32167 this.buffer = new Array(valueSize * 5);
32171 mixFunction = this._lerp;
32172 mixFunctionAdditive = this._lerpAdditive;
32173 setIdentity = this._setAdditiveIdentityNumeric;
32174 this.buffer = new Float64Array(valueSize * 5);
32177 this._mixBufferRegion = mixFunction;
32178 this._mixBufferRegionAdditive = mixFunctionAdditive;
32179 this._setIdentity = setIdentity;
32180 this._origIndex = 3;
32181 this._addIndex = 4;
32182 this.cumulativeWeight = 0;
32183 this.cumulativeWeightAdditive = 0;
32185 this.referenceCount = 0;
32188 Object.assign(PropertyMixer.prototype, {
32189 // accumulate data in the 'incoming' region into 'accu<i>'
32190 accumulate: function accumulate(accuIndex, weight) {
32191 // note: happily accumulating nothing when weight = 0, the caller knows
32192 // the weight and shouldn't have made the call in the first place
32193 var buffer = this.buffer,
32194 stride = this.valueSize,
32195 offset = accuIndex * stride + stride;
32196 var currentWeight = this.cumulativeWeight;
32198 if (currentWeight === 0) {
32199 // accuN := incoming * weight
32200 for (var i = 0; i !== stride; ++i) {
32201 buffer[offset + i] = buffer[i];
32204 currentWeight = weight;
32206 // accuN := accuN + incoming * weight
32207 currentWeight += weight;
32208 var mix = weight / currentWeight;
32210 this._mixBufferRegion(buffer, offset, 0, mix, stride);
32213 this.cumulativeWeight = currentWeight;
32215 // accumulate data in the 'incoming' region into 'add'
32216 accumulateAdditive: function accumulateAdditive(weight) {
32217 var buffer = this.buffer,
32218 stride = this.valueSize,
32219 offset = stride * this._addIndex;
32221 if (this.cumulativeWeightAdditive === 0) {
32223 this._setIdentity();
32224 } // add := add + incoming * weight
32227 this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
32229 this.cumulativeWeightAdditive += weight;
32231 // apply the state of 'accu<i>' to the binding when accus differ
32232 apply: function apply(accuIndex) {
32233 var stride = this.valueSize,
32234 buffer = this.buffer,
32235 offset = accuIndex * stride + stride,
32236 weight = this.cumulativeWeight,
32237 weightAdditive = this.cumulativeWeightAdditive,
32238 binding = this.binding;
32239 this.cumulativeWeight = 0;
32240 this.cumulativeWeightAdditive = 0;
32243 // accuN := accuN + original * ( 1 - cumulativeWeight )
32244 var originalValueOffset = stride * this._origIndex;
32246 this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
32249 if (weightAdditive > 0) {
32250 // accuN := accuN + additive accuN
32251 this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
32254 for (var i = stride, e = stride + stride; i !== e; ++i) {
32255 if (buffer[i] !== buffer[i + stride]) {
32256 // value has changed -> update scene graph
32257 binding.setValue(buffer, offset);
32262 // remember the state of the bound property and copy it to both accus
32263 saveOriginalState: function saveOriginalState() {
32264 var binding = this.binding;
32265 var buffer = this.buffer,
32266 stride = this.valueSize,
32267 originalValueOffset = stride * this._origIndex;
32268 binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
32270 for (var i = stride, e = originalValueOffset; i !== e; ++i) {
32271 buffer[i] = buffer[originalValueOffset + i % stride];
32272 } // Add to identity for additive
32275 this._setIdentity();
32277 this.cumulativeWeight = 0;
32278 this.cumulativeWeightAdditive = 0;
32280 // apply the state previously taken via 'saveOriginalState' to the binding
32281 restoreOriginalState: function restoreOriginalState() {
32282 var originalValueOffset = this.valueSize * 3;
32283 this.binding.setValue(this.buffer, originalValueOffset);
32285 _setAdditiveIdentityNumeric: function _setAdditiveIdentityNumeric() {
32286 var startIndex = this._addIndex * this.valueSize;
32287 var endIndex = startIndex + this.valueSize;
32289 for (var i = startIndex; i < endIndex; i++) {
32290 this.buffer[i] = 0;
32293 _setAdditiveIdentityQuaternion: function _setAdditiveIdentityQuaternion() {
32294 this._setAdditiveIdentityNumeric();
32296 this.buffer[this._addIndex * this.valueSize + 3] = 1;
32298 _setAdditiveIdentityOther: function _setAdditiveIdentityOther() {
32299 var startIndex = this._origIndex * this.valueSize;
32300 var targetIndex = this._addIndex * this.valueSize;
32302 for (var i = 0; i < this.valueSize; i++) {
32303 this.buffer[targetIndex + i] = this.buffer[startIndex + i];
32307 _select: function _select(buffer, dstOffset, srcOffset, t, stride) {
32309 for (var i = 0; i !== stride; ++i) {
32310 buffer[dstOffset + i] = buffer[srcOffset + i];
32314 _slerp: function _slerp(buffer, dstOffset, srcOffset, t) {
32315 Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
32317 _slerpAdditive: function _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
32318 var workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
32320 Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
32322 Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
32324 _lerp: function _lerp(buffer, dstOffset, srcOffset, t, stride) {
32327 for (var i = 0; i !== stride; ++i) {
32328 var j = dstOffset + i;
32329 buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
32332 _lerpAdditive: function _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
32333 for (var i = 0; i !== stride; ++i) {
32334 var j = dstOffset + i;
32335 buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
32340 // Characters [].:/ are reserved for track binding syntax.
32341 var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
32343 var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
32344 // only latin characters, and the unicode \p{L} is not yet supported. So
32345 // instead, we exclude reserved characters and match everything else.
32348 var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
32350 var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
32351 // be matched to parse the rest of the track name.
32354 var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
32357 var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
32358 // characters. Accessor may contain any character except closing bracket.
32361 var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
32362 // contain any non-bracket characters.
32365 var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
32367 var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
32369 var _supportedObjectNames = ['material', 'materials', 'bones'];
32371 function Composite(targetGroup, path, optionalParsedPath) {
32372 var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
32373 this._targetGroup = targetGroup;
32374 this._bindings = targetGroup.subscribe_(path, parsedPath);
32377 Object.assign(Composite.prototype, {
32378 getValue: function getValue(array, offset) {
32379 this.bind(); // bind all binding
32381 var firstValidIndex = this._targetGroup.nCachedObjects_,
32382 binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
32384 if (binding !== undefined) binding.getValue(array, offset);
32386 setValue: function setValue(array, offset) {
32387 var bindings = this._bindings;
32389 for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
32390 bindings[i].setValue(array, offset);
32393 bind: function bind() {
32394 var bindings = this._bindings;
32396 for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
32397 bindings[i].bind();
32400 unbind: function unbind() {
32401 var bindings = this._bindings;
32403 for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
32404 bindings[i].unbind();
32409 function PropertyBinding(rootNode, path, parsedPath) {
32411 this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
32412 this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
32413 this.rootNode = rootNode;
32416 Object.assign(PropertyBinding, {
32417 Composite: Composite,
32418 create: function create(root, path, parsedPath) {
32419 if (!(root && root.isAnimationObjectGroup)) {
32420 return new PropertyBinding(root, path, parsedPath);
32422 return new PropertyBinding.Composite(root, path, parsedPath);
32427 * Replaces spaces with underscores and removes unsupported characters from
32428 * node names, to ensure compatibility with parseTrackName().
32430 * @param {string} name Node name to be sanitized.
32433 sanitizeNodeName: function sanitizeNodeName(name) {
32434 return name.replace(/\s/g, '_').replace(_reservedRe, '');
32436 parseTrackName: function parseTrackName(trackName) {
32437 var matches = _trackRe.exec(trackName);
32440 throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
32444 // directoryName: matches[ 1 ], // (tschw) currently unused
32445 nodeName: matches[2],
32446 objectName: matches[3],
32447 objectIndex: matches[4],
32448 propertyName: matches[5],
32450 propertyIndex: matches[6]
32452 var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
32454 if (lastDot !== undefined && lastDot !== -1) {
32455 var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
32456 // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
32457 // 'bar' could be the objectName, or part of a nodeName (which can
32458 // include '.' characters).
32460 if (_supportedObjectNames.indexOf(objectName) !== -1) {
32461 results.nodeName = results.nodeName.substring(0, lastDot);
32462 results.objectName = objectName;
32466 if (results.propertyName === null || results.propertyName.length === 0) {
32467 throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
32472 findNode: function findNode(root, nodeName) {
32473 if (!nodeName || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
32475 } // search into skeleton bones.
32478 if (root.skeleton) {
32479 var bone = root.skeleton.getBoneByName(nodeName);
32481 if (bone !== undefined) {
32484 } // search into node subtree.
32487 if (root.children) {
32488 var searchNodeSubtree = function searchNodeSubtree(children) {
32489 for (var i = 0; i < children.length; i++) {
32490 var childNode = children[i];
32492 if (childNode.name === nodeName || childNode.uuid === nodeName) {
32496 var result = searchNodeSubtree(childNode.children);
32497 if (result) return result;
32503 var subTreeNode = searchNodeSubtree(root.children);
32506 return subTreeNode;
32513 Object.assign(PropertyBinding.prototype, {
32514 // prototype, continued
32515 // these are used to "bind" a nonexistent property
32516 _getValue_unavailable: function _getValue_unavailable() {},
32517 _setValue_unavailable: function _setValue_unavailable() {},
32527 MatrixWorldNeedsUpdate: 2
32529 GetterByBindingType: [function getValue_direct(buffer, offset) {
32530 buffer[offset] = this.node[this.propertyName];
32531 }, function getValue_array(buffer, offset) {
32532 var source = this.resolvedProperty;
32534 for (var i = 0, n = source.length; i !== n; ++i) {
32535 buffer[offset++] = source[i];
32537 }, function getValue_arrayElement(buffer, offset) {
32538 buffer[offset] = this.resolvedProperty[this.propertyIndex];
32539 }, function getValue_toArray(buffer, offset) {
32540 this.resolvedProperty.toArray(buffer, offset);
32542 SetterByBindingTypeAndVersioning: [[// Direct
32543 function setValue_direct(buffer, offset) {
32544 this.targetObject[this.propertyName] = buffer[offset];
32545 }, function setValue_direct_setNeedsUpdate(buffer, offset) {
32546 this.targetObject[this.propertyName] = buffer[offset];
32547 this.targetObject.needsUpdate = true;
32548 }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
32549 this.targetObject[this.propertyName] = buffer[offset];
32550 this.targetObject.matrixWorldNeedsUpdate = true;
32551 }], [// EntireArray
32552 function setValue_array(buffer, offset) {
32553 var dest = this.resolvedProperty;
32555 for (var i = 0, n = dest.length; i !== n; ++i) {
32556 dest[i] = buffer[offset++];
32558 }, function setValue_array_setNeedsUpdate(buffer, offset) {
32559 var dest = this.resolvedProperty;
32561 for (var i = 0, n = dest.length; i !== n; ++i) {
32562 dest[i] = buffer[offset++];
32565 this.targetObject.needsUpdate = true;
32566 }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
32567 var dest = this.resolvedProperty;
32569 for (var i = 0, n = dest.length; i !== n; ++i) {
32570 dest[i] = buffer[offset++];
32573 this.targetObject.matrixWorldNeedsUpdate = true;
32574 }], [// ArrayElement
32575 function setValue_arrayElement(buffer, offset) {
32576 this.resolvedProperty[this.propertyIndex] = buffer[offset];
32577 }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
32578 this.resolvedProperty[this.propertyIndex] = buffer[offset];
32579 this.targetObject.needsUpdate = true;
32580 }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
32581 this.resolvedProperty[this.propertyIndex] = buffer[offset];
32582 this.targetObject.matrixWorldNeedsUpdate = true;
32583 }], [// HasToFromArray
32584 function setValue_fromArray(buffer, offset) {
32585 this.resolvedProperty.fromArray(buffer, offset);
32586 }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
32587 this.resolvedProperty.fromArray(buffer, offset);
32588 this.targetObject.needsUpdate = true;
32589 }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
32590 this.resolvedProperty.fromArray(buffer, offset);
32591 this.targetObject.matrixWorldNeedsUpdate = true;
32593 getValue: function getValue_unbound(targetArray, offset) {
32595 this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
32596 // 'bind' sets 'this.getValue' / 'setValue' and shadows the
32597 // prototype version of these methods with one that represents
32598 // the bound state. When the property is not found, the methods
32601 setValue: function getValue_unbound(sourceArray, offset) {
32603 this.setValue(sourceArray, offset);
32605 // create getter / setter pair for a property in the scene graph
32606 bind: function bind() {
32607 var targetObject = this.node;
32608 var parsedPath = this.parsedPath;
32609 var objectName = parsedPath.objectName;
32610 var propertyName = parsedPath.propertyName;
32611 var propertyIndex = parsedPath.propertyIndex;
32613 if (!targetObject) {
32614 targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
32615 this.node = targetObject;
32616 } // set fail state so we can just 'return' on error
32619 this.getValue = this._getValue_unavailable;
32620 this.setValue = this._setValue_unavailable; // ensure there is a value node
32622 if (!targetObject) {
32623 console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
32628 var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
32630 switch (objectName) {
32632 if (!targetObject.material) {
32633 console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
32637 if (!targetObject.material.materials) {
32638 console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
32642 targetObject = targetObject.material.materials;
32646 if (!targetObject.skeleton) {
32647 console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
32649 } // potential future optimization: skip this if propertyIndex is already an integer
32650 // and convert the integer string to a true integer.
32653 targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
32655 for (var i = 0; i < targetObject.length; i++) {
32656 if (targetObject[i].name === objectIndex) {
32665 if (targetObject[objectName] === undefined) {
32666 console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
32670 targetObject = targetObject[objectName];
32673 if (objectIndex !== undefined) {
32674 if (targetObject[objectIndex] === undefined) {
32675 console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
32679 targetObject = targetObject[objectIndex];
32681 } // resolve property
32684 var nodeProperty = targetObject[propertyName];
32686 if (nodeProperty === undefined) {
32687 var nodeName = parsedPath.nodeName;
32688 console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
32690 } // determine versioning scheme
32693 var versioning = this.Versioning.None;
32694 this.targetObject = targetObject;
32696 if (targetObject.needsUpdate !== undefined) {
32698 versioning = this.Versioning.NeedsUpdate;
32699 } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
32701 versioning = this.Versioning.MatrixWorldNeedsUpdate;
32702 } // determine how the property gets bound
32705 var bindingType = this.BindingType.Direct;
32707 if (propertyIndex !== undefined) {
32708 // access a sub element of the property array (only primitives are supported right now)
32709 if (propertyName === "morphTargetInfluences") {
32710 // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
32711 // support resolving morphTarget names into indices.
32712 if (!targetObject.geometry) {
32713 console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
32717 if (targetObject.geometry.isBufferGeometry) {
32718 if (!targetObject.geometry.morphAttributes) {
32719 console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
32723 if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
32724 propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
32727 console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
32732 bindingType = this.BindingType.ArrayElement;
32733 this.resolvedProperty = nodeProperty;
32734 this.propertyIndex = propertyIndex;
32735 } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
32736 // must use copy for Object3D.Euler/Quaternion
32737 bindingType = this.BindingType.HasFromToArray;
32738 this.resolvedProperty = nodeProperty;
32739 } else if (Array.isArray(nodeProperty)) {
32740 bindingType = this.BindingType.EntireArray;
32741 this.resolvedProperty = nodeProperty;
32743 this.propertyName = propertyName;
32744 } // select getter / setter
32747 this.getValue = this.GetterByBindingType[bindingType];
32748 this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
32750 unbind: function unbind() {
32751 this.node = null; // back to the prototype version of getValue / setValue
32752 // note: avoiding to mutate the shape of 'this' via 'delete'
32754 this.getValue = this._getValue_unbound;
32755 this.setValue = this._setValue_unbound;
32757 }); // DECLARE ALIAS AFTER assign prototype
32759 Object.assign(PropertyBinding.prototype, {
32760 // initial state of these methods that calls 'bind'
32761 _getValue_unbound: PropertyBinding.prototype.getValue,
32762 _setValue_unbound: PropertyBinding.prototype.setValue
32767 * A group of objects that receives a shared animation state.
32771 * - Add objects you would otherwise pass as 'root' to the
32772 * constructor or the .clipAction method of AnimationMixer.
32774 * - Instead pass this object as 'root'.
32776 * - You can also add and remove objects later when the mixer
32781 * Objects of this class appear as one object to the mixer,
32782 * so cache control of the individual objects must be done
32787 * - The animated properties must be compatible among the
32788 * all objects in the group.
32790 * - A single property can either be controlled through a
32791 * target group or directly, but not both.
32794 function AnimationObjectGroup() {
32795 this.uuid = MathUtils.generateUUID(); // cached objects followed by the active ones
32797 this._objects = Array.prototype.slice.call(arguments);
32798 this.nCachedObjects_ = 0; // threshold
32799 // note: read by PropertyBinding.Composite
32802 this._indicesByUUID = indices; // for bookkeeping
32804 for (var i = 0, n = arguments.length; i !== n; ++i) {
32805 indices[arguments[i].uuid] = i;
32808 this._paths = []; // inside: string
32810 this._parsedPaths = []; // inside: { we don't care, here }
32812 this._bindings = []; // inside: Array< PropertyBinding >
32814 this._bindingsIndicesByPath = {}; // inside: indices in these arrays
32820 return scope._objects.length;
32824 return this.total - scope.nCachedObjects_;
32829 get bindingsPerObject() {
32830 return scope._bindings.length;
32836 Object.assign(AnimationObjectGroup.prototype, {
32837 isAnimationObjectGroup: true,
32838 add: function add() {
32839 var objects = this._objects,
32840 indicesByUUID = this._indicesByUUID,
32841 paths = this._paths,
32842 parsedPaths = this._parsedPaths,
32843 bindings = this._bindings,
32844 nBindings = bindings.length;
32845 var knownObject = undefined,
32846 nObjects = objects.length,
32847 nCachedObjects = this.nCachedObjects_;
32849 for (var i = 0, n = arguments.length; i !== n; ++i) {
32850 var object = arguments[i],
32851 uuid = object.uuid;
32852 var index = indicesByUUID[uuid];
32854 if (index === undefined) {
32855 // unknown object -> add it to the ACTIVE region
32856 index = nObjects++;
32857 indicesByUUID[uuid] = index;
32858 objects.push(object); // accounting is done, now do the same for all bindings
32860 for (var j = 0, m = nBindings; j !== m; ++j) {
32861 bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
32863 } else if (index < nCachedObjects) {
32864 knownObject = objects[index]; // move existing object to the ACTIVE region
32866 var firstActiveIndex = --nCachedObjects,
32867 lastCachedObject = objects[firstActiveIndex];
32868 indicesByUUID[lastCachedObject.uuid] = index;
32869 objects[index] = lastCachedObject;
32870 indicesByUUID[uuid] = firstActiveIndex;
32871 objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
32873 for (var _j = 0, _m = nBindings; _j !== _m; ++_j) {
32874 var bindingsForPath = bindings[_j],
32875 lastCached = bindingsForPath[firstActiveIndex];
32876 var binding = bindingsForPath[index];
32877 bindingsForPath[index] = lastCached;
32879 if (binding === undefined) {
32880 // since we do not bother to create new bindings
32881 // for objects that are cached, the binding may
32882 // or may not exist
32883 binding = new PropertyBinding(object, paths[_j], parsedPaths[_j]);
32886 bindingsForPath[firstActiveIndex] = binding;
32888 } else if (objects[index] !== knownObject) {
32889 console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
32890 } // else the object is already where we want it to be
32895 this.nCachedObjects_ = nCachedObjects;
32897 remove: function remove() {
32898 var objects = this._objects,
32899 indicesByUUID = this._indicesByUUID,
32900 bindings = this._bindings,
32901 nBindings = bindings.length;
32902 var nCachedObjects = this.nCachedObjects_;
32904 for (var i = 0, n = arguments.length; i !== n; ++i) {
32905 var object = arguments[i],
32906 uuid = object.uuid,
32907 index = indicesByUUID[uuid];
32909 if (index !== undefined && index >= nCachedObjects) {
32910 // move existing object into the CACHED region
32911 var lastCachedIndex = nCachedObjects++,
32912 firstActiveObject = objects[lastCachedIndex];
32913 indicesByUUID[firstActiveObject.uuid] = index;
32914 objects[index] = firstActiveObject;
32915 indicesByUUID[uuid] = lastCachedIndex;
32916 objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
32918 for (var j = 0, m = nBindings; j !== m; ++j) {
32919 var bindingsForPath = bindings[j],
32920 firstActive = bindingsForPath[lastCachedIndex],
32921 binding = bindingsForPath[index];
32922 bindingsForPath[index] = firstActive;
32923 bindingsForPath[lastCachedIndex] = binding;
32929 this.nCachedObjects_ = nCachedObjects;
32932 uncache: function uncache() {
32933 var objects = this._objects,
32934 indicesByUUID = this._indicesByUUID,
32935 bindings = this._bindings,
32936 nBindings = bindings.length;
32937 var nCachedObjects = this.nCachedObjects_,
32938 nObjects = objects.length;
32940 for (var i = 0, n = arguments.length; i !== n; ++i) {
32941 var object = arguments[i],
32942 uuid = object.uuid,
32943 index = indicesByUUID[uuid];
32945 if (index !== undefined) {
32946 delete indicesByUUID[uuid];
32948 if (index < nCachedObjects) {
32949 // object is cached, shrink the CACHED region
32950 var firstActiveIndex = --nCachedObjects,
32951 lastCachedObject = objects[firstActiveIndex],
32952 lastIndex = --nObjects,
32953 lastObject = objects[lastIndex]; // last cached object takes this object's place
32955 indicesByUUID[lastCachedObject.uuid] = index;
32956 objects[index] = lastCachedObject; // last object goes to the activated slot and pop
32958 indicesByUUID[lastObject.uuid] = firstActiveIndex;
32959 objects[firstActiveIndex] = lastObject;
32960 objects.pop(); // accounting is done, now do the same for all bindings
32962 for (var j = 0, m = nBindings; j !== m; ++j) {
32963 var bindingsForPath = bindings[j],
32964 lastCached = bindingsForPath[firstActiveIndex],
32965 last = bindingsForPath[lastIndex];
32966 bindingsForPath[index] = lastCached;
32967 bindingsForPath[firstActiveIndex] = last;
32968 bindingsForPath.pop();
32971 // object is active, just swap with the last and pop
32972 var _lastIndex = --nObjects,
32973 _lastObject = objects[_lastIndex];
32975 if (_lastIndex > 0) {
32976 indicesByUUID[_lastObject.uuid] = index;
32979 objects[index] = _lastObject;
32980 objects.pop(); // accounting is done, now do the same for all bindings
32982 for (var _j2 = 0, _m2 = nBindings; _j2 !== _m2; ++_j2) {
32983 var _bindingsForPath = bindings[_j2];
32984 _bindingsForPath[index] = _bindingsForPath[_lastIndex];
32986 _bindingsForPath.pop();
32988 } // cached or active
32990 } // if object is known
32995 this.nCachedObjects_ = nCachedObjects;
32997 // Internal interface used by befriended PropertyBinding.Composite:
32998 subscribe_: function subscribe_(path, parsedPath) {
32999 // returns an array of bindings for the given path that is changed
33000 // according to the contained objects in the group
33001 var indicesByPath = this._bindingsIndicesByPath;
33002 var index = indicesByPath[path];
33003 var bindings = this._bindings;
33004 if (index !== undefined) return bindings[index];
33005 var paths = this._paths,
33006 parsedPaths = this._parsedPaths,
33007 objects = this._objects,
33008 nObjects = objects.length,
33009 nCachedObjects = this.nCachedObjects_,
33010 bindingsForPath = new Array(nObjects);
33011 index = bindings.length;
33012 indicesByPath[path] = index;
33014 parsedPaths.push(parsedPath);
33015 bindings.push(bindingsForPath);
33017 for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
33018 var object = objects[i];
33019 bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
33022 return bindingsForPath;
33024 unsubscribe_: function unsubscribe_(path) {
33025 // tells the group to forget about a property path and no longer
33026 // update the array previously obtained with 'subscribe_'
33027 var indicesByPath = this._bindingsIndicesByPath,
33028 index = indicesByPath[path];
33030 if (index !== undefined) {
33031 var paths = this._paths,
33032 parsedPaths = this._parsedPaths,
33033 bindings = this._bindings,
33034 lastBindingsIndex = bindings.length - 1,
33035 lastBindings = bindings[lastBindingsIndex],
33036 lastBindingsPath = path[lastBindingsIndex];
33037 indicesByPath[lastBindingsPath] = index;
33038 bindings[index] = lastBindings;
33040 parsedPaths[index] = parsedPaths[lastBindingsIndex];
33042 paths[index] = paths[lastBindingsIndex];
33048 var AnimationAction = /*#__PURE__*/function () {
33049 function AnimationAction(mixer, clip, localRoot, blendMode) {
33050 if (localRoot === void 0) {
33054 if (blendMode === void 0) {
33055 blendMode = clip.blendMode;
33058 this._mixer = mixer;
33060 this._localRoot = localRoot;
33061 this.blendMode = blendMode;
33062 var tracks = clip.tracks,
33063 nTracks = tracks.length,
33064 interpolants = new Array(nTracks);
33065 var interpolantSettings = {
33066 endingStart: ZeroCurvatureEnding,
33067 endingEnd: ZeroCurvatureEnding
33070 for (var i = 0; i !== nTracks; ++i) {
33071 var interpolant = tracks[i].createInterpolant(null);
33072 interpolants[i] = interpolant;
33073 interpolant.settings = interpolantSettings;
33076 this._interpolantSettings = interpolantSettings;
33077 this._interpolants = interpolants; // bound by the mixer
33078 // inside: PropertyMixer (managed by the mixer)
33080 this._propertyBindings = new Array(nTracks);
33081 this._cacheIndex = null; // for the memory manager
33083 this._byClipCacheIndex = null; // for the memory manager
33085 this._timeScaleInterpolant = null;
33086 this._weightInterpolant = null;
33087 this.loop = LoopRepeat;
33088 this._loopCount = -1; // global mixer time when the action is to be started
33089 // it's set back to 'null' upon start of the action
33091 this._startTime = null; // scaled local time of the action
33092 // gets clamped or wrapped to 0..clip.duration according to loop
33095 this.timeScale = 1;
33096 this._effectiveTimeScale = 1;
33098 this._effectiveWeight = 1;
33099 this.repetitions = Infinity; // no. of repetitions when looping
33101 this.paused = false; // true -> zero effective time scale
33103 this.enabled = true; // false -> zero effective weight
33105 this.clampWhenFinished = false; // keep feeding the last frame?
33107 this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
33109 this.zeroSlopeAtEnd = true; // clips for start, loop and end
33110 } // State & Scheduling
33113 var _proto = AnimationAction.prototype;
33115 _proto.play = function play() {
33116 this._mixer._activateAction(this);
33121 _proto.stop = function stop() {
33122 this._mixer._deactivateAction(this);
33124 return this.reset();
33127 _proto.reset = function reset() {
33128 this.paused = false;
33129 this.enabled = true;
33130 this.time = 0; // restart clip
33132 this._loopCount = -1; // forget previous loops
33134 this._startTime = null; // forget scheduling
33136 return this.stopFading().stopWarping();
33139 _proto.isRunning = function isRunning() {
33140 return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
33141 } // return true when play has been called
33144 _proto.isScheduled = function isScheduled() {
33145 return this._mixer._isActiveAction(this);
33148 _proto.startAt = function startAt(time) {
33149 this._startTime = time;
33153 _proto.setLoop = function setLoop(mode, repetitions) {
33155 this.repetitions = repetitions;
33158 // set the weight stopping any scheduled fading
33159 // although .enabled = false yields an effective weight of zero, this
33160 // method does *not* change .enabled, because it would be confusing
33163 _proto.setEffectiveWeight = function setEffectiveWeight(weight) {
33164 this.weight = weight; // note: same logic as when updated at runtime
33166 this._effectiveWeight = this.enabled ? weight : 0;
33167 return this.stopFading();
33168 } // return the weight considering fading and .enabled
33171 _proto.getEffectiveWeight = function getEffectiveWeight() {
33172 return this._effectiveWeight;
33175 _proto.fadeIn = function fadeIn(duration) {
33176 return this._scheduleFading(duration, 0, 1);
33179 _proto.fadeOut = function fadeOut(duration) {
33180 return this._scheduleFading(duration, 1, 0);
33183 _proto.crossFadeFrom = function crossFadeFrom(fadeOutAction, duration, warp) {
33184 fadeOutAction.fadeOut(duration);
33185 this.fadeIn(duration);
33188 var fadeInDuration = this._clip.duration,
33189 fadeOutDuration = fadeOutAction._clip.duration,
33190 startEndRatio = fadeOutDuration / fadeInDuration,
33191 endStartRatio = fadeInDuration / fadeOutDuration;
33192 fadeOutAction.warp(1.0, startEndRatio, duration);
33193 this.warp(endStartRatio, 1.0, duration);
33199 _proto.crossFadeTo = function crossFadeTo(fadeInAction, duration, warp) {
33200 return fadeInAction.crossFadeFrom(this, duration, warp);
33203 _proto.stopFading = function stopFading() {
33204 var weightInterpolant = this._weightInterpolant;
33206 if (weightInterpolant !== null) {
33207 this._weightInterpolant = null;
33209 this._mixer._takeBackControlInterpolant(weightInterpolant);
33213 } // Time Scale Control
33214 // set the time scale stopping any scheduled warping
33215 // although .paused = true yields an effective time scale of zero, this
33216 // method does *not* change .paused, because it would be confusing
33219 _proto.setEffectiveTimeScale = function setEffectiveTimeScale(timeScale) {
33220 this.timeScale = timeScale;
33221 this._effectiveTimeScale = this.paused ? 0 : timeScale;
33222 return this.stopWarping();
33223 } // return the time scale considering warping and .paused
33226 _proto.getEffectiveTimeScale = function getEffectiveTimeScale() {
33227 return this._effectiveTimeScale;
33230 _proto.setDuration = function setDuration(duration) {
33231 this.timeScale = this._clip.duration / duration;
33232 return this.stopWarping();
33235 _proto.syncWith = function syncWith(action) {
33236 this.time = action.time;
33237 this.timeScale = action.timeScale;
33238 return this.stopWarping();
33241 _proto.halt = function halt(duration) {
33242 return this.warp(this._effectiveTimeScale, 0, duration);
33245 _proto.warp = function warp(startTimeScale, endTimeScale, duration) {
33246 var mixer = this._mixer,
33248 timeScale = this.timeScale;
33249 var interpolant = this._timeScaleInterpolant;
33251 if (interpolant === null) {
33252 interpolant = mixer._lendControlInterpolant();
33253 this._timeScaleInterpolant = interpolant;
33256 var times = interpolant.parameterPositions,
33257 values = interpolant.sampleValues;
33259 times[1] = now + duration;
33260 values[0] = startTimeScale / timeScale;
33261 values[1] = endTimeScale / timeScale;
33265 _proto.stopWarping = function stopWarping() {
33266 var timeScaleInterpolant = this._timeScaleInterpolant;
33268 if (timeScaleInterpolant !== null) {
33269 this._timeScaleInterpolant = null;
33271 this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
33275 } // Object Accessors
33278 _proto.getMixer = function getMixer() {
33279 return this._mixer;
33282 _proto.getClip = function getClip() {
33286 _proto.getRoot = function getRoot() {
33287 return this._localRoot || this._mixer._root;
33291 _proto._update = function _update(time, deltaTime, timeDirection, accuIndex) {
33292 // called by the mixer
33293 if (!this.enabled) {
33294 // call ._updateWeight() to update ._effectiveWeight
33295 this._updateWeight(time);
33300 var startTime = this._startTime;
33302 if (startTime !== null) {
33303 // check for scheduled start of action
33304 var timeRunning = (time - startTime) * timeDirection;
33306 if (timeRunning < 0 || timeDirection === 0) {
33307 return; // yet to come / don't decide when delta = 0
33311 this._startTime = null; // unschedule
33313 deltaTime = timeDirection * timeRunning;
33314 } // apply time scale and advance time
33317 deltaTime *= this._updateTimeScale(time);
33319 var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
33320 // an effective weight of 0
33323 var weight = this._updateWeight(time);
33326 var _interpolants = this._interpolants;
33327 var propertyMixers = this._propertyBindings;
33329 switch (this.blendMode) {
33330 case AdditiveAnimationBlendMode:
33331 for (var j = 0, m = _interpolants.length; j !== m; ++j) {
33332 _interpolants[j].evaluate(clipTime);
33334 propertyMixers[j].accumulateAdditive(weight);
33339 case NormalAnimationBlendMode:
33341 for (var _j = 0, _m = _interpolants.length; _j !== _m; ++_j) {
33342 _interpolants[_j].evaluate(clipTime);
33344 propertyMixers[_j].accumulate(accuIndex, weight);
33351 _proto._updateWeight = function _updateWeight(time) {
33354 if (this.enabled) {
33355 weight = this.weight;
33356 var interpolant = this._weightInterpolant;
33358 if (interpolant !== null) {
33359 var interpolantValue = interpolant.evaluate(time)[0];
33360 weight *= interpolantValue;
33362 if (time > interpolant.parameterPositions[1]) {
33365 if (interpolantValue === 0) {
33366 // faded out, disable
33367 this.enabled = false;
33373 this._effectiveWeight = weight;
33377 _proto._updateTimeScale = function _updateTimeScale(time) {
33380 if (!this.paused) {
33381 timeScale = this.timeScale;
33382 var interpolant = this._timeScaleInterpolant;
33384 if (interpolant !== null) {
33385 var interpolantValue = interpolant.evaluate(time)[0];
33386 timeScale *= interpolantValue;
33388 if (time > interpolant.parameterPositions[1]) {
33389 this.stopWarping();
33391 if (timeScale === 0) {
33392 // motion has halted, pause
33393 this.paused = true;
33395 // warp done - apply final time scale
33396 this.timeScale = timeScale;
33402 this._effectiveTimeScale = timeScale;
33406 _proto._updateTime = function _updateTime(deltaTime) {
33407 var duration = this._clip.duration;
33408 var loop = this.loop;
33409 var time = this.time + deltaTime;
33410 var loopCount = this._loopCount;
33411 var pingPong = loop === LoopPingPong;
33413 if (deltaTime === 0) {
33414 if (loopCount === -1) return time;
33415 return pingPong && (loopCount & 1) === 1 ? duration - time : time;
33418 if (loop === LoopOnce) {
33419 if (loopCount === -1) {
33421 this._loopCount = 0;
33423 this._setEndings(true, true, false);
33427 if (time >= duration) {
33429 } else if (time < 0) {
33436 if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
33439 this._mixer.dispatchEvent({
33442 direction: deltaTime < 0 ? -1 : 1
33446 // repetitive Repeat or PingPong
33447 if (loopCount === -1) {
33449 if (deltaTime >= 0) {
33452 this._setEndings(true, this.repetitions === 0, pingPong);
33454 // when looping in reverse direction, the initial
33455 // transition through zero counts as a repetition,
33456 // so leave loopCount at -1
33457 this._setEndings(this.repetitions === 0, true, pingPong);
33461 if (time >= duration || time < 0) {
33463 var loopDelta = Math.floor(time / duration); // signed
33465 time -= duration * loopDelta;
33466 loopCount += Math.abs(loopDelta);
33467 var pending = this.repetitions - loopCount;
33469 if (pending <= 0) {
33470 // have to stop (switch state, clamp time, fire event)
33471 if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
33472 time = deltaTime > 0 ? duration : 0;
33475 this._mixer.dispatchEvent({
33478 direction: deltaTime > 0 ? 1 : -1
33482 if (pending === 1) {
33483 // entering the last round
33484 var atStart = deltaTime < 0;
33486 this._setEndings(atStart, !atStart, pingPong);
33488 this._setEndings(false, false, pingPong);
33491 this._loopCount = loopCount;
33494 this._mixer.dispatchEvent({
33497 loopDelta: loopDelta
33504 if (pingPong && (loopCount & 1) === 1) {
33505 // invert time for the "pong round"
33506 return duration - time;
33513 _proto._setEndings = function _setEndings(atStart, atEnd, pingPong) {
33514 var settings = this._interpolantSettings;
33517 settings.endingStart = ZeroSlopeEnding;
33518 settings.endingEnd = ZeroSlopeEnding;
33520 // assuming for LoopOnce atStart == atEnd == true
33522 settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
33524 settings.endingStart = WrapAroundEnding;
33528 settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
33530 settings.endingEnd = WrapAroundEnding;
33535 _proto._scheduleFading = function _scheduleFading(duration, weightNow, weightThen) {
33536 var mixer = this._mixer,
33538 var interpolant = this._weightInterpolant;
33540 if (interpolant === null) {
33541 interpolant = mixer._lendControlInterpolant();
33542 this._weightInterpolant = interpolant;
33545 var times = interpolant.parameterPositions,
33546 values = interpolant.sampleValues;
33548 values[0] = weightNow;
33549 times[1] = now + duration;
33550 values[1] = weightThen;
33554 return AnimationAction;
33557 function AnimationMixer(root) {
33560 this._initMemoryManager();
33562 this._accuIndex = 0;
33564 this.timeScale = 1.0;
33567 AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
33568 constructor: AnimationMixer,
33569 _bindAction: function _bindAction(action, prototypeAction) {
33570 var root = action._localRoot || this._root,
33571 tracks = action._clip.tracks,
33572 nTracks = tracks.length,
33573 bindings = action._propertyBindings,
33574 interpolants = action._interpolants,
33575 rootUuid = root.uuid,
33576 bindingsByRoot = this._bindingsByRootAndName;
33577 var bindingsByName = bindingsByRoot[rootUuid];
33579 if (bindingsByName === undefined) {
33580 bindingsByName = {};
33581 bindingsByRoot[rootUuid] = bindingsByName;
33584 for (var i = 0; i !== nTracks; ++i) {
33585 var track = tracks[i],
33586 trackName = track.name;
33587 var binding = bindingsByName[trackName];
33589 if (binding !== undefined) {
33590 bindings[i] = binding;
33592 binding = bindings[i];
33594 if (binding !== undefined) {
33595 // existing binding, make sure the cache knows
33596 if (binding._cacheIndex === null) {
33597 ++binding.referenceCount;
33599 this._addInactiveBinding(binding, rootUuid, trackName);
33605 var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
33606 binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
33607 ++binding.referenceCount;
33609 this._addInactiveBinding(binding, rootUuid, trackName);
33611 bindings[i] = binding;
33614 interpolants[i].resultBuffer = binding.buffer;
33617 _activateAction: function _activateAction(action) {
33618 if (!this._isActiveAction(action)) {
33619 if (action._cacheIndex === null) {
33620 // this action has been forgotten by the cache, but the user
33621 // appears to be still using it -> rebind
33622 var rootUuid = (action._localRoot || this._root).uuid,
33623 clipUuid = action._clip.uuid,
33624 actionsForClip = this._actionsByClip[clipUuid];
33626 this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
33628 this._addInactiveAction(action, clipUuid, rootUuid);
33631 var bindings = action._propertyBindings; // increment reference counts / sort out state
33633 for (var i = 0, n = bindings.length; i !== n; ++i) {
33634 var binding = bindings[i];
33636 if (binding.useCount++ === 0) {
33637 this._lendBinding(binding);
33639 binding.saveOriginalState();
33643 this._lendAction(action);
33646 _deactivateAction: function _deactivateAction(action) {
33647 if (this._isActiveAction(action)) {
33648 var bindings = action._propertyBindings; // decrement reference counts / sort out state
33650 for (var i = 0, n = bindings.length; i !== n; ++i) {
33651 var binding = bindings[i];
33653 if (--binding.useCount === 0) {
33654 binding.restoreOriginalState();
33656 this._takeBackBinding(binding);
33660 this._takeBackAction(action);
33664 _initMemoryManager: function _initMemoryManager() {
33665 this._actions = []; // 'nActiveActions' followed by inactive ones
33667 this._nActiveActions = 0;
33668 this._actionsByClip = {}; // inside:
33670 // knownActions: Array< AnimationAction > - used as prototypes
33671 // actionByRoot: AnimationAction - lookup
33674 this._bindings = []; // 'nActiveBindings' followed by inactive ones
33676 this._nActiveBindings = 0;
33677 this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
33679 this._controlInterpolants = []; // same game as above
33681 this._nActiveControlInterpolants = 0;
33686 return scope._actions.length;
33690 return scope._nActiveActions;
33696 return scope._bindings.length;
33700 return scope._nActiveBindings;
33704 controlInterpolants: {
33706 return scope._controlInterpolants.length;
33710 return scope._nActiveControlInterpolants;
33716 // Memory management for AnimationAction objects
33717 _isActiveAction: function _isActiveAction(action) {
33718 var index = action._cacheIndex;
33719 return index !== null && index < this._nActiveActions;
33721 _addInactiveAction: function _addInactiveAction(action, clipUuid, rootUuid) {
33722 var actions = this._actions,
33723 actionsByClip = this._actionsByClip;
33724 var actionsForClip = actionsByClip[clipUuid];
33726 if (actionsForClip === undefined) {
33728 knownActions: [action],
33731 action._byClipCacheIndex = 0;
33732 actionsByClip[clipUuid] = actionsForClip;
33734 var knownActions = actionsForClip.knownActions;
33735 action._byClipCacheIndex = knownActions.length;
33736 knownActions.push(action);
33739 action._cacheIndex = actions.length;
33740 actions.push(action);
33741 actionsForClip.actionByRoot[rootUuid] = action;
33743 _removeInactiveAction: function _removeInactiveAction(action) {
33744 var actions = this._actions,
33745 lastInactiveAction = actions[actions.length - 1],
33746 cacheIndex = action._cacheIndex;
33747 lastInactiveAction._cacheIndex = cacheIndex;
33748 actions[cacheIndex] = lastInactiveAction;
33750 action._cacheIndex = null;
33751 var clipUuid = action._clip.uuid,
33752 actionsByClip = this._actionsByClip,
33753 actionsForClip = actionsByClip[clipUuid],
33754 knownActionsForClip = actionsForClip.knownActions,
33755 lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
33756 byClipCacheIndex = action._byClipCacheIndex;
33757 lastKnownAction._byClipCacheIndex = byClipCacheIndex;
33758 knownActionsForClip[byClipCacheIndex] = lastKnownAction;
33759 knownActionsForClip.pop();
33760 action._byClipCacheIndex = null;
33761 var actionByRoot = actionsForClip.actionByRoot,
33762 rootUuid = (action._localRoot || this._root).uuid;
33763 delete actionByRoot[rootUuid];
33765 if (knownActionsForClip.length === 0) {
33766 delete actionsByClip[clipUuid];
33769 this._removeInactiveBindingsForAction(action);
33771 _removeInactiveBindingsForAction: function _removeInactiveBindingsForAction(action) {
33772 var bindings = action._propertyBindings;
33774 for (var i = 0, n = bindings.length; i !== n; ++i) {
33775 var binding = bindings[i];
33777 if (--binding.referenceCount === 0) {
33778 this._removeInactiveBinding(binding);
33782 _lendAction: function _lendAction(action) {
33783 // [ active actions | inactive actions ]
33784 // [ active actions >| inactive actions ]
33788 var actions = this._actions,
33789 prevIndex = action._cacheIndex,
33790 lastActiveIndex = this._nActiveActions++,
33791 firstInactiveAction = actions[lastActiveIndex];
33792 action._cacheIndex = lastActiveIndex;
33793 actions[lastActiveIndex] = action;
33794 firstInactiveAction._cacheIndex = prevIndex;
33795 actions[prevIndex] = firstInactiveAction;
33797 _takeBackAction: function _takeBackAction(action) {
33798 // [ active actions | inactive actions ]
33799 // [ active actions |< inactive actions ]
33803 var actions = this._actions,
33804 prevIndex = action._cacheIndex,
33805 firstInactiveIndex = --this._nActiveActions,
33806 lastActiveAction = actions[firstInactiveIndex];
33807 action._cacheIndex = firstInactiveIndex;
33808 actions[firstInactiveIndex] = action;
33809 lastActiveAction._cacheIndex = prevIndex;
33810 actions[prevIndex] = lastActiveAction;
33812 // Memory management for PropertyMixer objects
33813 _addInactiveBinding: function _addInactiveBinding(binding, rootUuid, trackName) {
33814 var bindingsByRoot = this._bindingsByRootAndName,
33815 bindings = this._bindings;
33816 var bindingByName = bindingsByRoot[rootUuid];
33818 if (bindingByName === undefined) {
33819 bindingByName = {};
33820 bindingsByRoot[rootUuid] = bindingByName;
33823 bindingByName[trackName] = binding;
33824 binding._cacheIndex = bindings.length;
33825 bindings.push(binding);
33827 _removeInactiveBinding: function _removeInactiveBinding(binding) {
33828 var bindings = this._bindings,
33829 propBinding = binding.binding,
33830 rootUuid = propBinding.rootNode.uuid,
33831 trackName = propBinding.path,
33832 bindingsByRoot = this._bindingsByRootAndName,
33833 bindingByName = bindingsByRoot[rootUuid],
33834 lastInactiveBinding = bindings[bindings.length - 1],
33835 cacheIndex = binding._cacheIndex;
33836 lastInactiveBinding._cacheIndex = cacheIndex;
33837 bindings[cacheIndex] = lastInactiveBinding;
33839 delete bindingByName[trackName];
33841 if (Object.keys(bindingByName).length === 0) {
33842 delete bindingsByRoot[rootUuid];
33845 _lendBinding: function _lendBinding(binding) {
33846 var bindings = this._bindings,
33847 prevIndex = binding._cacheIndex,
33848 lastActiveIndex = this._nActiveBindings++,
33849 firstInactiveBinding = bindings[lastActiveIndex];
33850 binding._cacheIndex = lastActiveIndex;
33851 bindings[lastActiveIndex] = binding;
33852 firstInactiveBinding._cacheIndex = prevIndex;
33853 bindings[prevIndex] = firstInactiveBinding;
33855 _takeBackBinding: function _takeBackBinding(binding) {
33856 var bindings = this._bindings,
33857 prevIndex = binding._cacheIndex,
33858 firstInactiveIndex = --this._nActiveBindings,
33859 lastActiveBinding = bindings[firstInactiveIndex];
33860 binding._cacheIndex = firstInactiveIndex;
33861 bindings[firstInactiveIndex] = binding;
33862 lastActiveBinding._cacheIndex = prevIndex;
33863 bindings[prevIndex] = lastActiveBinding;
33865 // Memory management of Interpolants for weight and time scale
33866 _lendControlInterpolant: function _lendControlInterpolant() {
33867 var interpolants = this._controlInterpolants,
33868 lastActiveIndex = this._nActiveControlInterpolants++;
33869 var interpolant = interpolants[lastActiveIndex];
33871 if (interpolant === undefined) {
33872 interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
33873 interpolant.__cacheIndex = lastActiveIndex;
33874 interpolants[lastActiveIndex] = interpolant;
33877 return interpolant;
33879 _takeBackControlInterpolant: function _takeBackControlInterpolant(interpolant) {
33880 var interpolants = this._controlInterpolants,
33881 prevIndex = interpolant.__cacheIndex,
33882 firstInactiveIndex = --this._nActiveControlInterpolants,
33883 lastActiveInterpolant = interpolants[firstInactiveIndex];
33884 interpolant.__cacheIndex = firstInactiveIndex;
33885 interpolants[firstInactiveIndex] = interpolant;
33886 lastActiveInterpolant.__cacheIndex = prevIndex;
33887 interpolants[prevIndex] = lastActiveInterpolant;
33889 _controlInterpolantsResultBuffer: new Float32Array(1),
33890 // return an action for a clip optionally using a custom root target
33891 // object (this method allocates a lot of dynamic memory in case a
33892 // previously unknown clip/root combination is specified)
33893 clipAction: function clipAction(clip, optionalRoot, blendMode) {
33894 var root = optionalRoot || this._root,
33895 rootUuid = root.uuid;
33896 var clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
33897 var clipUuid = clipObject !== null ? clipObject.uuid : clip;
33898 var actionsForClip = this._actionsByClip[clipUuid];
33899 var prototypeAction = null;
33901 if (blendMode === undefined) {
33902 if (clipObject !== null) {
33903 blendMode = clipObject.blendMode;
33905 blendMode = NormalAnimationBlendMode;
33909 if (actionsForClip !== undefined) {
33910 var existingAction = actionsForClip.actionByRoot[rootUuid];
33912 if (existingAction !== undefined && existingAction.blendMode === blendMode) {
33913 return existingAction;
33914 } // we know the clip, so we don't have to parse all
33915 // the bindings again but can just copy
33918 prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
33920 if (clipObject === null) clipObject = prototypeAction._clip;
33921 } // clip must be known when specified via string
33924 if (clipObject === null) return null; // allocate all resources required to run it
33926 var newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
33928 this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
33931 this._addInactiveAction(newAction, clipUuid, rootUuid);
33935 // get an existing action
33936 existingAction: function existingAction(clip, optionalRoot) {
33937 var root = optionalRoot || this._root,
33938 rootUuid = root.uuid,
33939 clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
33940 clipUuid = clipObject ? clipObject.uuid : clip,
33941 actionsForClip = this._actionsByClip[clipUuid];
33943 if (actionsForClip !== undefined) {
33944 return actionsForClip.actionByRoot[rootUuid] || null;
33949 // deactivates all previously scheduled actions
33950 stopAllAction: function stopAllAction() {
33951 var actions = this._actions,
33952 nActions = this._nActiveActions;
33954 for (var i = nActions - 1; i >= 0; --i) {
33960 // advance the time and update apply the animation
33961 update: function update(deltaTime) {
33962 deltaTime *= this.timeScale;
33963 var actions = this._actions,
33964 nActions = this._nActiveActions,
33965 time = this.time += deltaTime,
33966 timeDirection = Math.sign(deltaTime),
33967 accuIndex = this._accuIndex ^= 1; // run active actions
33969 for (var i = 0; i !== nActions; ++i) {
33970 var action = actions[i];
33972 action._update(time, deltaTime, timeDirection, accuIndex);
33973 } // update scene graph
33976 var bindings = this._bindings,
33977 nBindings = this._nActiveBindings;
33979 for (var _i = 0; _i !== nBindings; ++_i) {
33980 bindings[_i].apply(accuIndex);
33985 // Allows you to seek to a specific time in an animation.
33986 setTime: function setTime(timeInSeconds) {
33987 this.time = 0; // Zero out time attribute for AnimationMixer object;
33989 for (var i = 0; i < this._actions.length; i++) {
33990 this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
33993 return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
33995 // return this mixer's root target object
33996 getRoot: function getRoot() {
33999 // free all resources specific to a particular clip
34000 uncacheClip: function uncacheClip(clip) {
34001 var actions = this._actions,
34002 clipUuid = clip.uuid,
34003 actionsByClip = this._actionsByClip,
34004 actionsForClip = actionsByClip[clipUuid];
34006 if (actionsForClip !== undefined) {
34007 // note: just calling _removeInactiveAction would mess up the
34008 // iteration state and also require updating the state we can
34010 var actionsToRemove = actionsForClip.knownActions;
34012 for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
34013 var action = actionsToRemove[i];
34015 this._deactivateAction(action);
34017 var cacheIndex = action._cacheIndex,
34018 lastInactiveAction = actions[actions.length - 1];
34019 action._cacheIndex = null;
34020 action._byClipCacheIndex = null;
34021 lastInactiveAction._cacheIndex = cacheIndex;
34022 actions[cacheIndex] = lastInactiveAction;
34025 this._removeInactiveBindingsForAction(action);
34028 delete actionsByClip[clipUuid];
34031 // free all resources specific to a particular root target object
34032 uncacheRoot: function uncacheRoot(root) {
34033 var rootUuid = root.uuid,
34034 actionsByClip = this._actionsByClip;
34036 for (var clipUuid in actionsByClip) {
34037 var actionByRoot = actionsByClip[clipUuid].actionByRoot,
34038 action = actionByRoot[rootUuid];
34040 if (action !== undefined) {
34041 this._deactivateAction(action);
34043 this._removeInactiveAction(action);
34047 var bindingsByRoot = this._bindingsByRootAndName,
34048 bindingByName = bindingsByRoot[rootUuid];
34050 if (bindingByName !== undefined) {
34051 for (var trackName in bindingByName) {
34052 var binding = bindingByName[trackName];
34053 binding.restoreOriginalState();
34055 this._removeInactiveBinding(binding);
34059 // remove a targeted clip from the cache
34060 uncacheAction: function uncacheAction(clip, optionalRoot) {
34061 var action = this.existingAction(clip, optionalRoot);
34063 if (action !== null) {
34064 this._deactivateAction(action);
34066 this._removeInactiveAction(action);
34071 var Uniform = /*#__PURE__*/function () {
34072 function Uniform(value) {
34073 if (typeof value === 'string') {
34074 console.warn('THREE.Uniform: Type parameter is no longer needed.');
34075 value = arguments[1];
34078 this.value = value;
34081 var _proto = Uniform.prototype;
34083 _proto.clone = function clone() {
34084 return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
34090 function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
34091 InterleavedBuffer.call(this, array, stride);
34092 this.meshPerAttribute = meshPerAttribute || 1;
34095 InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
34096 constructor: InstancedInterleavedBuffer,
34097 isInstancedInterleavedBuffer: true,
34098 copy: function copy(source) {
34099 InterleavedBuffer.prototype.copy.call(this, source);
34100 this.meshPerAttribute = source.meshPerAttribute;
34103 clone: function clone(data) {
34104 var ib = InterleavedBuffer.prototype.clone.call(this, data);
34105 ib.meshPerAttribute = this.meshPerAttribute;
34108 toJSON: function toJSON(data) {
34109 var json = InterleavedBuffer.prototype.toJSON.call(this, data);
34110 json.isInstancedInterleavedBuffer = true;
34111 json.meshPerAttribute = this.meshPerAttribute;
34116 function GLBufferAttribute(buffer, type, itemSize, elementSize, count) {
34117 this.buffer = buffer;
34119 this.itemSize = itemSize;
34120 this.elementSize = elementSize;
34121 this.count = count;
34125 Object.defineProperty(GLBufferAttribute.prototype, 'needsUpdate', {
34126 set: function set(value) {
34127 if (value === true) this.version++;
34130 Object.assign(GLBufferAttribute.prototype, {
34131 isGLBufferAttribute: true,
34132 setBuffer: function setBuffer(buffer) {
34133 this.buffer = buffer;
34136 setType: function setType(type, elementSize) {
34138 this.elementSize = elementSize;
34141 setItemSize: function setItemSize(itemSize) {
34142 this.itemSize = itemSize;
34145 setCount: function setCount(count) {
34146 this.count = count;
34151 function Raycaster(origin, direction, near, far) {
34152 this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
34154 this.near = near || 0;
34155 this.far = far || Infinity;
34156 this.camera = null;
34157 this.layers = new Layers();
34169 Object.defineProperties(this.params, {
34171 get: function get() {
34172 console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
34173 return this.Points;
34179 function ascSort(a, b) {
34180 return a.distance - b.distance;
34183 function _intersectObject(object, raycaster, intersects, recursive) {
34184 if (object.layers.test(raycaster.layers)) {
34185 object.raycast(raycaster, intersects);
34188 if (recursive === true) {
34189 var children = object.children;
34191 for (var i = 0, l = children.length; i < l; i++) {
34192 _intersectObject(children[i], raycaster, intersects, true);
34197 Object.assign(Raycaster.prototype, {
34198 set: function set(origin, direction) {
34199 // direction is assumed to be normalized (for accurate distance calculations)
34200 this.ray.set(origin, direction);
34202 setFromCamera: function setFromCamera(coords, camera) {
34203 if (camera && camera.isPerspectiveCamera) {
34204 this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
34205 this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
34206 this.camera = camera;
34207 } else if (camera && camera.isOrthographicCamera) {
34208 this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
34210 this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
34211 this.camera = camera;
34213 console.error('THREE.Raycaster: Unsupported camera type.');
34216 intersectObject: function intersectObject(object, recursive, optionalTarget) {
34217 var intersects = optionalTarget || [];
34219 _intersectObject(object, this, intersects, recursive);
34221 intersects.sort(ascSort);
34224 intersectObjects: function intersectObjects(objects, recursive, optionalTarget) {
34225 var intersects = optionalTarget || [];
34227 if (Array.isArray(objects) === false) {
34228 console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
34232 for (var i = 0, l = objects.length; i < l; i++) {
34233 _intersectObject(objects[i], this, intersects, recursive);
34236 intersects.sort(ascSort);
34242 * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
34244 * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
34245 * The azimuthal angle (theta) is measured from the positive z-axis.
34248 var Spherical = /*#__PURE__*/function () {
34249 function Spherical(radius, phi, theta) {
34250 if (radius === void 0) {
34254 if (phi === void 0) {
34258 if (theta === void 0) {
34262 this.radius = radius;
34263 this.phi = phi; // polar angle
34265 this.theta = theta; // azimuthal angle
34270 var _proto = Spherical.prototype;
34272 _proto.set = function set(radius, phi, theta) {
34273 this.radius = radius;
34275 this.theta = theta;
34279 _proto.clone = function clone() {
34280 return new this.constructor().copy(this);
34283 _proto.copy = function copy(other) {
34284 this.radius = other.radius;
34285 this.phi = other.phi;
34286 this.theta = other.theta;
34288 } // restrict phi to be betwee EPS and PI-EPS
34291 _proto.makeSafe = function makeSafe() {
34292 var EPS = 0.000001;
34293 this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
34297 _proto.setFromVector3 = function setFromVector3(v) {
34298 return this.setFromCartesianCoords(v.x, v.y, v.z);
34301 _proto.setFromCartesianCoords = function setFromCartesianCoords(x, y, z) {
34302 this.radius = Math.sqrt(x * x + y * y + z * z);
34304 if (this.radius === 0) {
34308 this.theta = Math.atan2(x, z);
34309 this.phi = Math.acos(MathUtils.clamp(y / this.radius, -1, 1));
34319 * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
34321 var Cylindrical = /*#__PURE__*/function () {
34322 function Cylindrical(radius, theta, y) {
34323 this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
34325 this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
34327 this.y = y !== undefined ? y : 0; // height above the x-z plane
34332 var _proto = Cylindrical.prototype;
34334 _proto.set = function set(radius, theta, y) {
34335 this.radius = radius;
34336 this.theta = theta;
34341 _proto.clone = function clone() {
34342 return new this.constructor().copy(this);
34345 _proto.copy = function copy(other) {
34346 this.radius = other.radius;
34347 this.theta = other.theta;
34352 _proto.setFromVector3 = function setFromVector3(v) {
34353 return this.setFromCartesianCoords(v.x, v.y, v.z);
34356 _proto.setFromCartesianCoords = function setFromCartesianCoords(x, y, z) {
34357 this.radius = Math.sqrt(x * x + z * z);
34358 this.theta = Math.atan2(x, z);
34363 return Cylindrical;
34366 var _vector$7 = /*@__PURE__*/new Vector2();
34368 var Box2 = /*#__PURE__*/function () {
34369 function Box2(min, max) {
34370 Object.defineProperty(this, 'isBox2', {
34373 this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
34374 this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
34377 var _proto = Box2.prototype;
34379 _proto.set = function set(min, max) {
34380 this.min.copy(min);
34381 this.max.copy(max);
34385 _proto.setFromPoints = function setFromPoints(points) {
34388 for (var i = 0, il = points.length; i < il; i++) {
34389 this.expandByPoint(points[i]);
34395 _proto.setFromCenterAndSize = function setFromCenterAndSize(center, size) {
34396 var halfSize = _vector$7.copy(size).multiplyScalar(0.5);
34398 this.min.copy(center).sub(halfSize);
34399 this.max.copy(center).add(halfSize);
34403 _proto.clone = function clone() {
34404 return new this.constructor().copy(this);
34407 _proto.copy = function copy(box) {
34408 this.min.copy(box.min);
34409 this.max.copy(box.max);
34413 _proto.makeEmpty = function makeEmpty() {
34414 this.min.x = this.min.y = +Infinity;
34415 this.max.x = this.max.y = -Infinity;
34419 _proto.isEmpty = function isEmpty() {
34420 // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
34421 return this.max.x < this.min.x || this.max.y < this.min.y;
34424 _proto.getCenter = function getCenter(target) {
34425 if (target === undefined) {
34426 console.warn('THREE.Box2: .getCenter() target is now required');
34427 target = new Vector2();
34430 return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
34433 _proto.getSize = function getSize(target) {
34434 if (target === undefined) {
34435 console.warn('THREE.Box2: .getSize() target is now required');
34436 target = new Vector2();
34439 return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
34442 _proto.expandByPoint = function expandByPoint(point) {
34443 this.min.min(point);
34444 this.max.max(point);
34448 _proto.expandByVector = function expandByVector(vector) {
34449 this.min.sub(vector);
34450 this.max.add(vector);
34454 _proto.expandByScalar = function expandByScalar(scalar) {
34455 this.min.addScalar(-scalar);
34456 this.max.addScalar(scalar);
34460 _proto.containsPoint = function containsPoint(point) {
34461 return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
34464 _proto.containsBox = function containsBox(box) {
34465 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;
34468 _proto.getParameter = function getParameter(point, target) {
34469 // This can potentially have a divide by zero if the box
34470 // has a size dimension of 0.
34471 if (target === undefined) {
34472 console.warn('THREE.Box2: .getParameter() target is now required');
34473 target = new Vector2();
34476 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));
34479 _proto.intersectsBox = function intersectsBox(box) {
34480 // using 4 splitting planes to rule out intersections
34481 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;
34484 _proto.clampPoint = function clampPoint(point, target) {
34485 if (target === undefined) {
34486 console.warn('THREE.Box2: .clampPoint() target is now required');
34487 target = new Vector2();
34490 return target.copy(point).clamp(this.min, this.max);
34493 _proto.distanceToPoint = function distanceToPoint(point) {
34494 var clampedPoint = _vector$7.copy(point).clamp(this.min, this.max);
34496 return clampedPoint.sub(point).length();
34499 _proto.intersect = function intersect(box) {
34500 this.min.max(box.min);
34501 this.max.min(box.max);
34505 _proto.union = function union(box) {
34506 this.min.min(box.min);
34507 this.max.max(box.max);
34511 _proto.translate = function translate(offset) {
34512 this.min.add(offset);
34513 this.max.add(offset);
34517 _proto.equals = function equals(box) {
34518 return box.min.equals(this.min) && box.max.equals(this.max);
34524 var _startP = /*@__PURE__*/new Vector3();
34526 var _startEnd = /*@__PURE__*/new Vector3();
34528 var Line3 = /*#__PURE__*/function () {
34529 function Line3(start, end) {
34530 this.start = start !== undefined ? start : new Vector3();
34531 this.end = end !== undefined ? end : new Vector3();
34534 var _proto = Line3.prototype;
34536 _proto.set = function set(start, end) {
34537 this.start.copy(start);
34538 this.end.copy(end);
34542 _proto.clone = function clone() {
34543 return new this.constructor().copy(this);
34546 _proto.copy = function copy(line) {
34547 this.start.copy(line.start);
34548 this.end.copy(line.end);
34552 _proto.getCenter = function getCenter(target) {
34553 if (target === undefined) {
34554 console.warn('THREE.Line3: .getCenter() target is now required');
34555 target = new Vector3();
34558 return target.addVectors(this.start, this.end).multiplyScalar(0.5);
34561 _proto.delta = function delta(target) {
34562 if (target === undefined) {
34563 console.warn('THREE.Line3: .delta() target is now required');
34564 target = new Vector3();
34567 return target.subVectors(this.end, this.start);
34570 _proto.distanceSq = function distanceSq() {
34571 return this.start.distanceToSquared(this.end);
34574 _proto.distance = function distance() {
34575 return this.start.distanceTo(this.end);
34578 _proto.at = function at(t, target) {
34579 if (target === undefined) {
34580 console.warn('THREE.Line3: .at() target is now required');
34581 target = new Vector3();
34584 return this.delta(target).multiplyScalar(t).add(this.start);
34587 _proto.closestPointToPointParameter = function closestPointToPointParameter(point, clampToLine) {
34588 _startP.subVectors(point, this.start);
34590 _startEnd.subVectors(this.end, this.start);
34592 var startEnd2 = _startEnd.dot(_startEnd);
34594 var startEnd_startP = _startEnd.dot(_startP);
34596 var t = startEnd_startP / startEnd2;
34599 t = MathUtils.clamp(t, 0, 1);
34605 _proto.closestPointToPoint = function closestPointToPoint(point, clampToLine, target) {
34606 var t = this.closestPointToPointParameter(point, clampToLine);
34608 if (target === undefined) {
34609 console.warn('THREE.Line3: .closestPointToPoint() target is now required');
34610 target = new Vector3();
34613 return this.delta(target).multiplyScalar(t).add(this.start);
34616 _proto.applyMatrix4 = function applyMatrix4(matrix) {
34617 this.start.applyMatrix4(matrix);
34618 this.end.applyMatrix4(matrix);
34622 _proto.equals = function equals(line) {
34623 return line.start.equals(this.start) && line.end.equals(this.end);
34629 function ImmediateRenderObject(material) {
34630 Object3D.call(this);
34631 this.material = material;
34633 this.render = function ()
34634 /* renderCallback */
34637 this.hasPositions = false;
34638 this.hasNormals = false;
34639 this.hasColors = false;
34640 this.hasUvs = false;
34641 this.positionArray = null;
34642 this.normalArray = null;
34643 this.colorArray = null;
34644 this.uvArray = null;
34648 ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
34649 ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
34650 ImmediateRenderObject.prototype.isImmediateRenderObject = true;
34652 var _vector$8 = /*@__PURE__*/new Vector3();
34654 var SpotLightHelper = /*#__PURE__*/function (_Object3D) {
34655 _inheritsLoose(SpotLightHelper, _Object3D);
34657 function SpotLightHelper(light, color) {
34660 _this = _Object3D.call(this) || this;
34661 _this.light = light;
34663 _this.light.updateMatrixWorld();
34665 _this.matrix = light.matrixWorld;
34666 _this.matrixAutoUpdate = false;
34667 _this.color = color;
34668 var geometry = new BufferGeometry();
34669 var 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];
34671 for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
34672 var p1 = i / l * Math.PI * 2;
34673 var p2 = j / l * Math.PI * 2;
34674 positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
34677 geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
34678 var material = new LineBasicMaterial({
34682 _this.cone = new LineSegments(geometry, material);
34684 _this.add(_this.cone);
34691 var _proto = SpotLightHelper.prototype;
34693 _proto.dispose = function dispose() {
34694 this.cone.geometry.dispose();
34695 this.cone.material.dispose();
34698 _proto.update = function update() {
34699 this.light.updateMatrixWorld();
34700 var coneLength = this.light.distance ? this.light.distance : 1000;
34701 var coneWidth = coneLength * Math.tan(this.light.angle);
34702 this.cone.scale.set(coneWidth, coneWidth, coneLength);
34704 _vector$8.setFromMatrixPosition(this.light.target.matrixWorld);
34706 this.cone.lookAt(_vector$8);
34708 if (this.color !== undefined) {
34709 this.cone.material.color.set(this.color);
34711 this.cone.material.color.copy(this.light.color);
34715 return SpotLightHelper;
34718 var _vector$9 = /*@__PURE__*/new Vector3();
34720 var _boneMatrix = /*@__PURE__*/new Matrix4();
34722 var _matrixWorldInv = /*@__PURE__*/new Matrix4();
34724 var SkeletonHelper = /*#__PURE__*/function (_LineSegments) {
34725 _inheritsLoose(SkeletonHelper, _LineSegments);
34727 function SkeletonHelper(object) {
34730 var bones = getBoneList(object);
34731 var geometry = new BufferGeometry();
34734 var color1 = new Color(0, 0, 1);
34735 var color2 = new Color(0, 1, 0);
34737 for (var i = 0; i < bones.length; i++) {
34738 var bone = bones[i];
34740 if (bone.parent && bone.parent.isBone) {
34741 vertices.push(0, 0, 0);
34742 vertices.push(0, 0, 0);
34743 colors.push(color1.r, color1.g, color1.b);
34744 colors.push(color2.r, color2.g, color2.b);
34748 geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
34749 geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
34750 var material = new LineBasicMaterial({
34751 vertexColors: true,
34757 _this = _LineSegments.call(this, geometry, material) || this;
34758 _this.type = 'SkeletonHelper';
34759 _this.isSkeletonHelper = true;
34760 _this.root = object;
34761 _this.bones = bones;
34762 _this.matrix = object.matrixWorld;
34763 _this.matrixAutoUpdate = false;
34767 var _proto = SkeletonHelper.prototype;
34769 _proto.updateMatrixWorld = function updateMatrixWorld(force) {
34770 var bones = this.bones;
34771 var geometry = this.geometry;
34772 var position = geometry.getAttribute('position');
34774 _matrixWorldInv.copy(this.root.matrixWorld).invert();
34776 for (var i = 0, j = 0; i < bones.length; i++) {
34777 var bone = bones[i];
34779 if (bone.parent && bone.parent.isBone) {
34780 _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
34782 _vector$9.setFromMatrixPosition(_boneMatrix);
34784 position.setXYZ(j, _vector$9.x, _vector$9.y, _vector$9.z);
34786 _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
34788 _vector$9.setFromMatrixPosition(_boneMatrix);
34790 position.setXYZ(j + 1, _vector$9.x, _vector$9.y, _vector$9.z);
34795 geometry.getAttribute('position').needsUpdate = true;
34797 _LineSegments.prototype.updateMatrixWorld.call(this, force);
34800 return SkeletonHelper;
34803 function getBoneList(object) {
34806 if (object && object.isBone) {
34807 boneList.push(object);
34810 for (var i = 0; i < object.children.length; i++) {
34811 boneList.push.apply(boneList, getBoneList(object.children[i]));
34817 var PointLightHelper = /*#__PURE__*/function (_Mesh) {
34818 _inheritsLoose(PointLightHelper, _Mesh);
34820 function PointLightHelper(light, sphereSize, color) {
34823 var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
34824 var material = new MeshBasicMaterial({
34829 _this = _Mesh.call(this, geometry, material) || this;
34830 _this.light = light;
34832 _this.light.updateMatrixWorld();
34834 _this.color = color;
34835 _this.type = 'PointLightHelper';
34836 _this.matrix = _this.light.matrixWorld;
34837 _this.matrixAutoUpdate = false;
34841 // TODO: delete this comment?
34842 const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
34843 const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
34844 this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
34845 this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
34846 const d = light.distance;
34848 this.lightDistance.visible = false;
34850 this.lightDistance.scale.set( d, d, d );
34852 this.add( this.lightDistance );
34859 var _proto = PointLightHelper.prototype;
34861 _proto.dispose = function dispose() {
34862 this.geometry.dispose();
34863 this.material.dispose();
34866 _proto.update = function update() {
34867 if (this.color !== undefined) {
34868 this.material.color.set(this.color);
34870 this.material.color.copy(this.light.color);
34873 const d = this.light.distance;
34875 this.lightDistance.visible = false;
34877 this.lightDistance.visible = true;
34878 this.lightDistance.scale.set( d, d, d );
34884 return PointLightHelper;
34887 var _vector$a = /*@__PURE__*/new Vector3();
34889 var _color1 = /*@__PURE__*/new Color();
34891 var _color2 = /*@__PURE__*/new Color();
34893 var HemisphereLightHelper = /*#__PURE__*/function (_Object3D) {
34894 _inheritsLoose(HemisphereLightHelper, _Object3D);
34896 function HemisphereLightHelper(light, size, color) {
34899 _this = _Object3D.call(this) || this;
34900 _this.light = light;
34902 _this.light.updateMatrixWorld();
34904 _this.matrix = light.matrixWorld;
34905 _this.matrixAutoUpdate = false;
34906 _this.color = color;
34907 var geometry = new OctahedronBufferGeometry(size);
34908 geometry.rotateY(Math.PI * 0.5);
34909 _this.material = new MeshBasicMaterial({
34914 if (_this.color === undefined) _this.material.vertexColors = true;
34915 var position = geometry.getAttribute('position');
34916 var colors = new Float32Array(position.count * 3);
34917 geometry.setAttribute('color', new BufferAttribute(colors, 3));
34919 _this.add(new Mesh(geometry, _this.material));
34926 var _proto = HemisphereLightHelper.prototype;
34928 _proto.dispose = function dispose() {
34929 this.children[0].geometry.dispose();
34930 this.children[0].material.dispose();
34933 _proto.update = function update() {
34934 var mesh = this.children[0];
34936 if (this.color !== undefined) {
34937 this.material.color.set(this.color);
34939 var colors = mesh.geometry.getAttribute('color');
34941 _color1.copy(this.light.color);
34943 _color2.copy(this.light.groundColor);
34945 for (var i = 0, l = colors.count; i < l; i++) {
34946 var color = i < l / 2 ? _color1 : _color2;
34947 colors.setXYZ(i, color.r, color.g, color.b);
34950 colors.needsUpdate = true;
34953 mesh.lookAt(_vector$a.setFromMatrixPosition(this.light.matrixWorld).negate());
34956 return HemisphereLightHelper;
34959 var GridHelper = /*#__PURE__*/function (_LineSegments) {
34960 _inheritsLoose(GridHelper, _LineSegments);
34962 function GridHelper(size, divisions, color1, color2) {
34965 if (size === void 0) {
34969 if (divisions === void 0) {
34973 if (color1 === void 0) {
34977 if (color2 === void 0) {
34981 color1 = new Color(color1);
34982 color2 = new Color(color2);
34983 var center = divisions / 2;
34984 var step = size / divisions;
34985 var halfSize = size / 2;
34989 for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
34990 vertices.push(-halfSize, 0, k, halfSize, 0, k);
34991 vertices.push(k, 0, -halfSize, k, 0, halfSize);
34992 var color = i === center ? color1 : color2;
34993 color.toArray(colors, j);
34995 color.toArray(colors, j);
34997 color.toArray(colors, j);
34999 color.toArray(colors, j);
35003 var geometry = new BufferGeometry();
35004 geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
35005 geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
35006 var material = new LineBasicMaterial({
35007 vertexColors: true,
35010 _this = _LineSegments.call(this, geometry, material) || this;
35011 _this.type = 'GridHelper';
35018 var PolarGridHelper = /*#__PURE__*/function (_LineSegments) {
35019 _inheritsLoose(PolarGridHelper, _LineSegments);
35021 function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
35024 if (radius === void 0) {
35028 if (radials === void 0) {
35032 if (circles === void 0) {
35036 if (divisions === void 0) {
35040 if (color1 === void 0) {
35044 if (color2 === void 0) {
35048 color1 = new Color(color1);
35049 color2 = new Color(color2);
35051 var colors = []; // create the radials
35053 for (var i = 0; i <= radials; i++) {
35054 var v = i / radials * (Math.PI * 2);
35055 var x = Math.sin(v) * radius;
35056 var z = Math.cos(v) * radius;
35057 vertices.push(0, 0, 0);
35058 vertices.push(x, 0, z);
35059 var color = i & 1 ? color1 : color2;
35060 colors.push(color.r, color.g, color.b);
35061 colors.push(color.r, color.g, color.b);
35062 } // create the circles
35065 for (var _i = 0; _i <= circles; _i++) {
35066 var _color = _i & 1 ? color1 : color2;
35068 var r = radius - radius / circles * _i;
35070 for (var j = 0; j < divisions; j++) {
35072 var _v = j / divisions * (Math.PI * 2);
35074 var _x = Math.sin(_v) * r;
35076 var _z = Math.cos(_v) * r;
35078 vertices.push(_x, 0, _z);
35079 colors.push(_color.r, _color.g, _color.b); // second vertex
35081 _v = (j + 1) / divisions * (Math.PI * 2);
35082 _x = Math.sin(_v) * r;
35083 _z = Math.cos(_v) * r;
35084 vertices.push(_x, 0, _z);
35085 colors.push(_color.r, _color.g, _color.b);
35089 var geometry = new BufferGeometry();
35090 geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
35091 geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
35092 var material = new LineBasicMaterial({
35093 vertexColors: true,
35096 _this = _LineSegments.call(this, geometry, material) || this;
35097 _this.type = 'PolarGridHelper';
35101 return PolarGridHelper;
35104 var _v1$6 = /*@__PURE__*/new Vector3();
35106 var _v2$3 = /*@__PURE__*/new Vector3();
35108 var _v3$1 = /*@__PURE__*/new Vector3();
35110 var DirectionalLightHelper = /*#__PURE__*/function (_Object3D) {
35111 _inheritsLoose(DirectionalLightHelper, _Object3D);
35113 function DirectionalLightHelper(light, size, color) {
35116 _this = _Object3D.call(this) || this;
35117 _this.light = light;
35119 _this.light.updateMatrixWorld();
35121 _this.matrix = light.matrixWorld;
35122 _this.matrixAutoUpdate = false;
35123 _this.color = color;
35124 if (size === undefined) size = 1;
35125 var geometry = new BufferGeometry();
35126 geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
35127 var material = new LineBasicMaterial({
35131 _this.lightPlane = new Line(geometry, material);
35133 _this.add(_this.lightPlane);
35135 geometry = new BufferGeometry();
35136 geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
35137 _this.targetLine = new Line(geometry, material);
35139 _this.add(_this.targetLine);
35146 var _proto = DirectionalLightHelper.prototype;
35148 _proto.dispose = function dispose() {
35149 this.lightPlane.geometry.dispose();
35150 this.lightPlane.material.dispose();
35151 this.targetLine.geometry.dispose();
35152 this.targetLine.material.dispose();
35155 _proto.update = function update() {
35156 _v1$6.setFromMatrixPosition(this.light.matrixWorld);
35158 _v2$3.setFromMatrixPosition(this.light.target.matrixWorld);
35160 _v3$1.subVectors(_v2$3, _v1$6);
35162 this.lightPlane.lookAt(_v2$3);
35164 if (this.color !== undefined) {
35165 this.lightPlane.material.color.set(this.color);
35166 this.targetLine.material.color.set(this.color);
35168 this.lightPlane.material.color.copy(this.light.color);
35169 this.targetLine.material.color.copy(this.light.color);
35172 this.targetLine.lookAt(_v2$3);
35173 this.targetLine.scale.z = _v3$1.length();
35176 return DirectionalLightHelper;
35179 var _vector$b = /*@__PURE__*/new Vector3();
35181 var _camera = /*@__PURE__*/new Camera();
35183 * - shows frustum, line of sight and up of the camera
35184 * - suitable for fast updates
35185 * - based on frustum visualization in lightgl.js shadowmap example
35186 * http://evanw.github.com/lightgl.js/tests/shadowmap.html
35190 var CameraHelper = /*#__PURE__*/function (_LineSegments) {
35191 _inheritsLoose(CameraHelper, _LineSegments);
35193 function CameraHelper(camera) {
35196 var geometry = new BufferGeometry();
35197 var material = new LineBasicMaterial({
35199 vertexColors: true,
35204 var pointMap = {}; // colors
35206 var colorFrustum = new Color(0xffaa00);
35207 var colorCone = new Color(0xff0000);
35208 var colorUp = new Color(0x00aaff);
35209 var colorTarget = new Color(0xffffff);
35210 var colorCross = new Color(0x333333); // near
35212 addLine('n1', 'n2', colorFrustum);
35213 addLine('n2', 'n4', colorFrustum);
35214 addLine('n4', 'n3', colorFrustum);
35215 addLine('n3', 'n1', colorFrustum); // far
35217 addLine('f1', 'f2', colorFrustum);
35218 addLine('f2', 'f4', colorFrustum);
35219 addLine('f4', 'f3', colorFrustum);
35220 addLine('f3', 'f1', colorFrustum); // sides
35222 addLine('n1', 'f1', colorFrustum);
35223 addLine('n2', 'f2', colorFrustum);
35224 addLine('n3', 'f3', colorFrustum);
35225 addLine('n4', 'f4', colorFrustum); // cone
35227 addLine('p', 'n1', colorCone);
35228 addLine('p', 'n2', colorCone);
35229 addLine('p', 'n3', colorCone);
35230 addLine('p', 'n4', colorCone); // up
35232 addLine('u1', 'u2', colorUp);
35233 addLine('u2', 'u3', colorUp);
35234 addLine('u3', 'u1', colorUp); // target
35236 addLine('c', 't', colorTarget);
35237 addLine('p', 'c', colorCross); // cross
35239 addLine('cn1', 'cn2', colorCross);
35240 addLine('cn3', 'cn4', colorCross);
35241 addLine('cf1', 'cf2', colorCross);
35242 addLine('cf3', 'cf4', colorCross);
35244 function addLine(a, b, color) {
35245 addPoint(a, color);
35246 addPoint(b, color);
35249 function addPoint(id, color) {
35250 vertices.push(0, 0, 0);
35251 colors.push(color.r, color.g, color.b);
35253 if (pointMap[id] === undefined) {
35257 pointMap[id].push(vertices.length / 3 - 1);
35260 geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
35261 geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
35262 _this = _LineSegments.call(this, geometry, material) || this;
35263 _this.type = 'CameraHelper';
35264 _this.camera = camera;
35265 if (_this.camera.updateProjectionMatrix) _this.camera.updateProjectionMatrix();
35266 _this.matrix = camera.matrixWorld;
35267 _this.matrixAutoUpdate = false;
35268 _this.pointMap = pointMap;
35275 var _proto = CameraHelper.prototype;
35277 _proto.update = function update() {
35278 var geometry = this.geometry;
35279 var pointMap = this.pointMap;
35281 h = 1; // we need just camera projection matrix inverse
35282 // world matrix must be identity
35284 _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
35287 setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
35288 setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
35290 setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
35291 setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
35292 setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
35293 setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
35295 setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
35296 setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
35297 setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
35298 setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
35300 setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
35301 setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
35302 setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
35304 setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
35305 setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
35306 setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
35307 setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
35308 setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
35309 setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
35310 setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
35311 setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
35312 geometry.getAttribute('position').needsUpdate = true;
35315 return CameraHelper;
35318 function setPoint(point, pointMap, geometry, camera, x, y, z) {
35319 _vector$b.set(x, y, z).unproject(camera);
35321 var points = pointMap[point];
35323 if (points !== undefined) {
35324 var position = geometry.getAttribute('position');
35326 for (var i = 0, l = points.length; i < l; i++) {
35327 position.setXYZ(points[i], _vector$b.x, _vector$b.y, _vector$b.z);
35332 var _box$3 = /*@__PURE__*/new Box3();
35334 var BoxHelper = /*#__PURE__*/function (_LineSegments) {
35335 _inheritsLoose(BoxHelper, _LineSegments);
35337 function BoxHelper(object, color) {
35340 if (color === void 0) {
35344 var 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]);
35345 var positions = new Float32Array(8 * 3);
35346 var geometry = new BufferGeometry();
35347 geometry.setIndex(new BufferAttribute(indices, 1));
35348 geometry.setAttribute('position', new BufferAttribute(positions, 3));
35349 _this = _LineSegments.call(this, geometry, new LineBasicMaterial({
35353 _this.object = object;
35354 _this.type = 'BoxHelper';
35355 _this.matrixAutoUpdate = false;
35362 var _proto = BoxHelper.prototype;
35364 _proto.update = function update(object) {
35365 if (object !== undefined) {
35366 console.warn('THREE.BoxHelper: .update() has no longer arguments.');
35369 if (this.object !== undefined) {
35370 _box$3.setFromObject(this.object);
35373 if (_box$3.isEmpty()) return;
35374 var min = _box$3.min;
35375 var max = _box$3.max;
35381 0: max.x, max.y, max.z
35382 1: min.x, max.y, max.z
35383 2: min.x, min.y, max.z
35384 3: max.x, min.y, max.z
35385 4: max.x, max.y, min.z
35386 5: min.x, max.y, min.z
35387 6: min.x, min.y, min.z
35388 7: max.x, min.y, min.z
35391 var position = this.geometry.attributes.position;
35392 var array = position.array;
35417 position.needsUpdate = true;
35418 this.geometry.computeBoundingSphere();
35421 _proto.setFromObject = function setFromObject(object) {
35422 this.object = object;
35427 _proto.copy = function copy(source) {
35428 LineSegments.prototype.copy.call(this, source);
35429 this.object = source.object;
35436 var Box3Helper = /*#__PURE__*/function (_LineSegments) {
35437 _inheritsLoose(Box3Helper, _LineSegments);
35439 function Box3Helper(box, color) {
35442 if (color === void 0) {
35446 var 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]);
35447 var 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];
35448 var geometry = new BufferGeometry();
35449 geometry.setIndex(new BufferAttribute(indices, 1));
35450 geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
35451 _this = _LineSegments.call(this, geometry, new LineBasicMaterial({
35456 _this.type = 'Box3Helper';
35458 _this.geometry.computeBoundingSphere();
35463 var _proto = Box3Helper.prototype;
35465 _proto.updateMatrixWorld = function updateMatrixWorld(force) {
35466 var box = this.box;
35467 if (box.isEmpty()) return;
35468 box.getCenter(this.position);
35469 box.getSize(this.scale);
35470 this.scale.multiplyScalar(0.5);
35472 _LineSegments.prototype.updateMatrixWorld.call(this, force);
35478 var PlaneHelper = /*#__PURE__*/function (_Line) {
35479 _inheritsLoose(PlaneHelper, _Line);
35481 function PlaneHelper(plane, size, hex) {
35484 if (size === void 0) {
35488 if (hex === void 0) {
35493 var 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];
35494 var geometry = new BufferGeometry();
35495 geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
35496 geometry.computeBoundingSphere();
35497 _this = _Line.call(this, geometry, new LineBasicMaterial({
35501 _this.type = 'PlaneHelper';
35502 _this.plane = plane;
35504 var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
35505 var geometry2 = new BufferGeometry();
35506 geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
35507 geometry2.computeBoundingSphere();
35509 _this.add(new Mesh(geometry2, new MeshBasicMaterial({
35520 var _proto = PlaneHelper.prototype;
35522 _proto.updateMatrixWorld = function updateMatrixWorld(force) {
35523 var scale = -this.plane.constant;
35524 if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
35526 this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
35527 this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
35529 this.lookAt(this.plane.normal);
35531 _Line.prototype.updateMatrixWorld.call(this, force);
35534 return PlaneHelper;
35537 var _axis = /*@__PURE__*/new Vector3();
35539 var _lineGeometry, _coneGeometry;
35541 var ArrowHelper = /*#__PURE__*/function (_Object3D) {
35542 _inheritsLoose(ArrowHelper, _Object3D);
35544 function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
35547 _this = _Object3D.call(this) || this; // dir is assumed to be normalized
35549 _this.type = 'ArrowHelper';
35550 if (dir === undefined) dir = new Vector3(0, 0, 1);
35551 if (origin === undefined) origin = new Vector3(0, 0, 0);
35552 if (length === undefined) length = 1;
35553 if (color === undefined) color = 0xffff00;
35554 if (headLength === undefined) headLength = 0.2 * length;
35555 if (headWidth === undefined) headWidth = 0.2 * headLength;
35557 if (_lineGeometry === undefined) {
35558 _lineGeometry = new BufferGeometry();
35560 _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
35562 _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
35564 _coneGeometry.translate(0, -0.5, 0);
35567 _this.position.copy(origin);
35569 _this.line = new Line(_lineGeometry, new LineBasicMaterial({
35573 _this.line.matrixAutoUpdate = false;
35575 _this.add(_this.line);
35577 _this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
35581 _this.cone.matrixAutoUpdate = false;
35583 _this.add(_this.cone);
35585 _this.setDirection(dir);
35587 _this.setLength(length, headLength, headWidth);
35592 var _proto = ArrowHelper.prototype;
35594 _proto.setDirection = function setDirection(dir) {
35595 // dir is assumed to be normalized
35596 if (dir.y > 0.99999) {
35597 this.quaternion.set(0, 0, 0, 1);
35598 } else if (dir.y < -0.99999) {
35599 this.quaternion.set(1, 0, 0, 0);
35601 _axis.set(dir.z, 0, -dir.x).normalize();
35603 var radians = Math.acos(dir.y);
35604 this.quaternion.setFromAxisAngle(_axis, radians);
35608 _proto.setLength = function setLength(length, headLength, headWidth) {
35609 if (headLength === undefined) headLength = 0.2 * length;
35610 if (headWidth === undefined) headWidth = 0.2 * headLength;
35611 this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
35613 this.line.updateMatrix();
35614 this.cone.scale.set(headWidth, headLength, headWidth);
35615 this.cone.position.y = length;
35616 this.cone.updateMatrix();
35619 _proto.setColor = function setColor(color) {
35620 this.line.material.color.set(color);
35621 this.cone.material.color.set(color);
35624 _proto.copy = function copy(source) {
35625 _Object3D.prototype.copy.call(this, source, false);
35627 this.line.copy(source.line);
35628 this.cone.copy(source.cone);
35632 return ArrowHelper;
35635 var AxesHelper = /*#__PURE__*/function (_LineSegments) {
35636 _inheritsLoose(AxesHelper, _LineSegments);
35638 function AxesHelper(size) {
35641 if (size === void 0) {
35645 var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
35646 var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
35647 var geometry = new BufferGeometry();
35648 geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
35649 geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
35650 var material = new LineBasicMaterial({
35651 vertexColors: true,
35654 _this = _LineSegments.call(this, geometry, material) || this;
35655 _this.type = 'AxesHelper';
35662 var _floatView = new Float32Array(1);
35664 var _int32View = new Int32Array(_floatView.buffer);
35667 // Converts float32 to float16 (stored as uint16 value).
35668 toHalfFloat: function toHalfFloat(val) {
35669 // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
35671 /* This method is faster than the OpenEXR implementation (very often
35672 * used, eg. in Ogre), with the additional benefit of rounding, inspired
35673 * by James Tursa?s half-precision code. */
35674 _floatView[0] = val;
35675 var x = _int32View[0];
35676 var bits = x >> 16 & 0x8000;
35679 var m = x >> 12 & 0x07ff;
35680 /* Keep one extra bit for rounding */
35682 var e = x >> 23 & 0xff;
35683 /* Using int is faster here */
35685 /* If zero, or denormal, or exponent underflows too much for a denormal
35686 * half, return signed zero. */
35688 if (e < 103) return bits;
35689 /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
35693 /* If exponent was 0xff and one mantissa bit was set, it means NaN,
35694 * not Inf, so make sure we set one mantissa bit too. */
35696 bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
35699 /* If exponent underflows but not too much, return a denormal */
35704 /* Extra rounding may overflow and set mantissa to 0 and exponent
35705 * to 1, which is OK. */
35707 bits |= (m >> 114 - e) + (m >> 113 - e & 1);
35711 bits |= e - 112 << 10 | m >> 1;
35712 /* Extra rounding. An overflow will set mantissa to 0 and increment
35713 * the exponent, which is OK. */
35723 var SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
35724 // chosen to approximate a Trowbridge-Reitz distribution function times the
35725 // geometric shadowing function. These sigma values squared must match the
35726 // variance #defines in cube_uv_reflection_fragment.glsl.js.
35728 var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
35729 var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
35730 // samples and exit early, but not recompile the shader.
35732 var MAX_SAMPLES = 20;
35733 var ENCODINGS = (_ENCODINGS = {}, _ENCODINGS[LinearEncoding] = 0, _ENCODINGS[sRGBEncoding] = 1, _ENCODINGS[RGBEEncoding] = 2, _ENCODINGS[RGBM7Encoding] = 3, _ENCODINGS[RGBM16Encoding] = 4, _ENCODINGS[RGBDEncoding] = 5, _ENCODINGS[GammaEncoding] = 6, _ENCODINGS);
35735 var _flatCamera = /*@__PURE__*/new OrthographicCamera();
35737 var _createPlanes2 = /*@__PURE__*/_createPlanes(),
35738 _lodPlanes = _createPlanes2._lodPlanes,
35739 _sizeLods = _createPlanes2._sizeLods,
35740 _sigmas = _createPlanes2._sigmas;
35742 var _oldTarget = null; // Golden Ratio
35744 var PHI = (1 + Math.sqrt(5)) / 2;
35745 var INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
35746 // same axis), used as axis directions evenly spread on a sphere.
35748 var _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)];
35750 * This class generates a Prefiltered, Mipmapped Radiance Environment Map
35751 * (PMREM) from a cubeMap environment texture. This allows different levels of
35752 * blur to be quickly accessed based on material roughness. It is packed into a
35753 * special CubeUV format that allows us to perform custom interpolation so that
35754 * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
35755 * chain, it only goes down to the LOD_MIN level (above), and then creates extra
35756 * even more filtered 'mips' at the same LOD_MIN resolution, associated with
35757 * higher roughness levels. In this way we maintain resolution to smoothly
35758 * interpolate diffuse lighting while limiting sampling computation.
35761 var PMREMGenerator = /*#__PURE__*/function () {
35762 function PMREMGenerator(renderer) {
35763 this._renderer = renderer;
35764 this._pingPongRenderTarget = null;
35765 this._blurMaterial = _getBlurShader(MAX_SAMPLES);
35766 this._equirectShader = null;
35767 this._cubemapShader = null;
35769 this._compileMaterial(this._blurMaterial);
35772 * Generates a PMREM from a supplied Scene, which can be faster than using an
35773 * image if networking bandwidth is low. Optional sigma specifies a blur radius
35774 * in radians to be applied to the scene before PMREM generation. Optional near
35775 * and far planes ensure the scene is rendered in its entirety (the cubeCamera
35776 * is placed at the origin).
35780 var _proto = PMREMGenerator.prototype;
35782 _proto.fromScene = function fromScene(scene, sigma, near, far) {
35783 if (sigma === void 0) {
35787 if (near === void 0) {
35791 if (far === void 0) {
35795 _oldTarget = this._renderer.getRenderTarget();
35797 var cubeUVRenderTarget = this._allocateTargets();
35799 this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
35802 this._blur(cubeUVRenderTarget, 0, 0, sigma);
35805 this._applyPMREM(cubeUVRenderTarget);
35807 this._cleanup(cubeUVRenderTarget);
35809 return cubeUVRenderTarget;
35812 * Generates a PMREM from an equirectangular texture, which can be either LDR
35813 * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
35814 * as this matches best with the 256 x 256 cubemap output.
35818 _proto.fromEquirectangular = function fromEquirectangular(equirectangular) {
35819 return this._fromTexture(equirectangular);
35822 * Generates a PMREM from an cubemap texture, which can be either LDR
35823 * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
35824 * as this matches best with the 256 x 256 cubemap output.
35828 _proto.fromCubemap = function fromCubemap(cubemap) {
35829 return this._fromTexture(cubemap);
35832 * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
35833 * your texture's network fetch for increased concurrency.
35837 _proto.compileCubemapShader = function compileCubemapShader() {
35838 if (this._cubemapShader === null) {
35839 this._cubemapShader = _getCubemapShader();
35841 this._compileMaterial(this._cubemapShader);
35845 * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
35846 * your texture's network fetch for increased concurrency.
35850 _proto.compileEquirectangularShader = function compileEquirectangularShader() {
35851 if (this._equirectShader === null) {
35852 this._equirectShader = _getEquirectShader();
35854 this._compileMaterial(this._equirectShader);
35858 * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
35859 * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
35860 * one of them will cause any others to also become unusable.
35864 _proto.dispose = function dispose() {
35865 this._blurMaterial.dispose();
35867 if (this._cubemapShader !== null) this._cubemapShader.dispose();
35868 if (this._equirectShader !== null) this._equirectShader.dispose();
35870 for (var i = 0; i < _lodPlanes.length; i++) {
35871 _lodPlanes[i].dispose();
35873 } // private interface
35876 _proto._cleanup = function _cleanup(outputTarget) {
35877 this._pingPongRenderTarget.dispose();
35879 this._renderer.setRenderTarget(_oldTarget);
35881 outputTarget.scissorTest = false;
35883 _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
35886 _proto._fromTexture = function _fromTexture(texture) {
35887 _oldTarget = this._renderer.getRenderTarget();
35889 var cubeUVRenderTarget = this._allocateTargets(texture);
35891 this._textureToCubeUV(texture, cubeUVRenderTarget);
35893 this._applyPMREM(cubeUVRenderTarget);
35895 this._cleanup(cubeUVRenderTarget);
35897 return cubeUVRenderTarget;
35900 _proto._allocateTargets = function _allocateTargets(texture) {
35901 // warning: null texture is valid
35903 magFilter: NearestFilter,
35904 minFilter: NearestFilter,
35905 generateMipmaps: false,
35906 type: UnsignedByteType,
35907 format: RGBEFormat,
35908 encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
35912 var cubeUVRenderTarget = _createRenderTarget(params);
35914 cubeUVRenderTarget.depthBuffer = texture ? false : true;
35915 this._pingPongRenderTarget = _createRenderTarget(params);
35916 return cubeUVRenderTarget;
35919 _proto._compileMaterial = function _compileMaterial(material) {
35920 var tmpMesh = new Mesh(_lodPlanes[0], material);
35922 this._renderer.compile(tmpMesh, _flatCamera);
35925 _proto._sceneToCubeUV = function _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
35928 var cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
35929 var upSign = [1, -1, 1, 1, 1, 1];
35930 var forwardSign = [1, 1, 1, -1, -1, -1];
35931 var renderer = this._renderer;
35932 var outputEncoding = renderer.outputEncoding;
35933 var toneMapping = renderer.toneMapping;
35934 var clearColor = renderer.getClearColor();
35935 var clearAlpha = renderer.getClearAlpha();
35936 renderer.toneMapping = NoToneMapping;
35937 renderer.outputEncoding = LinearEncoding;
35938 var background = scene.background;
35940 if (background && background.isColor) {
35941 background.convertSRGBToLinear(); // Convert linear to RGBE
35943 var maxComponent = Math.max(background.r, background.g, background.b);
35944 var fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
35945 background = background.multiplyScalar(Math.pow(2.0, -fExp));
35946 var alpha = (fExp + 128.0) / 255.0;
35947 renderer.setClearColor(background, alpha);
35948 scene.background = null;
35951 for (var i = 0; i < 6; i++) {
35955 cubeCamera.up.set(0, upSign[i], 0);
35956 cubeCamera.lookAt(forwardSign[i], 0, 0);
35957 } else if (col == 1) {
35958 cubeCamera.up.set(0, 0, upSign[i]);
35959 cubeCamera.lookAt(0, forwardSign[i], 0);
35961 cubeCamera.up.set(0, upSign[i], 0);
35962 cubeCamera.lookAt(0, 0, forwardSign[i]);
35965 _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
35967 renderer.setRenderTarget(cubeUVRenderTarget);
35968 renderer.render(scene, cubeCamera);
35971 renderer.toneMapping = toneMapping;
35972 renderer.outputEncoding = outputEncoding;
35973 renderer.setClearColor(clearColor, clearAlpha);
35976 _proto._textureToCubeUV = function _textureToCubeUV(texture, cubeUVRenderTarget) {
35977 var renderer = this._renderer;
35979 if (texture.isCubeTexture) {
35980 if (this._cubemapShader == null) {
35981 this._cubemapShader = _getCubemapShader();
35984 if (this._equirectShader == null) {
35985 this._equirectShader = _getEquirectShader();
35989 var material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
35990 var mesh = new Mesh(_lodPlanes[0], material);
35991 var uniforms = material.uniforms;
35992 uniforms['envMap'].value = texture;
35994 if (!texture.isCubeTexture) {
35995 uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
35998 uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
35999 uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
36001 _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
36003 renderer.setRenderTarget(cubeUVRenderTarget);
36004 renderer.render(mesh, _flatCamera);
36007 _proto._applyPMREM = function _applyPMREM(cubeUVRenderTarget) {
36008 var renderer = this._renderer;
36009 var autoClear = renderer.autoClear;
36010 renderer.autoClear = false;
36012 for (var i = 1; i < TOTAL_LODS; i++) {
36013 var sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
36014 var poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
36016 this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
36019 renderer.autoClear = autoClear;
36022 * This is a two-pass Gaussian blur for a cubemap. Normally this is done
36023 * vertically and horizontally, but this breaks down on a cube. Here we apply
36024 * the blur latitudinally (around the poles), and then longitudinally (towards
36025 * the poles) to approximate the orthogonally-separable blur. It is least
36026 * accurate at the poles, but still does a decent job.
36030 _proto._blur = function _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
36031 var pingPongRenderTarget = this._pingPongRenderTarget;
36033 this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
36035 this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
36038 _proto._halfBlur = function _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
36039 var renderer = this._renderer;
36040 var blurMaterial = this._blurMaterial;
36042 if (direction !== 'latitudinal' && direction !== 'longitudinal') {
36043 console.error('blur direction must be either latitudinal or longitudinal!');
36044 } // Number of standard deviations at which to cut off the discrete approximation.
36047 var STANDARD_DEVIATIONS = 3;
36048 var blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
36049 var blurUniforms = blurMaterial.uniforms;
36050 var pixels = _sizeLods[lodIn] - 1;
36051 var radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
36052 var sigmaPixels = sigmaRadians / radiansPerPixel;
36053 var samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
36055 if (samples > MAX_SAMPLES) {
36056 console.warn("sigmaRadians, " + sigmaRadians + ", is too large and will clip, as it requested " + samples + " samples when the maximum is set to " + MAX_SAMPLES);
36062 for (var i = 0; i < MAX_SAMPLES; ++i) {
36063 var _x = i / sigmaPixels;
36065 var weight = Math.exp(-_x * _x / 2);
36066 weights.push(weight);
36070 } else if (i < samples) {
36075 for (var _i = 0; _i < weights.length; _i++) {
36076 weights[_i] = weights[_i] / sum;
36079 blurUniforms['envMap'].value = targetIn.texture;
36080 blurUniforms['samples'].value = samples;
36081 blurUniforms['weights'].value = weights;
36082 blurUniforms['latitudinal'].value = direction === 'latitudinal';
36085 blurUniforms['poleAxis'].value = poleAxis;
36088 blurUniforms['dTheta'].value = radiansPerPixel;
36089 blurUniforms['mipInt'].value = LOD_MAX - lodIn;
36090 blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
36091 blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
36092 var outputSize = _sizeLods[lodOut];
36093 var x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
36094 var y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
36096 _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
36098 renderer.setRenderTarget(targetOut);
36099 renderer.render(blurMesh, _flatCamera);
36102 return PMREMGenerator;
36105 function _isLDR(texture) {
36106 if (texture === undefined || texture.type !== UnsignedByteType) return false;
36107 return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
36110 function _createPlanes() {
36111 var _lodPlanes = [];
36112 var _sizeLods = [];
36116 for (var i = 0; i < TOTAL_LODS; i++) {
36117 var sizeLod = Math.pow(2, lod);
36119 _sizeLods.push(sizeLod);
36121 var sigma = 1.0 / sizeLod;
36123 if (i > LOD_MAX - LOD_MIN) {
36124 sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
36125 } else if (i == 0) {
36129 _sigmas.push(sigma);
36131 var texelSize = 1.0 / (sizeLod - 1);
36132 var min = -texelSize / 2;
36133 var max = 1 + texelSize / 2;
36134 var uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
36137 var positionSize = 3;
36139 var faceIndexSize = 1;
36140 var position = new Float32Array(positionSize * vertices * cubeFaces);
36141 var uv = new Float32Array(uvSize * vertices * cubeFaces);
36142 var faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
36144 for (var face = 0; face < cubeFaces; face++) {
36145 var x = face % 3 * 2 / 3 - 1;
36146 var y = face > 2 ? 0 : -1;
36147 var 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];
36148 position.set(coordinates, positionSize * vertices * face);
36149 uv.set(uv1, uvSize * vertices * face);
36150 var fill = [face, face, face, face, face, face];
36151 faceIndex.set(fill, faceIndexSize * vertices * face);
36154 var planes = new BufferGeometry();
36155 planes.setAttribute('position', new BufferAttribute(position, positionSize));
36156 planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
36157 planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
36159 _lodPlanes.push(planes);
36161 if (lod > LOD_MIN) {
36167 _lodPlanes: _lodPlanes,
36168 _sizeLods: _sizeLods,
36173 function _createRenderTarget(params) {
36174 var cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
36175 cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
36176 cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
36177 cubeUVRenderTarget.scissorTest = true;
36178 return cubeUVRenderTarget;
36181 function _setViewport(target, x, y, width, height) {
36182 target.viewport.set(x, y, width, height);
36183 target.scissor.set(x, y, width, height);
36186 function _getBlurShader(maxSamples) {
36187 var weights = new Float32Array(maxSamples);
36188 var poleAxis = new Vector3(0, 1, 0);
36189 var shaderMaterial = new RawShaderMaterial({
36190 name: 'SphericalGaussianBlur',
36217 value: ENCODINGS[LinearEncoding]
36219 'outputEncoding': {
36220 value: ENCODINGS[LinearEncoding]
36223 vertexShader: _getCommonVertexShader(),
36226 "\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" + _getEncodings() + "\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\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t",
36227 blending: NoBlending,
36231 return shaderMaterial;
36234 function _getEquirectShader() {
36235 var texelSize = new Vector2(1, 1);
36236 var shaderMaterial = new RawShaderMaterial({
36237 name: 'EquirectangularToCubeUV',
36246 value: ENCODINGS[LinearEncoding]
36248 'outputEncoding': {
36249 value: ENCODINGS[LinearEncoding]
36252 vertexShader: _getCommonVertexShader(),
36255 "\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" + _getEncodings() + "\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\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t",
36256 blending: NoBlending,
36260 return shaderMaterial;
36263 function _getCubemapShader() {
36264 var shaderMaterial = new RawShaderMaterial({
36265 name: 'CubemapToCubeUV',
36271 value: ENCODINGS[LinearEncoding]
36273 'outputEncoding': {
36274 value: ENCODINGS[LinearEncoding]
36277 vertexShader: _getCommonVertexShader(),
36280 "\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" + _getEncodings() + "\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t",
36281 blending: NoBlending,
36285 return shaderMaterial;
36288 function _getCommonVertexShader() {
36291 "\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"
36295 function _getEncodings() {
36298 "\n\n\t\tuniform int inputEncoding;\n\t\tuniform int outputEncoding;\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 if ( inputEncoding == 1 ) {\n\n\t\t\t\treturn sRGBToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 2 ) {\n\n\t\t\t\treturn RGBEToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 3 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 7.0 );\n\n\t\t\t} else if ( inputEncoding == 4 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 16.0 );\n\n\t\t\t} else if ( inputEncoding == 5 ) {\n\n\t\t\t\treturn RGBDToLinear( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn GammaToLinear( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 linearToOutputTexel( vec4 value ) {\n\n\t\t\tif ( outputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( outputEncoding == 1 ) {\n\n\t\t\t\treturn LinearTosRGB( value );\n\n\t\t\t} else if ( outputEncoding == 2 ) {\n\n\t\t\t\treturn LinearToRGBE( value );\n\n\t\t\t} else if ( outputEncoding == 3 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 7.0 );\n\n\t\t\t} else if ( outputEncoding == 4 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 16.0 );\n\n\t\t\t} else if ( outputEncoding == 5 ) {\n\n\t\t\t\treturn LinearToRGBD( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn LinearToGamma( value, 2.2 );\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"
36302 function Face4(a, b, c, d, normal, color, materialIndex) {
36303 console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
36304 return new Face3(a, b, c, normal, color, materialIndex);
36307 var LinePieces = 1;
36309 var FaceColors = 1;
36310 var VertexColors = 2;
36311 function MeshFaceMaterial(materials) {
36312 console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
36315 function MultiMaterial(materials) {
36316 if (materials === void 0) {
36320 console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
36321 materials.isMultiMaterial = true;
36322 materials.materials = materials;
36324 materials.clone = function () {
36325 return materials.slice();
36330 function PointCloud(geometry, material) {
36331 console.warn('THREE.PointCloud has been renamed to THREE.Points.');
36332 return new Points(geometry, material);
36334 function Particle(material) {
36335 console.warn('THREE.Particle has been renamed to THREE.Sprite.');
36336 return new Sprite(material);
36338 function ParticleSystem(geometry, material) {
36339 console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
36340 return new Points(geometry, material);
36342 function PointCloudMaterial(parameters) {
36343 console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
36344 return new PointsMaterial(parameters);
36346 function ParticleBasicMaterial(parameters) {
36347 console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
36348 return new PointsMaterial(parameters);
36350 function ParticleSystemMaterial(parameters) {
36351 console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
36352 return new PointsMaterial(parameters);
36354 function Vertex(x, y, z) {
36355 console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
36356 return new Vector3(x, y, z);
36359 function DynamicBufferAttribute(array, itemSize) {
36360 console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
36361 return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
36363 function Int8Attribute(array, itemSize) {
36364 console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
36365 return new Int8BufferAttribute(array, itemSize);
36367 function Uint8Attribute(array, itemSize) {
36368 console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
36369 return new Uint8BufferAttribute(array, itemSize);
36371 function Uint8ClampedAttribute(array, itemSize) {
36372 console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
36373 return new Uint8ClampedBufferAttribute(array, itemSize);
36375 function Int16Attribute(array, itemSize) {
36376 console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
36377 return new Int16BufferAttribute(array, itemSize);
36379 function Uint16Attribute(array, itemSize) {
36380 console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
36381 return new Uint16BufferAttribute(array, itemSize);
36383 function Int32Attribute(array, itemSize) {
36384 console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
36385 return new Int32BufferAttribute(array, itemSize);
36387 function Uint32Attribute(array, itemSize) {
36388 console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
36389 return new Uint32BufferAttribute(array, itemSize);
36391 function Float32Attribute(array, itemSize) {
36392 console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
36393 return new Float32BufferAttribute(array, itemSize);
36395 function Float64Attribute(array, itemSize) {
36396 console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
36397 return new Float64BufferAttribute(array, itemSize);
36400 Curve.create = function (construct, getPoint) {
36401 console.log('THREE.Curve.create() has been deprecated');
36402 construct.prototype = Object.create(Curve.prototype);
36403 construct.prototype.constructor = construct;
36404 construct.prototype.getPoint = getPoint;
36409 Object.assign(CurvePath.prototype, {
36410 createPointsGeometry: function createPointsGeometry(divisions) {
36411 console.warn('THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from path points (for Line or Points objects)
36413 var pts = this.getPoints(divisions);
36414 return this.createGeometry(pts);
36416 createSpacedPointsGeometry: function createSpacedPointsGeometry(divisions) {
36417 console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
36419 var pts = this.getSpacedPoints(divisions);
36420 return this.createGeometry(pts);
36422 createGeometry: function createGeometry(points) {
36423 console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
36424 var geometry = new Geometry();
36426 for (var i = 0, l = points.length; i < l; i++) {
36427 var point = points[i];
36428 geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
36435 Object.assign(Path.prototype, {
36436 fromPoints: function fromPoints(points) {
36437 console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
36438 return this.setFromPoints(points);
36442 function ClosedSplineCurve3(points) {
36443 console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
36444 CatmullRomCurve3.call(this, points);
36445 this.type = 'catmullrom';
36446 this.closed = true;
36448 ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
36450 function SplineCurve3(points) {
36451 console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
36452 CatmullRomCurve3.call(this, points);
36453 this.type = 'catmullrom';
36455 SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
36457 function Spline(points) {
36458 console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
36459 CatmullRomCurve3.call(this, points);
36460 this.type = 'catmullrom';
36462 Spline.prototype = Object.create(CatmullRomCurve3.prototype);
36463 Object.assign(Spline.prototype, {
36464 initFromArray: function initFromArray()
36467 console.error('THREE.Spline: .initFromArray() has been removed.');
36469 getControlPointsArray: function getControlPointsArray()
36470 /* optionalTarget */
36472 console.error('THREE.Spline: .getControlPointsArray() has been removed.');
36474 reparametrizeByArcLength: function reparametrizeByArcLength()
36477 console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
36481 function AxisHelper(size) {
36482 console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
36483 return new AxesHelper(size);
36485 function BoundingBoxHelper(object, color) {
36486 console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
36487 return new BoxHelper(object, color);
36489 function EdgesHelper(object, hex) {
36490 console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
36491 return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
36492 color: hex !== undefined ? hex : 0xffffff
36496 GridHelper.prototype.setColors = function () {
36497 console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
36500 SkeletonHelper.prototype.update = function () {
36501 console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
36504 function WireframeHelper(object, hex) {
36505 console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
36506 return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
36507 color: hex !== undefined ? hex : 0xffffff
36511 Object.assign(Loader.prototype, {
36512 extractUrlBase: function extractUrlBase(url) {
36513 console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
36514 return LoaderUtils.extractUrlBase(url);
36517 Loader.Handlers = {
36518 add: function add()
36519 /* regex, loader */
36521 console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
36523 get: function get()
36526 console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
36529 function XHRLoader(manager) {
36530 console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
36531 return new FileLoader(manager);
36533 function BinaryTextureLoader(manager) {
36534 console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
36535 return new DataTextureLoader(manager);
36538 Object.assign(Box2.prototype, {
36539 center: function center(optionalTarget) {
36540 console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
36541 return this.getCenter(optionalTarget);
36543 empty: function empty() {
36544 console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
36545 return this.isEmpty();
36547 isIntersectionBox: function isIntersectionBox(box) {
36548 console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
36549 return this.intersectsBox(box);
36551 size: function size(optionalTarget) {
36552 console.warn('THREE.Box2: .size() has been renamed to .getSize().');
36553 return this.getSize(optionalTarget);
36556 Object.assign(Box3.prototype, {
36557 center: function center(optionalTarget) {
36558 console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
36559 return this.getCenter(optionalTarget);
36561 empty: function empty() {
36562 console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
36563 return this.isEmpty();
36565 isIntersectionBox: function isIntersectionBox(box) {
36566 console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
36567 return this.intersectsBox(box);
36569 isIntersectionSphere: function isIntersectionSphere(sphere) {
36570 console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
36571 return this.intersectsSphere(sphere);
36573 size: function size(optionalTarget) {
36574 console.warn('THREE.Box3: .size() has been renamed to .getSize().');
36575 return this.getSize(optionalTarget);
36578 Object.assign(Sphere.prototype, {
36579 empty: function empty() {
36580 console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
36581 return this.isEmpty();
36585 Frustum.prototype.setFromMatrix = function (m) {
36586 console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
36587 return this.setFromProjectionMatrix(m);
36590 Line3.prototype.center = function (optionalTarget) {
36591 console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
36592 return this.getCenter(optionalTarget);
36595 Object.assign(MathUtils, {
36596 random16: function random16() {
36597 console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
36598 return Math.random();
36600 nearestPowerOfTwo: function nearestPowerOfTwo(value) {
36601 console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
36602 return MathUtils.floorPowerOfTwo(value);
36604 nextPowerOfTwo: function nextPowerOfTwo(value) {
36605 console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
36606 return MathUtils.ceilPowerOfTwo(value);
36609 Object.assign(Matrix3.prototype, {
36610 flattenToArrayOffset: function flattenToArrayOffset(array, offset) {
36611 console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
36612 return this.toArray(array, offset);
36614 multiplyVector3: function multiplyVector3(vector) {
36615 console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
36616 return vector.applyMatrix3(this);
36618 multiplyVector3Array: function multiplyVector3Array()
36621 console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
36623 applyToBufferAttribute: function applyToBufferAttribute(attribute) {
36624 console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
36625 return attribute.applyMatrix3(this);
36627 applyToVector3Array: function applyToVector3Array()
36628 /* array, offset, length */
36630 console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
36632 getInverse: function getInverse(matrix) {
36633 console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
36634 return this.copy(matrix).invert();
36637 Object.assign(Matrix4.prototype, {
36638 extractPosition: function extractPosition(m) {
36639 console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
36640 return this.copyPosition(m);
36642 flattenToArrayOffset: function flattenToArrayOffset(array, offset) {
36643 console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
36644 return this.toArray(array, offset);
36646 getPosition: function getPosition() {
36647 console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
36648 return new Vector3().setFromMatrixColumn(this, 3);
36650 setRotationFromQuaternion: function setRotationFromQuaternion(q) {
36651 console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
36652 return this.makeRotationFromQuaternion(q);
36654 multiplyToArray: function multiplyToArray() {
36655 console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
36657 multiplyVector3: function multiplyVector3(vector) {
36658 console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
36659 return vector.applyMatrix4(this);
36661 multiplyVector4: function multiplyVector4(vector) {
36662 console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
36663 return vector.applyMatrix4(this);
36665 multiplyVector3Array: function multiplyVector3Array()
36668 console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
36670 rotateAxis: function rotateAxis(v) {
36671 console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
36672 v.transformDirection(this);
36674 crossVector: function crossVector(vector) {
36675 console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
36676 return vector.applyMatrix4(this);
36678 translate: function translate() {
36679 console.error('THREE.Matrix4: .translate() has been removed.');
36681 rotateX: function rotateX() {
36682 console.error('THREE.Matrix4: .rotateX() has been removed.');
36684 rotateY: function rotateY() {
36685 console.error('THREE.Matrix4: .rotateY() has been removed.');
36687 rotateZ: function rotateZ() {
36688 console.error('THREE.Matrix4: .rotateZ() has been removed.');
36690 rotateByAxis: function rotateByAxis() {
36691 console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
36693 applyToBufferAttribute: function applyToBufferAttribute(attribute) {
36694 console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
36695 return attribute.applyMatrix4(this);
36697 applyToVector3Array: function applyToVector3Array()
36698 /* array, offset, length */
36700 console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
36702 makeFrustum: function makeFrustum(left, right, bottom, top, near, far) {
36703 console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
36704 return this.makePerspective(left, right, top, bottom, near, far);
36706 getInverse: function getInverse(matrix) {
36707 console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
36708 return this.copy(matrix).invert();
36712 Plane.prototype.isIntersectionLine = function (line) {
36713 console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
36714 return this.intersectsLine(line);
36717 Object.assign(Quaternion.prototype, {
36718 multiplyVector3: function multiplyVector3(vector) {
36719 console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
36720 return vector.applyQuaternion(this);
36722 inverse: function inverse() {
36723 console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
36724 return this.invert();
36727 Object.assign(Ray.prototype, {
36728 isIntersectionBox: function isIntersectionBox(box) {
36729 console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
36730 return this.intersectsBox(box);
36732 isIntersectionPlane: function isIntersectionPlane(plane) {
36733 console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
36734 return this.intersectsPlane(plane);
36736 isIntersectionSphere: function isIntersectionSphere(sphere) {
36737 console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
36738 return this.intersectsSphere(sphere);
36741 Object.assign(Triangle.prototype, {
36742 area: function area() {
36743 console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
36744 return this.getArea();
36746 barycoordFromPoint: function barycoordFromPoint(point, target) {
36747 console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
36748 return this.getBarycoord(point, target);
36750 midpoint: function midpoint(target) {
36751 console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
36752 return this.getMidpoint(target);
36754 normal: function normal(target) {
36755 console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
36756 return this.getNormal(target);
36758 plane: function plane(target) {
36759 console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
36760 return this.getPlane(target);
36763 Object.assign(Triangle, {
36764 barycoordFromPoint: function barycoordFromPoint(point, a, b, c, target) {
36765 console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
36766 return Triangle.getBarycoord(point, a, b, c, target);
36768 normal: function normal(a, b, c, target) {
36769 console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
36770 return Triangle.getNormal(a, b, c, target);
36773 Object.assign(Shape.prototype, {
36774 extractAllPoints: function extractAllPoints(divisions) {
36775 console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
36776 return this.extractPoints(divisions);
36778 extrude: function extrude(options) {
36779 console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
36780 return new ExtrudeGeometry(this, options);
36782 makeGeometry: function makeGeometry(options) {
36783 console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
36784 return new ShapeGeometry(this, options);
36787 Object.assign(Vector2.prototype, {
36788 fromAttribute: function fromAttribute(attribute, index, offset) {
36789 console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
36790 return this.fromBufferAttribute(attribute, index, offset);
36792 distanceToManhattan: function distanceToManhattan(v) {
36793 console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
36794 return this.manhattanDistanceTo(v);
36796 lengthManhattan: function lengthManhattan() {
36797 console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
36798 return this.manhattanLength();
36801 Object.assign(Vector3.prototype, {
36802 setEulerFromRotationMatrix: function setEulerFromRotationMatrix() {
36803 console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
36805 setEulerFromQuaternion: function setEulerFromQuaternion() {
36806 console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
36808 getPositionFromMatrix: function getPositionFromMatrix(m) {
36809 console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
36810 return this.setFromMatrixPosition(m);
36812 getScaleFromMatrix: function getScaleFromMatrix(m) {
36813 console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
36814 return this.setFromMatrixScale(m);
36816 getColumnFromMatrix: function getColumnFromMatrix(index, matrix) {
36817 console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
36818 return this.setFromMatrixColumn(matrix, index);
36820 applyProjection: function applyProjection(m) {
36821 console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
36822 return this.applyMatrix4(m);
36824 fromAttribute: function fromAttribute(attribute, index, offset) {
36825 console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
36826 return this.fromBufferAttribute(attribute, index, offset);
36828 distanceToManhattan: function distanceToManhattan(v) {
36829 console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
36830 return this.manhattanDistanceTo(v);
36832 lengthManhattan: function lengthManhattan() {
36833 console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
36834 return this.manhattanLength();
36837 Object.assign(Vector4.prototype, {
36838 fromAttribute: function fromAttribute(attribute, index, offset) {
36839 console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
36840 return this.fromBufferAttribute(attribute, index, offset);
36842 lengthManhattan: function lengthManhattan() {
36843 console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
36844 return this.manhattanLength();
36848 Object.assign(Geometry.prototype, {
36849 computeTangents: function computeTangents() {
36850 console.error('THREE.Geometry: .computeTangents() has been removed.');
36852 computeLineDistances: function computeLineDistances() {
36853 console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
36855 applyMatrix: function applyMatrix(matrix) {
36856 console.warn('THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().');
36857 return this.applyMatrix4(matrix);
36860 Object.assign(Object3D.prototype, {
36861 getChildByName: function getChildByName(name) {
36862 console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
36863 return this.getObjectByName(name);
36865 renderDepth: function renderDepth() {
36866 console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
36868 translate: function translate(distance, axis) {
36869 console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
36870 return this.translateOnAxis(axis, distance);
36872 getWorldRotation: function getWorldRotation() {
36873 console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
36875 applyMatrix: function applyMatrix(matrix) {
36876 console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
36877 return this.applyMatrix4(matrix);
36880 Object.defineProperties(Object3D.prototype, {
36882 get: function get() {
36883 console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
36884 return this.rotation.order;
36886 set: function set(value) {
36887 console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
36888 this.rotation.order = value;
36892 get: function get() {
36893 console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
36895 set: function set() {
36896 console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
36900 Object.assign(Mesh.prototype, {
36901 setDrawMode: function setDrawMode() {
36902 console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
36905 Object.defineProperties(Mesh.prototype, {
36907 get: function get() {
36908 console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
36909 return TrianglesDrawMode;
36911 set: function set() {
36912 console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
36916 Object.defineProperties(LOD.prototype, {
36918 get: function get() {
36919 console.warn('THREE.LOD: .objects has been renamed to .levels.');
36920 return this.levels;
36924 Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
36925 get: function get() {
36926 console.warn('THREE.Skeleton: useVertexTexture has been removed.');
36928 set: function set() {
36929 console.warn('THREE.Skeleton: useVertexTexture has been removed.');
36933 SkinnedMesh.prototype.initBones = function () {
36934 console.error('THREE.SkinnedMesh: initBones() has been removed.');
36937 Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
36938 get: function get() {
36939 console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
36940 return this.arcLengthDivisions;
36942 set: function set(value) {
36943 console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
36944 this.arcLengthDivisions = value;
36948 PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
36949 console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
36950 if (filmGauge !== undefined) this.filmGauge = filmGauge;
36951 this.setFocalLength(focalLength);
36955 Object.defineProperties(Light.prototype, {
36957 set: function set() {
36958 console.warn('THREE.Light: .onlyShadow has been removed.');
36962 set: function set(value) {
36963 console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
36964 this.shadow.camera.fov = value;
36967 shadowCameraLeft: {
36968 set: function set(value) {
36969 console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
36970 this.shadow.camera.left = value;
36973 shadowCameraRight: {
36974 set: function set(value) {
36975 console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
36976 this.shadow.camera.right = value;
36980 set: function set(value) {
36981 console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
36982 this.shadow.camera.top = value;
36985 shadowCameraBottom: {
36986 set: function set(value) {
36987 console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
36988 this.shadow.camera.bottom = value;
36991 shadowCameraNear: {
36992 set: function set(value) {
36993 console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
36994 this.shadow.camera.near = value;
36998 set: function set(value) {
36999 console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
37000 this.shadow.camera.far = value;
37003 shadowCameraVisible: {
37004 set: function set() {
37005 console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
37009 set: function set(value) {
37010 console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
37011 this.shadow.bias = value;
37015 set: function set() {
37016 console.warn('THREE.Light: .shadowDarkness has been removed.');
37020 set: function set(value) {
37021 console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
37022 this.shadow.mapSize.width = value;
37026 set: function set(value) {
37027 console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
37028 this.shadow.mapSize.height = value;
37033 Object.defineProperties(BufferAttribute.prototype, {
37035 get: function get() {
37036 console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
37037 return this.array.length;
37041 get: function get() {
37042 console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
37043 return this.usage === DynamicDrawUsage;
37045 set: function set()
37048 console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
37049 this.setUsage(DynamicDrawUsage);
37053 Object.assign(BufferAttribute.prototype, {
37054 setDynamic: function setDynamic(value) {
37055 console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
37056 this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
37059 copyIndicesArray: function copyIndicesArray()
37062 console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
37064 setArray: function setArray()
37067 console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
37070 Object.assign(BufferGeometry.prototype, {
37071 addIndex: function addIndex(index) {
37072 console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
37073 this.setIndex(index);
37075 addAttribute: function addAttribute(name, attribute) {
37076 console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
37078 if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
37079 console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
37080 return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
37083 if (name === 'index') {
37084 console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
37085 this.setIndex(attribute);
37089 return this.setAttribute(name, attribute);
37091 addDrawCall: function addDrawCall(start, count, indexOffset) {
37092 if (indexOffset !== undefined) {
37093 console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
37096 console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
37097 this.addGroup(start, count);
37099 clearDrawCalls: function clearDrawCalls() {
37100 console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
37101 this.clearGroups();
37103 computeTangents: function computeTangents() {
37104 console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
37106 computeOffsets: function computeOffsets() {
37107 console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
37109 removeAttribute: function removeAttribute(name) {
37110 console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
37111 return this.deleteAttribute(name);
37113 applyMatrix: function applyMatrix(matrix) {
37114 console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
37115 return this.applyMatrix4(matrix);
37118 Object.defineProperties(BufferGeometry.prototype, {
37120 get: function get() {
37121 console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
37122 return this.groups;
37126 get: function get() {
37127 console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
37128 return this.groups;
37132 Object.defineProperties(InstancedBufferGeometry.prototype, {
37133 maxInstancedCount: {
37134 get: function get() {
37135 console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
37136 return this.instanceCount;
37138 set: function set(value) {
37139 console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
37140 this.instanceCount = value;
37144 Object.defineProperties(Raycaster.prototype, {
37146 get: function get() {
37147 console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
37148 return this.params.Line.threshold;
37150 set: function set(value) {
37151 console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
37152 this.params.Line.threshold = value;
37156 Object.defineProperties(InterleavedBuffer.prototype, {
37158 get: function get() {
37159 console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
37160 return this.usage === DynamicDrawUsage;
37162 set: function set(value) {
37163 console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
37164 this.setUsage(value);
37168 Object.assign(InterleavedBuffer.prototype, {
37169 setDynamic: function setDynamic(value) {
37170 console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
37171 this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
37174 setArray: function setArray()
37177 console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
37181 Object.assign(ExtrudeBufferGeometry.prototype, {
37182 getArrays: function getArrays() {
37183 console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
37185 addShapeList: function addShapeList() {
37186 console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
37188 addShape: function addShape() {
37189 console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
37193 Object.assign(Scene.prototype, {
37194 dispose: function dispose() {
37195 console.error('THREE.Scene: .dispose() has been removed.');
37199 Object.defineProperties(Uniform.prototype, {
37201 set: function set() {
37202 console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
37206 value: function value() {
37207 console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
37213 Object.defineProperties(Material.prototype, {
37215 get: function get() {
37216 console.warn('THREE.Material: .wrapAround has been removed.');
37218 set: function set() {
37219 console.warn('THREE.Material: .wrapAround has been removed.');
37223 get: function get() {
37224 console.warn('THREE.Material: .overdraw has been removed.');
37226 set: function set() {
37227 console.warn('THREE.Material: .overdraw has been removed.');
37231 get: function get() {
37232 console.warn('THREE.Material: .wrapRGB has been removed.');
37233 return new Color();
37237 get: function get() {
37238 console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
37240 set: function set(value) {
37241 console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
37242 this.flatShading = value === FlatShading;
37246 get: function get() {
37247 console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
37248 return this.stencilFuncMask;
37250 set: function set(value) {
37251 console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
37252 this.stencilFuncMask = value;
37256 Object.defineProperties(MeshPhongMaterial.prototype, {
37258 get: function get() {
37259 console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
37262 set: function set() {
37263 console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
37267 Object.defineProperties(MeshPhysicalMaterial.prototype, {
37269 get: function get() {
37270 console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
37271 return this.transmission;
37273 set: function set(value) {
37274 console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
37275 this.transmission = value;
37279 Object.defineProperties(ShaderMaterial.prototype, {
37281 get: function get() {
37282 console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
37283 return this.extensions.derivatives;
37285 set: function set(value) {
37286 console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
37287 this.extensions.derivatives = value;
37292 Object.assign(WebGLRenderer.prototype, {
37293 clearTarget: function clearTarget(renderTarget, color, depth, stencil) {
37294 console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
37295 this.setRenderTarget(renderTarget);
37296 this.clear(color, depth, stencil);
37298 animate: function animate(callback) {
37299 console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
37300 this.setAnimationLoop(callback);
37302 getCurrentRenderTarget: function getCurrentRenderTarget() {
37303 console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
37304 return this.getRenderTarget();
37306 getMaxAnisotropy: function getMaxAnisotropy() {
37307 console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
37308 return this.capabilities.getMaxAnisotropy();
37310 getPrecision: function getPrecision() {
37311 console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
37312 return this.capabilities.precision;
37314 resetGLState: function resetGLState() {
37315 console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
37316 return this.state.reset();
37318 supportsFloatTextures: function supportsFloatTextures() {
37319 console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
37320 return this.extensions.get('OES_texture_float');
37322 supportsHalfFloatTextures: function supportsHalfFloatTextures() {
37323 console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
37324 return this.extensions.get('OES_texture_half_float');
37326 supportsStandardDerivatives: function supportsStandardDerivatives() {
37327 console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
37328 return this.extensions.get('OES_standard_derivatives');
37330 supportsCompressedTextureS3TC: function supportsCompressedTextureS3TC() {
37331 console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
37332 return this.extensions.get('WEBGL_compressed_texture_s3tc');
37334 supportsCompressedTexturePVRTC: function supportsCompressedTexturePVRTC() {
37335 console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
37336 return this.extensions.get('WEBGL_compressed_texture_pvrtc');
37338 supportsBlendMinMax: function supportsBlendMinMax() {
37339 console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
37340 return this.extensions.get('EXT_blend_minmax');
37342 supportsVertexTextures: function supportsVertexTextures() {
37343 console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
37344 return this.capabilities.vertexTextures;
37346 supportsInstancedArrays: function supportsInstancedArrays() {
37347 console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
37348 return this.extensions.get('ANGLE_instanced_arrays');
37350 enableScissorTest: function enableScissorTest(boolean) {
37351 console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
37352 this.setScissorTest(boolean);
37354 initMaterial: function initMaterial() {
37355 console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
37357 addPrePlugin: function addPrePlugin() {
37358 console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
37360 addPostPlugin: function addPostPlugin() {
37361 console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
37363 updateShadowMap: function updateShadowMap() {
37364 console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
37366 setFaceCulling: function setFaceCulling() {
37367 console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
37369 allocTextureUnit: function allocTextureUnit() {
37370 console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
37372 setTexture: function setTexture() {
37373 console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
37375 setTexture2D: function setTexture2D() {
37376 console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
37378 setTextureCube: function setTextureCube() {
37379 console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
37381 getActiveMipMapLevel: function getActiveMipMapLevel() {
37382 console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
37383 return this.getActiveMipmapLevel();
37386 Object.defineProperties(WebGLRenderer.prototype, {
37387 shadowMapEnabled: {
37388 get: function get() {
37389 return this.shadowMap.enabled;
37391 set: function set(value) {
37392 console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
37393 this.shadowMap.enabled = value;
37397 get: function get() {
37398 return this.shadowMap.type;
37400 set: function set(value) {
37401 console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
37402 this.shadowMap.type = value;
37405 shadowMapCullFace: {
37406 get: function get() {
37407 console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
37410 set: function set()
37413 console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
37417 get: function get() {
37418 console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
37419 return this.getContext();
37423 get: function get() {
37424 console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
37429 get: function get() {
37430 console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
37433 set: function set() {
37434 console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
37438 get: function get() {
37439 console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
37442 set: function set(value) {
37443 console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
37444 this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
37447 toneMappingWhitePoint: {
37448 get: function get() {
37449 console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
37452 set: function set() {
37453 console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
37457 Object.defineProperties(WebGLShadowMap.prototype, {
37459 get: function get() {
37460 console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
37463 set: function set()
37466 console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
37469 renderReverseSided: {
37470 get: function get() {
37471 console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
37474 set: function set() {
37475 console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
37478 renderSingleSided: {
37479 get: function get() {
37480 console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
37483 set: function set() {
37484 console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
37488 function WebGLRenderTargetCube(width, height, options) {
37489 console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
37490 return new WebGLCubeRenderTarget(width, options);
37493 Object.defineProperties(WebGLRenderTarget.prototype, {
37495 get: function get() {
37496 console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
37497 return this.texture.wrapS;
37499 set: function set(value) {
37500 console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
37501 this.texture.wrapS = value;
37505 get: function get() {
37506 console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
37507 return this.texture.wrapT;
37509 set: function set(value) {
37510 console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
37511 this.texture.wrapT = value;
37515 get: function get() {
37516 console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
37517 return this.texture.magFilter;
37519 set: function set(value) {
37520 console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
37521 this.texture.magFilter = value;
37525 get: function get() {
37526 console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
37527 return this.texture.minFilter;
37529 set: function set(value) {
37530 console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
37531 this.texture.minFilter = value;
37535 get: function get() {
37536 console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
37537 return this.texture.anisotropy;
37539 set: function set(value) {
37540 console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
37541 this.texture.anisotropy = value;
37545 get: function get() {
37546 console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
37547 return this.texture.offset;
37549 set: function set(value) {
37550 console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
37551 this.texture.offset = value;
37555 get: function get() {
37556 console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
37557 return this.texture.repeat;
37559 set: function set(value) {
37560 console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
37561 this.texture.repeat = value;
37565 get: function get() {
37566 console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
37567 return this.texture.format;
37569 set: function set(value) {
37570 console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
37571 this.texture.format = value;
37575 get: function get() {
37576 console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
37577 return this.texture.type;
37579 set: function set(value) {
37580 console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
37581 this.texture.type = value;
37585 get: function get() {
37586 console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
37587 return this.texture.generateMipmaps;
37589 set: function set(value) {
37590 console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
37591 this.texture.generateMipmaps = value;
37596 Object.defineProperties(Audio.prototype, {
37598 value: function value(file) {
37599 console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
37601 var audioLoader = new AudioLoader();
37602 audioLoader.load(file, function (buffer) {
37603 scope.setBuffer(buffer);
37609 set: function set() {
37610 console.warn('THREE.Audio: .startTime is now .play( delay ).');
37615 AudioAnalyser.prototype.getData = function () {
37616 console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
37617 return this.getFrequencyData();
37621 CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
37622 console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
37623 return this.update(renderer, scene);
37626 CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
37627 console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
37628 return this.renderTarget.clear(renderer, color, depth, stencil);
37632 var GeometryUtils = {
37633 merge: function merge(geometry1, geometry2, materialIndexOffset) {
37634 console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
37637 if (geometry2.isMesh) {
37638 geometry2.matrixAutoUpdate && geometry2.updateMatrix();
37639 matrix = geometry2.matrix;
37640 geometry2 = geometry2.geometry;
37643 geometry1.merge(geometry2, matrix, materialIndexOffset);
37645 center: function center(geometry) {
37646 console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
37647 return geometry.center();
37650 ImageUtils.crossOrigin = undefined;
37652 ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
37653 console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
37654 var loader = new TextureLoader();
37655 loader.setCrossOrigin(this.crossOrigin);
37656 var texture = loader.load(url, onLoad, undefined, onError);
37657 if (mapping) texture.mapping = mapping;
37661 ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
37662 console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
37663 var loader = new CubeTextureLoader();
37664 loader.setCrossOrigin(this.crossOrigin);
37665 var texture = loader.load(urls, onLoad, undefined, onError);
37666 if (mapping) texture.mapping = mapping;
37670 ImageUtils.loadCompressedTexture = function () {
37671 console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
37674 ImageUtils.loadCompressedTextureCube = function () {
37675 console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
37679 function CanvasRenderer() {
37680 console.error('THREE.CanvasRenderer has been removed');
37683 function JSONLoader() {
37684 console.error('THREE.JSONLoader has been removed.');
37688 createMultiMaterialObject: function createMultiMaterialObject()
37689 /* geometry, materials */
37691 console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
37693 detach: function detach()
37694 /* child, parent, scene */
37696 console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
37698 attach: function attach()
37699 /* child, scene, parent */
37701 console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
37705 function LensFlare() {
37706 console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
37709 if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
37710 /* eslint-disable no-undef */
37711 __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
37716 /* eslint-enable no-undef */
37720 exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
37721 exports.AddEquation = AddEquation;
37722 exports.AddOperation = AddOperation;
37723 exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
37724 exports.AdditiveBlending = AdditiveBlending;
37725 exports.AlphaFormat = AlphaFormat;
37726 exports.AlwaysDepth = AlwaysDepth;
37727 exports.AlwaysStencilFunc = AlwaysStencilFunc;
37728 exports.AmbientLight = AmbientLight;
37729 exports.AmbientLightProbe = AmbientLightProbe;
37730 exports.AnimationClip = AnimationClip;
37731 exports.AnimationLoader = AnimationLoader;
37732 exports.AnimationMixer = AnimationMixer;
37733 exports.AnimationObjectGroup = AnimationObjectGroup;
37734 exports.AnimationUtils = AnimationUtils;
37735 exports.ArcCurve = ArcCurve;
37736 exports.ArrayCamera = ArrayCamera;
37737 exports.ArrowHelper = ArrowHelper;
37738 exports.Audio = Audio;
37739 exports.AudioAnalyser = AudioAnalyser;
37740 exports.AudioContext = AudioContext;
37741 exports.AudioListener = AudioListener;
37742 exports.AudioLoader = AudioLoader;
37743 exports.AxesHelper = AxesHelper;
37744 exports.AxisHelper = AxisHelper;
37745 exports.BackSide = BackSide;
37746 exports.BasicDepthPacking = BasicDepthPacking;
37747 exports.BasicShadowMap = BasicShadowMap;
37748 exports.BinaryTextureLoader = BinaryTextureLoader;
37749 exports.Bone = Bone;
37750 exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
37751 exports.BoundingBoxHelper = BoundingBoxHelper;
37752 exports.Box2 = Box2;
37753 exports.Box3 = Box3;
37754 exports.Box3Helper = Box3Helper;
37755 exports.BoxBufferGeometry = BoxBufferGeometry;
37756 exports.BoxGeometry = BoxGeometry;
37757 exports.BoxHelper = BoxHelper;
37758 exports.BufferAttribute = BufferAttribute;
37759 exports.BufferGeometry = BufferGeometry;
37760 exports.BufferGeometryLoader = BufferGeometryLoader;
37761 exports.ByteType = ByteType;
37762 exports.Cache = Cache;
37763 exports.Camera = Camera;
37764 exports.CameraHelper = CameraHelper;
37765 exports.CanvasRenderer = CanvasRenderer;
37766 exports.CanvasTexture = CanvasTexture;
37767 exports.CatmullRomCurve3 = CatmullRomCurve3;
37768 exports.CineonToneMapping = CineonToneMapping;
37769 exports.CircleBufferGeometry = CircleBufferGeometry;
37770 exports.CircleGeometry = CircleGeometry;
37771 exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
37772 exports.Clock = Clock;
37773 exports.ClosedSplineCurve3 = ClosedSplineCurve3;
37774 exports.Color = Color;
37775 exports.ColorKeyframeTrack = ColorKeyframeTrack;
37776 exports.CompressedTexture = CompressedTexture;
37777 exports.CompressedTextureLoader = CompressedTextureLoader;
37778 exports.ConeBufferGeometry = ConeBufferGeometry;
37779 exports.ConeGeometry = ConeGeometry;
37780 exports.CubeCamera = CubeCamera;
37781 exports.CubeGeometry = BoxGeometry;
37782 exports.CubeReflectionMapping = CubeReflectionMapping;
37783 exports.CubeRefractionMapping = CubeRefractionMapping;
37784 exports.CubeTexture = CubeTexture;
37785 exports.CubeTextureLoader = CubeTextureLoader;
37786 exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
37787 exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
37788 exports.CubicBezierCurve = CubicBezierCurve;
37789 exports.CubicBezierCurve3 = CubicBezierCurve3;
37790 exports.CubicInterpolant = CubicInterpolant;
37791 exports.CullFaceBack = CullFaceBack;
37792 exports.CullFaceFront = CullFaceFront;
37793 exports.CullFaceFrontBack = CullFaceFrontBack;
37794 exports.CullFaceNone = CullFaceNone;
37795 exports.Curve = Curve;
37796 exports.CurvePath = CurvePath;
37797 exports.CustomBlending = CustomBlending;
37798 exports.CustomToneMapping = CustomToneMapping;
37799 exports.CylinderBufferGeometry = CylinderBufferGeometry;
37800 exports.CylinderGeometry = CylinderGeometry;
37801 exports.Cylindrical = Cylindrical;
37802 exports.DataTexture = DataTexture;
37803 exports.DataTexture2DArray = DataTexture2DArray;
37804 exports.DataTexture3D = DataTexture3D;
37805 exports.DataTextureLoader = DataTextureLoader;
37806 exports.DataUtils = DataUtils;
37807 exports.DecrementStencilOp = DecrementStencilOp;
37808 exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
37809 exports.DefaultLoadingManager = DefaultLoadingManager;
37810 exports.DepthFormat = DepthFormat;
37811 exports.DepthStencilFormat = DepthStencilFormat;
37812 exports.DepthTexture = DepthTexture;
37813 exports.DirectionalLight = DirectionalLight;
37814 exports.DirectionalLightHelper = DirectionalLightHelper;
37815 exports.DiscreteInterpolant = DiscreteInterpolant;
37816 exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
37817 exports.DodecahedronGeometry = DodecahedronGeometry;
37818 exports.DoubleSide = DoubleSide;
37819 exports.DstAlphaFactor = DstAlphaFactor;
37820 exports.DstColorFactor = DstColorFactor;
37821 exports.DynamicBufferAttribute = DynamicBufferAttribute;
37822 exports.DynamicCopyUsage = DynamicCopyUsage;
37823 exports.DynamicDrawUsage = DynamicDrawUsage;
37824 exports.DynamicReadUsage = DynamicReadUsage;
37825 exports.EdgesGeometry = EdgesGeometry;
37826 exports.EdgesHelper = EdgesHelper;
37827 exports.EllipseCurve = EllipseCurve;
37828 exports.EqualDepth = EqualDepth;
37829 exports.EqualStencilFunc = EqualStencilFunc;
37830 exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
37831 exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
37832 exports.Euler = Euler;
37833 exports.EventDispatcher = EventDispatcher;
37834 exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
37835 exports.ExtrudeGeometry = ExtrudeGeometry;
37836 exports.Face3 = Face3;
37837 exports.Face4 = Face4;
37838 exports.FaceColors = FaceColors;
37839 exports.FileLoader = FileLoader;
37840 exports.FlatShading = FlatShading;
37841 exports.Float16BufferAttribute = Float16BufferAttribute;
37842 exports.Float32Attribute = Float32Attribute;
37843 exports.Float32BufferAttribute = Float32BufferAttribute;
37844 exports.Float64Attribute = Float64Attribute;
37845 exports.Float64BufferAttribute = Float64BufferAttribute;
37846 exports.FloatType = FloatType;
37848 exports.FogExp2 = FogExp2;
37849 exports.Font = Font;
37850 exports.FontLoader = FontLoader;
37851 exports.FrontSide = FrontSide;
37852 exports.Frustum = Frustum;
37853 exports.GLBufferAttribute = GLBufferAttribute;
37854 exports.GLSL1 = GLSL1;
37855 exports.GLSL3 = GLSL3;
37856 exports.GammaEncoding = GammaEncoding;
37857 exports.Geometry = Geometry;
37858 exports.GeometryUtils = GeometryUtils;
37859 exports.GreaterDepth = GreaterDepth;
37860 exports.GreaterEqualDepth = GreaterEqualDepth;
37861 exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
37862 exports.GreaterStencilFunc = GreaterStencilFunc;
37863 exports.GridHelper = GridHelper;
37864 exports.Group = Group;
37865 exports.HalfFloatType = HalfFloatType;
37866 exports.HemisphereLight = HemisphereLight;
37867 exports.HemisphereLightHelper = HemisphereLightHelper;
37868 exports.HemisphereLightProbe = HemisphereLightProbe;
37869 exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
37870 exports.IcosahedronGeometry = IcosahedronGeometry;
37871 exports.ImageBitmapLoader = ImageBitmapLoader;
37872 exports.ImageLoader = ImageLoader;
37873 exports.ImageUtils = ImageUtils;
37874 exports.ImmediateRenderObject = ImmediateRenderObject;
37875 exports.IncrementStencilOp = IncrementStencilOp;
37876 exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
37877 exports.InstancedBufferAttribute = InstancedBufferAttribute;
37878 exports.InstancedBufferGeometry = InstancedBufferGeometry;
37879 exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
37880 exports.InstancedMesh = InstancedMesh;
37881 exports.Int16Attribute = Int16Attribute;
37882 exports.Int16BufferAttribute = Int16BufferAttribute;
37883 exports.Int32Attribute = Int32Attribute;
37884 exports.Int32BufferAttribute = Int32BufferAttribute;
37885 exports.Int8Attribute = Int8Attribute;
37886 exports.Int8BufferAttribute = Int8BufferAttribute;
37887 exports.IntType = IntType;
37888 exports.InterleavedBuffer = InterleavedBuffer;
37889 exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
37890 exports.Interpolant = Interpolant;
37891 exports.InterpolateDiscrete = InterpolateDiscrete;
37892 exports.InterpolateLinear = InterpolateLinear;
37893 exports.InterpolateSmooth = InterpolateSmooth;
37894 exports.InvertStencilOp = InvertStencilOp;
37895 exports.JSONLoader = JSONLoader;
37896 exports.KeepStencilOp = KeepStencilOp;
37897 exports.KeyframeTrack = KeyframeTrack;
37899 exports.LatheBufferGeometry = LatheBufferGeometry;
37900 exports.LatheGeometry = LatheGeometry;
37901 exports.Layers = Layers;
37902 exports.LensFlare = LensFlare;
37903 exports.LessDepth = LessDepth;
37904 exports.LessEqualDepth = LessEqualDepth;
37905 exports.LessEqualStencilFunc = LessEqualStencilFunc;
37906 exports.LessStencilFunc = LessStencilFunc;
37907 exports.Light = Light;
37908 exports.LightProbe = LightProbe;
37909 exports.Line = Line;
37910 exports.Line3 = Line3;
37911 exports.LineBasicMaterial = LineBasicMaterial;
37912 exports.LineCurve = LineCurve;
37913 exports.LineCurve3 = LineCurve3;
37914 exports.LineDashedMaterial = LineDashedMaterial;
37915 exports.LineLoop = LineLoop;
37916 exports.LinePieces = LinePieces;
37917 exports.LineSegments = LineSegments;
37918 exports.LineStrip = LineStrip;
37919 exports.LinearEncoding = LinearEncoding;
37920 exports.LinearFilter = LinearFilter;
37921 exports.LinearInterpolant = LinearInterpolant;
37922 exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
37923 exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
37924 exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
37925 exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
37926 exports.LinearToneMapping = LinearToneMapping;
37927 exports.Loader = Loader;
37928 exports.LoaderUtils = LoaderUtils;
37929 exports.LoadingManager = LoadingManager;
37930 exports.LogLuvEncoding = LogLuvEncoding;
37931 exports.LoopOnce = LoopOnce;
37932 exports.LoopPingPong = LoopPingPong;
37933 exports.LoopRepeat = LoopRepeat;
37934 exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
37935 exports.LuminanceFormat = LuminanceFormat;
37936 exports.MOUSE = MOUSE;
37937 exports.Material = Material;
37938 exports.MaterialLoader = MaterialLoader;
37939 exports.Math = MathUtils;
37940 exports.MathUtils = MathUtils;
37941 exports.Matrix3 = Matrix3;
37942 exports.Matrix4 = Matrix4;
37943 exports.MaxEquation = MaxEquation;
37944 exports.Mesh = Mesh;
37945 exports.MeshBasicMaterial = MeshBasicMaterial;
37946 exports.MeshDepthMaterial = MeshDepthMaterial;
37947 exports.MeshDistanceMaterial = MeshDistanceMaterial;
37948 exports.MeshFaceMaterial = MeshFaceMaterial;
37949 exports.MeshLambertMaterial = MeshLambertMaterial;
37950 exports.MeshMatcapMaterial = MeshMatcapMaterial;
37951 exports.MeshNormalMaterial = MeshNormalMaterial;
37952 exports.MeshPhongMaterial = MeshPhongMaterial;
37953 exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
37954 exports.MeshStandardMaterial = MeshStandardMaterial;
37955 exports.MeshToonMaterial = MeshToonMaterial;
37956 exports.MinEquation = MinEquation;
37957 exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
37958 exports.MixOperation = MixOperation;
37959 exports.MultiMaterial = MultiMaterial;
37960 exports.MultiplyBlending = MultiplyBlending;
37961 exports.MultiplyOperation = MultiplyOperation;
37962 exports.NearestFilter = NearestFilter;
37963 exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
37964 exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
37965 exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
37966 exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
37967 exports.NeverDepth = NeverDepth;
37968 exports.NeverStencilFunc = NeverStencilFunc;
37969 exports.NoBlending = NoBlending;
37970 exports.NoColors = NoColors;
37971 exports.NoToneMapping = NoToneMapping;
37972 exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
37973 exports.NormalBlending = NormalBlending;
37974 exports.NotEqualDepth = NotEqualDepth;
37975 exports.NotEqualStencilFunc = NotEqualStencilFunc;
37976 exports.NumberKeyframeTrack = NumberKeyframeTrack;
37977 exports.Object3D = Object3D;
37978 exports.ObjectLoader = ObjectLoader;
37979 exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
37980 exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
37981 exports.OctahedronGeometry = OctahedronGeometry;
37982 exports.OneFactor = OneFactor;
37983 exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
37984 exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
37985 exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
37986 exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
37987 exports.OrthographicCamera = OrthographicCamera;
37988 exports.PCFShadowMap = PCFShadowMap;
37989 exports.PCFSoftShadowMap = PCFSoftShadowMap;
37990 exports.PMREMGenerator = PMREMGenerator;
37991 exports.ParametricBufferGeometry = ParametricBufferGeometry;
37992 exports.ParametricGeometry = ParametricGeometry;
37993 exports.Particle = Particle;
37994 exports.ParticleBasicMaterial = ParticleBasicMaterial;
37995 exports.ParticleSystem = ParticleSystem;
37996 exports.ParticleSystemMaterial = ParticleSystemMaterial;
37997 exports.Path = Path;
37998 exports.PerspectiveCamera = PerspectiveCamera;
37999 exports.Plane = Plane;
38000 exports.PlaneBufferGeometry = PlaneBufferGeometry;
38001 exports.PlaneGeometry = PlaneGeometry;
38002 exports.PlaneHelper = PlaneHelper;
38003 exports.PointCloud = PointCloud;
38004 exports.PointCloudMaterial = PointCloudMaterial;
38005 exports.PointLight = PointLight;
38006 exports.PointLightHelper = PointLightHelper;
38007 exports.Points = Points;
38008 exports.PointsMaterial = PointsMaterial;
38009 exports.PolarGridHelper = PolarGridHelper;
38010 exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
38011 exports.PolyhedronGeometry = PolyhedronGeometry;
38012 exports.PositionalAudio = PositionalAudio;
38013 exports.PropertyBinding = PropertyBinding;
38014 exports.PropertyMixer = PropertyMixer;
38015 exports.QuadraticBezierCurve = QuadraticBezierCurve;
38016 exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
38017 exports.Quaternion = Quaternion;
38018 exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
38019 exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
38020 exports.REVISION = REVISION;
38021 exports.RGBADepthPacking = RGBADepthPacking;
38022 exports.RGBAFormat = RGBAFormat;
38023 exports.RGBAIntegerFormat = RGBAIntegerFormat;
38024 exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
38025 exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
38026 exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
38027 exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
38028 exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
38029 exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
38030 exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
38031 exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
38032 exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
38033 exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
38034 exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
38035 exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
38036 exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
38037 exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
38038 exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
38039 exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
38040 exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
38041 exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
38042 exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
38043 exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
38044 exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
38045 exports.RGBDEncoding = RGBDEncoding;
38046 exports.RGBEEncoding = RGBEEncoding;
38047 exports.RGBEFormat = RGBEFormat;
38048 exports.RGBFormat = RGBFormat;
38049 exports.RGBIntegerFormat = RGBIntegerFormat;
38050 exports.RGBM16Encoding = RGBM16Encoding;
38051 exports.RGBM7Encoding = RGBM7Encoding;
38052 exports.RGB_ETC1_Format = RGB_ETC1_Format;
38053 exports.RGB_ETC2_Format = RGB_ETC2_Format;
38054 exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
38055 exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
38056 exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
38057 exports.RGFormat = RGFormat;
38058 exports.RGIntegerFormat = RGIntegerFormat;
38059 exports.RawShaderMaterial = RawShaderMaterial;
38061 exports.Raycaster = Raycaster;
38062 exports.RectAreaLight = RectAreaLight;
38063 exports.RedFormat = RedFormat;
38064 exports.RedIntegerFormat = RedIntegerFormat;
38065 exports.ReinhardToneMapping = ReinhardToneMapping;
38066 exports.RepeatWrapping = RepeatWrapping;
38067 exports.ReplaceStencilOp = ReplaceStencilOp;
38068 exports.ReverseSubtractEquation = ReverseSubtractEquation;
38069 exports.RingBufferGeometry = RingBufferGeometry;
38070 exports.RingGeometry = RingGeometry;
38071 exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
38072 exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
38073 exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
38074 exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
38075 exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
38076 exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
38077 exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
38078 exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
38079 exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
38080 exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
38081 exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
38082 exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
38083 exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
38084 exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
38085 exports.Scene = Scene;
38086 exports.SceneUtils = SceneUtils;
38087 exports.ShaderChunk = ShaderChunk;
38088 exports.ShaderLib = ShaderLib;
38089 exports.ShaderMaterial = ShaderMaterial;
38090 exports.ShadowMaterial = ShadowMaterial;
38091 exports.Shape = Shape;
38092 exports.ShapeBufferGeometry = ShapeBufferGeometry;
38093 exports.ShapeGeometry = ShapeGeometry;
38094 exports.ShapePath = ShapePath;
38095 exports.ShapeUtils = ShapeUtils;
38096 exports.ShortType = ShortType;
38097 exports.Skeleton = Skeleton;
38098 exports.SkeletonHelper = SkeletonHelper;
38099 exports.SkinnedMesh = SkinnedMesh;
38100 exports.SmoothShading = SmoothShading;
38101 exports.Sphere = Sphere;
38102 exports.SphereBufferGeometry = SphereBufferGeometry;
38103 exports.SphereGeometry = SphereGeometry;
38104 exports.Spherical = Spherical;
38105 exports.SphericalHarmonics3 = SphericalHarmonics3;
38106 exports.Spline = Spline;
38107 exports.SplineCurve = SplineCurve;
38108 exports.SplineCurve3 = SplineCurve3;
38109 exports.SpotLight = SpotLight;
38110 exports.SpotLightHelper = SpotLightHelper;
38111 exports.Sprite = Sprite;
38112 exports.SpriteMaterial = SpriteMaterial;
38113 exports.SrcAlphaFactor = SrcAlphaFactor;
38114 exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
38115 exports.SrcColorFactor = SrcColorFactor;
38116 exports.StaticCopyUsage = StaticCopyUsage;
38117 exports.StaticDrawUsage = StaticDrawUsage;
38118 exports.StaticReadUsage = StaticReadUsage;
38119 exports.StereoCamera = StereoCamera;
38120 exports.StreamCopyUsage = StreamCopyUsage;
38121 exports.StreamDrawUsage = StreamDrawUsage;
38122 exports.StreamReadUsage = StreamReadUsage;
38123 exports.StringKeyframeTrack = StringKeyframeTrack;
38124 exports.SubtractEquation = SubtractEquation;
38125 exports.SubtractiveBlending = SubtractiveBlending;
38126 exports.TOUCH = TOUCH;
38127 exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
38128 exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
38129 exports.TetrahedronGeometry = TetrahedronGeometry;
38130 exports.TextBufferGeometry = TextBufferGeometry;
38131 exports.TextGeometry = TextGeometry;
38132 exports.Texture = Texture;
38133 exports.TextureLoader = TextureLoader;
38134 exports.TorusBufferGeometry = TorusBufferGeometry;
38135 exports.TorusGeometry = TorusGeometry;
38136 exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
38137 exports.TorusKnotGeometry = TorusKnotGeometry;
38138 exports.Triangle = Triangle;
38139 exports.TriangleFanDrawMode = TriangleFanDrawMode;
38140 exports.TriangleStripDrawMode = TriangleStripDrawMode;
38141 exports.TrianglesDrawMode = TrianglesDrawMode;
38142 exports.TubeBufferGeometry = TubeBufferGeometry;
38143 exports.TubeGeometry = TubeGeometry;
38144 exports.UVMapping = UVMapping;
38145 exports.Uint16Attribute = Uint16Attribute;
38146 exports.Uint16BufferAttribute = Uint16BufferAttribute;
38147 exports.Uint32Attribute = Uint32Attribute;
38148 exports.Uint32BufferAttribute = Uint32BufferAttribute;
38149 exports.Uint8Attribute = Uint8Attribute;
38150 exports.Uint8BufferAttribute = Uint8BufferAttribute;
38151 exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
38152 exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
38153 exports.Uniform = Uniform;
38154 exports.UniformsLib = UniformsLib;
38155 exports.UniformsUtils = UniformsUtils;
38156 exports.UnsignedByteType = UnsignedByteType;
38157 exports.UnsignedInt248Type = UnsignedInt248Type;
38158 exports.UnsignedIntType = UnsignedIntType;
38159 exports.UnsignedShort4444Type = UnsignedShort4444Type;
38160 exports.UnsignedShort5551Type = UnsignedShort5551Type;
38161 exports.UnsignedShort565Type = UnsignedShort565Type;
38162 exports.UnsignedShortType = UnsignedShortType;
38163 exports.VSMShadowMap = VSMShadowMap;
38164 exports.Vector2 = Vector2;
38165 exports.Vector3 = Vector3;
38166 exports.Vector4 = Vector4;
38167 exports.VectorKeyframeTrack = VectorKeyframeTrack;
38168 exports.Vertex = Vertex;
38169 exports.VertexColors = VertexColors;
38170 exports.VideoTexture = VideoTexture;
38171 exports.WebGL1Renderer = WebGL1Renderer;
38172 exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
38173 exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
38174 exports.WebGLRenderTarget = WebGLRenderTarget;
38175 exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
38176 exports.WebGLRenderer = WebGLRenderer;
38177 exports.WebGLUtils = WebGLUtils;
38178 exports.WireframeGeometry = WireframeGeometry;
38179 exports.WireframeHelper = WireframeHelper;
38180 exports.WrapAroundEnding = WrapAroundEnding;
38181 exports.XHRLoader = XHRLoader;
38182 exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
38183 exports.ZeroFactor = ZeroFactor;
38184 exports.ZeroSlopeEnding = ZeroSlopeEnding;
38185 exports.ZeroStencilOp = ZeroStencilOp;
38186 exports.sRGBEncoding = sRGBEncoding;
38188 Object.defineProperty(exports, '__esModule', { value: true });