The website of the KaosCube
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51116 lines
1.2 MiB

  1. console.warn( 'Scripts "build/three.js" and "build/three.min.js" are deprecated with r150+, and will be removed with r160. Please use ES Modules or alternatives: https://threejs.org/docs/index.html#manual/en/introduction/Installation' );
  2. /**
  3. * @license
  4. * Copyright 2010-2023 Three.js Authors
  5. * SPDX-License-Identifier: MIT
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  9. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  10. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.THREE = {}));
  11. })(this, (function (exports) { 'use strict';
  12. const REVISION = '151dev';
  13. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  14. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  15. const CullFaceNone = 0;
  16. const CullFaceBack = 1;
  17. const CullFaceFront = 2;
  18. const CullFaceFrontBack = 3;
  19. const BasicShadowMap = 0;
  20. const PCFShadowMap = 1;
  21. const PCFSoftShadowMap = 2;
  22. const VSMShadowMap = 3;
  23. const FrontSide = 0;
  24. const BackSide = 1;
  25. const DoubleSide = 2;
  26. const TwoPassDoubleSide = 2; // r149
  27. const NoBlending = 0;
  28. const NormalBlending = 1;
  29. const AdditiveBlending = 2;
  30. const SubtractiveBlending = 3;
  31. const MultiplyBlending = 4;
  32. const CustomBlending = 5;
  33. const AddEquation = 100;
  34. const SubtractEquation = 101;
  35. const ReverseSubtractEquation = 102;
  36. const MinEquation = 103;
  37. const MaxEquation = 104;
  38. const ZeroFactor = 200;
  39. const OneFactor = 201;
  40. const SrcColorFactor = 202;
  41. const OneMinusSrcColorFactor = 203;
  42. const SrcAlphaFactor = 204;
  43. const OneMinusSrcAlphaFactor = 205;
  44. const DstAlphaFactor = 206;
  45. const OneMinusDstAlphaFactor = 207;
  46. const DstColorFactor = 208;
  47. const OneMinusDstColorFactor = 209;
  48. const SrcAlphaSaturateFactor = 210;
  49. const NeverDepth = 0;
  50. const AlwaysDepth = 1;
  51. const LessDepth = 2;
  52. const LessEqualDepth = 3;
  53. const EqualDepth = 4;
  54. const GreaterEqualDepth = 5;
  55. const GreaterDepth = 6;
  56. const NotEqualDepth = 7;
  57. const MultiplyOperation = 0;
  58. const MixOperation = 1;
  59. const AddOperation = 2;
  60. const NoToneMapping = 0;
  61. const LinearToneMapping = 1;
  62. const ReinhardToneMapping = 2;
  63. const CineonToneMapping = 3;
  64. const ACESFilmicToneMapping = 4;
  65. const CustomToneMapping = 5;
  66. const UVMapping = 300;
  67. const CubeReflectionMapping = 301;
  68. const CubeRefractionMapping = 302;
  69. const EquirectangularReflectionMapping = 303;
  70. const EquirectangularRefractionMapping = 304;
  71. const CubeUVReflectionMapping = 306;
  72. const RepeatWrapping = 1000;
  73. const ClampToEdgeWrapping = 1001;
  74. const MirroredRepeatWrapping = 1002;
  75. const NearestFilter = 1003;
  76. const NearestMipmapNearestFilter = 1004;
  77. const NearestMipMapNearestFilter = 1004;
  78. const NearestMipmapLinearFilter = 1005;
  79. const NearestMipMapLinearFilter = 1005;
  80. const LinearFilter = 1006;
  81. const LinearMipmapNearestFilter = 1007;
  82. const LinearMipMapNearestFilter = 1007;
  83. const LinearMipmapLinearFilter = 1008;
  84. const LinearMipMapLinearFilter = 1008;
  85. const UnsignedByteType = 1009;
  86. const ByteType = 1010;
  87. const ShortType = 1011;
  88. const UnsignedShortType = 1012;
  89. const IntType = 1013;
  90. const UnsignedIntType = 1014;
  91. const FloatType = 1015;
  92. const HalfFloatType = 1016;
  93. const UnsignedShort4444Type = 1017;
  94. const UnsignedShort5551Type = 1018;
  95. const UnsignedInt248Type = 1020;
  96. const AlphaFormat = 1021;
  97. const RGBAFormat = 1023;
  98. const LuminanceFormat = 1024;
  99. const LuminanceAlphaFormat = 1025;
  100. const DepthFormat = 1026;
  101. const DepthStencilFormat = 1027;
  102. const RedFormat = 1028;
  103. const RedIntegerFormat = 1029;
  104. const RGFormat = 1030;
  105. const RGIntegerFormat = 1031;
  106. const RGBAIntegerFormat = 1033;
  107. const RGB_S3TC_DXT1_Format = 33776;
  108. const RGBA_S3TC_DXT1_Format = 33777;
  109. const RGBA_S3TC_DXT3_Format = 33778;
  110. const RGBA_S3TC_DXT5_Format = 33779;
  111. const RGB_PVRTC_4BPPV1_Format = 35840;
  112. const RGB_PVRTC_2BPPV1_Format = 35841;
  113. const RGBA_PVRTC_4BPPV1_Format = 35842;
  114. const RGBA_PVRTC_2BPPV1_Format = 35843;
  115. const RGB_ETC1_Format = 36196;
  116. const RGB_ETC2_Format = 37492;
  117. const RGBA_ETC2_EAC_Format = 37496;
  118. const RGBA_ASTC_4x4_Format = 37808;
  119. const RGBA_ASTC_5x4_Format = 37809;
  120. const RGBA_ASTC_5x5_Format = 37810;
  121. const RGBA_ASTC_6x5_Format = 37811;
  122. const RGBA_ASTC_6x6_Format = 37812;
  123. const RGBA_ASTC_8x5_Format = 37813;
  124. const RGBA_ASTC_8x6_Format = 37814;
  125. const RGBA_ASTC_8x8_Format = 37815;
  126. const RGBA_ASTC_10x5_Format = 37816;
  127. const RGBA_ASTC_10x6_Format = 37817;
  128. const RGBA_ASTC_10x8_Format = 37818;
  129. const RGBA_ASTC_10x10_Format = 37819;
  130. const RGBA_ASTC_12x10_Format = 37820;
  131. const RGBA_ASTC_12x12_Format = 37821;
  132. const RGBA_BPTC_Format = 36492;
  133. const RED_RGTC1_Format = 36283;
  134. const SIGNED_RED_RGTC1_Format = 36284;
  135. const RED_GREEN_RGTC2_Format = 36285;
  136. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  137. const LoopOnce = 2200;
  138. const LoopRepeat = 2201;
  139. const LoopPingPong = 2202;
  140. const InterpolateDiscrete = 2300;
  141. const InterpolateLinear = 2301;
  142. const InterpolateSmooth = 2302;
  143. const ZeroCurvatureEnding = 2400;
  144. const ZeroSlopeEnding = 2401;
  145. const WrapAroundEnding = 2402;
  146. const NormalAnimationBlendMode = 2500;
  147. const AdditiveAnimationBlendMode = 2501;
  148. const TrianglesDrawMode = 0;
  149. const TriangleStripDrawMode = 1;
  150. const TriangleFanDrawMode = 2;
  151. const LinearEncoding = 3000;
  152. const sRGBEncoding = 3001;
  153. const BasicDepthPacking = 3200;
  154. const RGBADepthPacking = 3201;
  155. const TangentSpaceNormalMap = 0;
  156. const ObjectSpaceNormalMap = 1;
  157. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  158. const NoColorSpace = '';
  159. const SRGBColorSpace = 'srgb';
  160. const LinearSRGBColorSpace = 'srgb-linear';
  161. const DisplayP3ColorSpace = 'display-p3';
  162. const ZeroStencilOp = 0;
  163. const KeepStencilOp = 7680;
  164. const ReplaceStencilOp = 7681;
  165. const IncrementStencilOp = 7682;
  166. const DecrementStencilOp = 7683;
  167. const IncrementWrapStencilOp = 34055;
  168. const DecrementWrapStencilOp = 34056;
  169. const InvertStencilOp = 5386;
  170. const NeverStencilFunc = 512;
  171. const LessStencilFunc = 513;
  172. const EqualStencilFunc = 514;
  173. const LessEqualStencilFunc = 515;
  174. const GreaterStencilFunc = 516;
  175. const NotEqualStencilFunc = 517;
  176. const GreaterEqualStencilFunc = 518;
  177. const AlwaysStencilFunc = 519;
  178. const StaticDrawUsage = 35044;
  179. const DynamicDrawUsage = 35048;
  180. const StreamDrawUsage = 35040;
  181. const StaticReadUsage = 35045;
  182. const DynamicReadUsage = 35049;
  183. const StreamReadUsage = 35041;
  184. const StaticCopyUsage = 35046;
  185. const DynamicCopyUsage = 35050;
  186. const StreamCopyUsage = 35042;
  187. const GLSL1 = '100';
  188. const GLSL3 = '300 es';
  189. const _SRGBAFormat = 1035; // fallback for WebGL 1
  190. /**
  191. * https://github.com/mrdoob/eventdispatcher.js/
  192. */
  193. class EventDispatcher {
  194. addEventListener( type, listener ) {
  195. if ( this._listeners === undefined ) this._listeners = {};
  196. const listeners = this._listeners;
  197. if ( listeners[ type ] === undefined ) {
  198. listeners[ type ] = [];
  199. }
  200. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  201. listeners[ type ].push( listener );
  202. }
  203. }
  204. hasEventListener( type, listener ) {
  205. if ( this._listeners === undefined ) return false;
  206. const listeners = this._listeners;
  207. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  208. }
  209. removeEventListener( type, listener ) {
  210. if ( this._listeners === undefined ) return;
  211. const listeners = this._listeners;
  212. const listenerArray = listeners[ type ];
  213. if ( listenerArray !== undefined ) {
  214. const index = listenerArray.indexOf( listener );
  215. if ( index !== - 1 ) {
  216. listenerArray.splice( index, 1 );
  217. }
  218. }
  219. }
  220. dispatchEvent( event ) {
  221. if ( this._listeners === undefined ) return;
  222. const listeners = this._listeners;
  223. const listenerArray = listeners[ event.type ];
  224. if ( listenerArray !== undefined ) {
  225. event.target = this;
  226. // Make a copy, in case listeners are removed while iterating.
  227. const array = listenerArray.slice( 0 );
  228. for ( let i = 0, l = array.length; i < l; i ++ ) {
  229. array[ i ].call( this, event );
  230. }
  231. event.target = null;
  232. }
  233. }
  234. }
  235. const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];
  236. let _seed = 1234567;
  237. const DEG2RAD = Math.PI / 180;
  238. const RAD2DEG = 180 / Math.PI;
  239. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  240. function generateUUID() {
  241. const d0 = Math.random() * 0xffffffff | 0;
  242. const d1 = Math.random() * 0xffffffff | 0;
  243. const d2 = Math.random() * 0xffffffff | 0;
  244. const d3 = Math.random() * 0xffffffff | 0;
  245. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  246. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  247. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  248. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  249. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  250. return uuid.toLowerCase();
  251. }
  252. function clamp( value, min, max ) {
  253. return Math.max( min, Math.min( max, value ) );
  254. }
  255. // compute euclidean modulo of m % n
  256. // https://en.wikipedia.org/wiki/Modulo_operation
  257. function euclideanModulo( n, m ) {
  258. return ( ( n % m ) + m ) % m;
  259. }
  260. // Linear mapping from range <a1, a2> to range <b1, b2>
  261. function mapLinear( x, a1, a2, b1, b2 ) {
  262. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  263. }
  264. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  265. function inverseLerp( x, y, value ) {
  266. if ( x !== y ) {
  267. return ( value - x ) / ( y - x );
  268. } else {
  269. return 0;
  270. }
  271. }
  272. // https://en.wikipedia.org/wiki/Linear_interpolation
  273. function lerp( x, y, t ) {
  274. return ( 1 - t ) * x + t * y;
  275. }
  276. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  277. function damp( x, y, lambda, dt ) {
  278. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  279. }
  280. // https://www.desmos.com/calculator/vcsjnyz7x4
  281. function pingpong( x, length = 1 ) {
  282. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  283. }
  284. // http://en.wikipedia.org/wiki/Smoothstep
  285. function smoothstep( x, min, max ) {
  286. if ( x <= min ) return 0;
  287. if ( x >= max ) return 1;
  288. x = ( x - min ) / ( max - min );
  289. return x * x * ( 3 - 2 * x );
  290. }
  291. function smootherstep( x, min, max ) {
  292. if ( x <= min ) return 0;
  293. if ( x >= max ) return 1;
  294. x = ( x - min ) / ( max - min );
  295. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  296. }
  297. // Random integer from <low, high> interval
  298. function randInt( low, high ) {
  299. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  300. }
  301. // Random float from <low, high> interval
  302. function randFloat( low, high ) {
  303. return low + Math.random() * ( high - low );
  304. }
  305. // Random float from <-range/2, range/2> interval
  306. function randFloatSpread( range ) {
  307. return range * ( 0.5 - Math.random() );
  308. }
  309. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  310. function seededRandom( s ) {
  311. if ( s !== undefined ) _seed = s;
  312. // Mulberry32 generator
  313. let t = _seed += 0x6D2B79F5;
  314. t = Math.imul( t ^ t >>> 15, t | 1 );
  315. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  316. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  317. }
  318. function degToRad( degrees ) {
  319. return degrees * DEG2RAD;
  320. }
  321. function radToDeg( radians ) {
  322. return radians * RAD2DEG;
  323. }
  324. function isPowerOfTwo( value ) {
  325. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  326. }
  327. function ceilPowerOfTwo( value ) {
  328. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  329. }
  330. function floorPowerOfTwo( value ) {
  331. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  332. }
  333. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  334. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  335. // rotations are applied to the axes in the order specified by 'order'
  336. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  337. // angles are in radians
  338. const cos = Math.cos;
  339. const sin = Math.sin;
  340. const c2 = cos( b / 2 );
  341. const s2 = sin( b / 2 );
  342. const c13 = cos( ( a + c ) / 2 );
  343. const s13 = sin( ( a + c ) / 2 );
  344. const c1_3 = cos( ( a - c ) / 2 );
  345. const s1_3 = sin( ( a - c ) / 2 );
  346. const c3_1 = cos( ( c - a ) / 2 );
  347. const s3_1 = sin( ( c - a ) / 2 );
  348. switch ( order ) {
  349. case 'XYX':
  350. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  351. break;
  352. case 'YZY':
  353. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  354. break;
  355. case 'ZXZ':
  356. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  357. break;
  358. case 'XZX':
  359. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  360. break;
  361. case 'YXY':
  362. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  363. break;
  364. case 'ZYZ':
  365. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  366. break;
  367. default:
  368. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  369. }
  370. }
  371. function denormalize( value, array ) {
  372. switch ( array.constructor ) {
  373. case Float32Array:
  374. return value;
  375. case Uint16Array:
  376. return value / 65535.0;
  377. case Uint8Array:
  378. return value / 255.0;
  379. case Int16Array:
  380. return Math.max( value / 32767.0, - 1.0 );
  381. case Int8Array:
  382. return Math.max( value / 127.0, - 1.0 );
  383. default:
  384. throw new Error( 'Invalid component type.' );
  385. }
  386. }
  387. function normalize( value, array ) {
  388. switch ( array.constructor ) {
  389. case Float32Array:
  390. return value;
  391. case Uint16Array:
  392. return Math.round( value * 65535.0 );
  393. case Uint8Array:
  394. return Math.round( value * 255.0 );
  395. case Int16Array:
  396. return Math.round( value * 32767.0 );
  397. case Int8Array:
  398. return Math.round( value * 127.0 );
  399. default:
  400. throw new Error( 'Invalid component type.' );
  401. }
  402. }
  403. const MathUtils = {
  404. DEG2RAD: DEG2RAD,
  405. RAD2DEG: RAD2DEG,
  406. generateUUID: generateUUID,
  407. clamp: clamp,
  408. euclideanModulo: euclideanModulo,
  409. mapLinear: mapLinear,
  410. inverseLerp: inverseLerp,
  411. lerp: lerp,
  412. damp: damp,
  413. pingpong: pingpong,
  414. smoothstep: smoothstep,
  415. smootherstep: smootherstep,
  416. randInt: randInt,
  417. randFloat: randFloat,
  418. randFloatSpread: randFloatSpread,
  419. seededRandom: seededRandom,
  420. degToRad: degToRad,
  421. radToDeg: radToDeg,
  422. isPowerOfTwo: isPowerOfTwo,
  423. ceilPowerOfTwo: ceilPowerOfTwo,
  424. floorPowerOfTwo: floorPowerOfTwo,
  425. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  426. normalize: normalize,
  427. denormalize: denormalize
  428. };
  429. class Vector2 {
  430. constructor( x = 0, y = 0 ) {
  431. Vector2.prototype.isVector2 = true;
  432. this.x = x;
  433. this.y = y;
  434. }
  435. get width() {
  436. return this.x;
  437. }
  438. set width( value ) {
  439. this.x = value;
  440. }
  441. get height() {
  442. return this.y;
  443. }
  444. set height( value ) {
  445. this.y = value;
  446. }
  447. set( x, y ) {
  448. this.x = x;
  449. this.y = y;
  450. return this;
  451. }
  452. setScalar( scalar ) {
  453. this.x = scalar;
  454. this.y = scalar;
  455. return this;
  456. }
  457. setX( x ) {
  458. this.x = x;
  459. return this;
  460. }
  461. setY( y ) {
  462. this.y = y;
  463. return this;
  464. }
  465. setComponent( index, value ) {
  466. switch ( index ) {
  467. case 0: this.x = value; break;
  468. case 1: this.y = value; break;
  469. default: throw new Error( 'index is out of range: ' + index );
  470. }
  471. return this;
  472. }
  473. getComponent( index ) {
  474. switch ( index ) {
  475. case 0: return this.x;
  476. case 1: return this.y;
  477. default: throw new Error( 'index is out of range: ' + index );
  478. }
  479. }
  480. clone() {
  481. return new this.constructor( this.x, this.y );
  482. }
  483. copy( v ) {
  484. this.x = v.x;
  485. this.y = v.y;
  486. return this;
  487. }
  488. add( v ) {
  489. this.x += v.x;
  490. this.y += v.y;
  491. return this;
  492. }
  493. addScalar( s ) {
  494. this.x += s;
  495. this.y += s;
  496. return this;
  497. }
  498. addVectors( a, b ) {
  499. this.x = a.x + b.x;
  500. this.y = a.y + b.y;
  501. return this;
  502. }
  503. addScaledVector( v, s ) {
  504. this.x += v.x * s;
  505. this.y += v.y * s;
  506. return this;
  507. }
  508. sub( v ) {
  509. this.x -= v.x;
  510. this.y -= v.y;
  511. return this;
  512. }
  513. subScalar( s ) {
  514. this.x -= s;
  515. this.y -= s;
  516. return this;
  517. }
  518. subVectors( a, b ) {
  519. this.x = a.x - b.x;
  520. this.y = a.y - b.y;
  521. return this;
  522. }
  523. multiply( v ) {
  524. this.x *= v.x;
  525. this.y *= v.y;
  526. return this;
  527. }
  528. multiplyScalar( scalar ) {
  529. this.x *= scalar;
  530. this.y *= scalar;
  531. return this;
  532. }
  533. divide( v ) {
  534. this.x /= v.x;
  535. this.y /= v.y;
  536. return this;
  537. }
  538. divideScalar( scalar ) {
  539. return this.multiplyScalar( 1 / scalar );
  540. }
  541. applyMatrix3( m ) {
  542. const x = this.x, y = this.y;
  543. const e = m.elements;
  544. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  545. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  546. return this;
  547. }
  548. min( v ) {
  549. this.x = Math.min( this.x, v.x );
  550. this.y = Math.min( this.y, v.y );
  551. return this;
  552. }
  553. max( v ) {
  554. this.x = Math.max( this.x, v.x );
  555. this.y = Math.max( this.y, v.y );
  556. return this;
  557. }
  558. clamp( min, max ) {
  559. // assumes min < max, componentwise
  560. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  561. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  562. return this;
  563. }
  564. clampScalar( minVal, maxVal ) {
  565. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  566. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  567. return this;
  568. }
  569. clampLength( min, max ) {
  570. const length = this.length();
  571. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  572. }
  573. floor() {
  574. this.x = Math.floor( this.x );
  575. this.y = Math.floor( this.y );
  576. return this;
  577. }
  578. ceil() {
  579. this.x = Math.ceil( this.x );
  580. this.y = Math.ceil( this.y );
  581. return this;
  582. }
  583. round() {
  584. this.x = Math.round( this.x );
  585. this.y = Math.round( this.y );
  586. return this;
  587. }
  588. roundToZero() {
  589. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  590. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  591. return this;
  592. }
  593. negate() {
  594. this.x = - this.x;
  595. this.y = - this.y;
  596. return this;
  597. }
  598. dot( v ) {
  599. return this.x * v.x + this.y * v.y;
  600. }
  601. cross( v ) {
  602. return this.x * v.y - this.y * v.x;
  603. }
  604. lengthSq() {
  605. return this.x * this.x + this.y * this.y;
  606. }
  607. length() {
  608. return Math.sqrt( this.x * this.x + this.y * this.y );
  609. }
  610. manhattanLength() {
  611. return Math.abs( this.x ) + Math.abs( this.y );
  612. }
  613. normalize() {
  614. return this.divideScalar( this.length() || 1 );
  615. }
  616. angle() {
  617. // computes the angle in radians with respect to the positive x-axis
  618. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  619. return angle;
  620. }
  621. distanceTo( v ) {
  622. return Math.sqrt( this.distanceToSquared( v ) );
  623. }
  624. distanceToSquared( v ) {
  625. const dx = this.x - v.x, dy = this.y - v.y;
  626. return dx * dx + dy * dy;
  627. }
  628. manhattanDistanceTo( v ) {
  629. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  630. }
  631. setLength( length ) {
  632. return this.normalize().multiplyScalar( length );
  633. }
  634. lerp( v, alpha ) {
  635. this.x += ( v.x - this.x ) * alpha;
  636. this.y += ( v.y - this.y ) * alpha;
  637. return this;
  638. }
  639. lerpVectors( v1, v2, alpha ) {
  640. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  641. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  642. return this;
  643. }
  644. equals( v ) {
  645. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  646. }
  647. fromArray( array, offset = 0 ) {
  648. this.x = array[ offset ];
  649. this.y = array[ offset + 1 ];
  650. return this;
  651. }
  652. toArray( array = [], offset = 0 ) {
  653. array[ offset ] = this.x;
  654. array[ offset + 1 ] = this.y;
  655. return array;
  656. }
  657. fromBufferAttribute( attribute, index ) {
  658. this.x = attribute.getX( index );
  659. this.y = attribute.getY( index );
  660. return this;
  661. }
  662. rotateAround( center, angle ) {
  663. const c = Math.cos( angle ), s = Math.sin( angle );
  664. const x = this.x - center.x;
  665. const y = this.y - center.y;
  666. this.x = x * c - y * s + center.x;
  667. this.y = x * s + y * c + center.y;
  668. return this;
  669. }
  670. random() {
  671. this.x = Math.random();
  672. this.y = Math.random();
  673. return this;
  674. }
  675. *[ Symbol.iterator ]() {
  676. yield this.x;
  677. yield this.y;
  678. }
  679. }
  680. class Matrix3 {
  681. constructor() {
  682. Matrix3.prototype.isMatrix3 = true;
  683. this.elements = [
  684. 1, 0, 0,
  685. 0, 1, 0,
  686. 0, 0, 1
  687. ];
  688. }
  689. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  690. const te = this.elements;
  691. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  692. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  693. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  694. return this;
  695. }
  696. identity() {
  697. this.set(
  698. 1, 0, 0,
  699. 0, 1, 0,
  700. 0, 0, 1
  701. );
  702. return this;
  703. }
  704. copy( m ) {
  705. const te = this.elements;
  706. const me = m.elements;
  707. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  708. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  709. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  710. return this;
  711. }
  712. extractBasis( xAxis, yAxis, zAxis ) {
  713. xAxis.setFromMatrix3Column( this, 0 );
  714. yAxis.setFromMatrix3Column( this, 1 );
  715. zAxis.setFromMatrix3Column( this, 2 );
  716. return this;
  717. }
  718. setFromMatrix4( m ) {
  719. const me = m.elements;
  720. this.set(
  721. me[ 0 ], me[ 4 ], me[ 8 ],
  722. me[ 1 ], me[ 5 ], me[ 9 ],
  723. me[ 2 ], me[ 6 ], me[ 10 ]
  724. );
  725. return this;
  726. }
  727. multiply( m ) {
  728. return this.multiplyMatrices( this, m );
  729. }
  730. premultiply( m ) {
  731. return this.multiplyMatrices( m, this );
  732. }
  733. multiplyMatrices( a, b ) {
  734. const ae = a.elements;
  735. const be = b.elements;
  736. const te = this.elements;
  737. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  738. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  739. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  740. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  741. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  742. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  743. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  744. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  745. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  746. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  747. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  748. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  749. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  750. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  751. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  752. return this;
  753. }
  754. multiplyScalar( s ) {
  755. const te = this.elements;
  756. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  757. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  758. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  759. return this;
  760. }
  761. determinant() {
  762. const te = this.elements;
  763. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  764. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  765. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  766. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  767. }
  768. invert() {
  769. const te = this.elements,
  770. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  771. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  772. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  773. t11 = n33 * n22 - n32 * n23,
  774. t12 = n32 * n13 - n33 * n12,
  775. t13 = n23 * n12 - n22 * n13,
  776. det = n11 * t11 + n21 * t12 + n31 * t13;
  777. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  778. const detInv = 1 / det;
  779. te[ 0 ] = t11 * detInv;
  780. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  781. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  782. te[ 3 ] = t12 * detInv;
  783. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  784. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  785. te[ 6 ] = t13 * detInv;
  786. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  787. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  788. return this;
  789. }
  790. transpose() {
  791. let tmp;
  792. const m = this.elements;
  793. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  794. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  795. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  796. return this;
  797. }
  798. getNormalMatrix( matrix4 ) {
  799. return this.setFromMatrix4( matrix4 ).invert().transpose();
  800. }
  801. transposeIntoArray( r ) {
  802. const m = this.elements;
  803. r[ 0 ] = m[ 0 ];
  804. r[ 1 ] = m[ 3 ];
  805. r[ 2 ] = m[ 6 ];
  806. r[ 3 ] = m[ 1 ];
  807. r[ 4 ] = m[ 4 ];
  808. r[ 5 ] = m[ 7 ];
  809. r[ 6 ] = m[ 2 ];
  810. r[ 7 ] = m[ 5 ];
  811. r[ 8 ] = m[ 8 ];
  812. return this;
  813. }
  814. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  815. const c = Math.cos( rotation );
  816. const s = Math.sin( rotation );
  817. this.set(
  818. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  819. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  820. 0, 0, 1
  821. );
  822. return this;
  823. }
  824. //
  825. scale( sx, sy ) {
  826. this.premultiply( _m3.makeScale( sx, sy ) );
  827. return this;
  828. }
  829. rotate( theta ) {
  830. this.premultiply( _m3.makeRotation( - theta ) );
  831. return this;
  832. }
  833. translate( tx, ty ) {
  834. this.premultiply( _m3.makeTranslation( tx, ty ) );
  835. return this;
  836. }
  837. // for 2D Transforms
  838. makeTranslation( x, y ) {
  839. this.set(
  840. 1, 0, x,
  841. 0, 1, y,
  842. 0, 0, 1
  843. );
  844. return this;
  845. }
  846. makeRotation( theta ) {
  847. // counterclockwise
  848. const c = Math.cos( theta );
  849. const s = Math.sin( theta );
  850. this.set(
  851. c, - s, 0,
  852. s, c, 0,
  853. 0, 0, 1
  854. );
  855. return this;
  856. }
  857. makeScale( x, y ) {
  858. this.set(
  859. x, 0, 0,
  860. 0, y, 0,
  861. 0, 0, 1
  862. );
  863. return this;
  864. }
  865. //
  866. equals( matrix ) {
  867. const te = this.elements;
  868. const me = matrix.elements;
  869. for ( let i = 0; i < 9; i ++ ) {
  870. if ( te[ i ] !== me[ i ] ) return false;
  871. }
  872. return true;
  873. }
  874. fromArray( array, offset = 0 ) {
  875. for ( let i = 0; i < 9; i ++ ) {
  876. this.elements[ i ] = array[ i + offset ];
  877. }
  878. return this;
  879. }
  880. toArray( array = [], offset = 0 ) {
  881. const te = this.elements;
  882. array[ offset ] = te[ 0 ];
  883. array[ offset + 1 ] = te[ 1 ];
  884. array[ offset + 2 ] = te[ 2 ];
  885. array[ offset + 3 ] = te[ 3 ];
  886. array[ offset + 4 ] = te[ 4 ];
  887. array[ offset + 5 ] = te[ 5 ];
  888. array[ offset + 6 ] = te[ 6 ];
  889. array[ offset + 7 ] = te[ 7 ];
  890. array[ offset + 8 ] = te[ 8 ];
  891. return array;
  892. }
  893. clone() {
  894. return new this.constructor().fromArray( this.elements );
  895. }
  896. }
  897. const _m3 = /*@__PURE__*/ new Matrix3();
  898. function arrayNeedsUint32( array ) {
  899. // assumes larger values usually on last
  900. for ( let i = array.length - 1; i >= 0; -- i ) {
  901. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  902. }
  903. return false;
  904. }
  905. const TYPED_ARRAYS = {
  906. Int8Array: Int8Array,
  907. Uint8Array: Uint8Array,
  908. Uint8ClampedArray: Uint8ClampedArray,
  909. Int16Array: Int16Array,
  910. Uint16Array: Uint16Array,
  911. Int32Array: Int32Array,
  912. Uint32Array: Uint32Array,
  913. Float32Array: Float32Array,
  914. Float64Array: Float64Array
  915. };
  916. function getTypedArray( type, buffer ) {
  917. return new TYPED_ARRAYS[ type ]( buffer );
  918. }
  919. function createElementNS( name ) {
  920. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  921. }
  922. class Quaternion {
  923. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  924. this.isQuaternion = true;
  925. this._x = x;
  926. this._y = y;
  927. this._z = z;
  928. this._w = w;
  929. }
  930. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  931. // fuzz-free, array-based Quaternion SLERP operation
  932. let x0 = src0[ srcOffset0 + 0 ],
  933. y0 = src0[ srcOffset0 + 1 ],
  934. z0 = src0[ srcOffset0 + 2 ],
  935. w0 = src0[ srcOffset0 + 3 ];
  936. const x1 = src1[ srcOffset1 + 0 ],
  937. y1 = src1[ srcOffset1 + 1 ],
  938. z1 = src1[ srcOffset1 + 2 ],
  939. w1 = src1[ srcOffset1 + 3 ];
  940. if ( t === 0 ) {
  941. dst[ dstOffset + 0 ] = x0;
  942. dst[ dstOffset + 1 ] = y0;
  943. dst[ dstOffset + 2 ] = z0;
  944. dst[ dstOffset + 3 ] = w0;
  945. return;
  946. }
  947. if ( t === 1 ) {
  948. dst[ dstOffset + 0 ] = x1;
  949. dst[ dstOffset + 1 ] = y1;
  950. dst[ dstOffset + 2 ] = z1;
  951. dst[ dstOffset + 3 ] = w1;
  952. return;
  953. }
  954. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  955. let s = 1 - t;
  956. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  957. dir = ( cos >= 0 ? 1 : - 1 ),
  958. sqrSin = 1 - cos * cos;
  959. // Skip the Slerp for tiny steps to avoid numeric problems:
  960. if ( sqrSin > Number.EPSILON ) {
  961. const sin = Math.sqrt( sqrSin ),
  962. len = Math.atan2( sin, cos * dir );
  963. s = Math.sin( s * len ) / sin;
  964. t = Math.sin( t * len ) / sin;
  965. }
  966. const tDir = t * dir;
  967. x0 = x0 * s + x1 * tDir;
  968. y0 = y0 * s + y1 * tDir;
  969. z0 = z0 * s + z1 * tDir;
  970. w0 = w0 * s + w1 * tDir;
  971. // Normalize in case we just did a lerp:
  972. if ( s === 1 - t ) {
  973. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  974. x0 *= f;
  975. y0 *= f;
  976. z0 *= f;
  977. w0 *= f;
  978. }
  979. }
  980. dst[ dstOffset ] = x0;
  981. dst[ dstOffset + 1 ] = y0;
  982. dst[ dstOffset + 2 ] = z0;
  983. dst[ dstOffset + 3 ] = w0;
  984. }
  985. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  986. const x0 = src0[ srcOffset0 ];
  987. const y0 = src0[ srcOffset0 + 1 ];
  988. const z0 = src0[ srcOffset0 + 2 ];
  989. const w0 = src0[ srcOffset0 + 3 ];
  990. const x1 = src1[ srcOffset1 ];
  991. const y1 = src1[ srcOffset1 + 1 ];
  992. const z1 = src1[ srcOffset1 + 2 ];
  993. const w1 = src1[ srcOffset1 + 3 ];
  994. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  995. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  996. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  997. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  998. return dst;
  999. }
  1000. get x() {
  1001. return this._x;
  1002. }
  1003. set x( value ) {
  1004. this._x = value;
  1005. this._onChangeCallback();
  1006. }
  1007. get y() {
  1008. return this._y;
  1009. }
  1010. set y( value ) {
  1011. this._y = value;
  1012. this._onChangeCallback();
  1013. }
  1014. get z() {
  1015. return this._z;
  1016. }
  1017. set z( value ) {
  1018. this._z = value;
  1019. this._onChangeCallback();
  1020. }
  1021. get w() {
  1022. return this._w;
  1023. }
  1024. set w( value ) {
  1025. this._w = value;
  1026. this._onChangeCallback();
  1027. }
  1028. set( x, y, z, w ) {
  1029. this._x = x;
  1030. this._y = y;
  1031. this._z = z;
  1032. this._w = w;
  1033. this._onChangeCallback();
  1034. return this;
  1035. }
  1036. clone() {
  1037. return new this.constructor( this._x, this._y, this._z, this._w );
  1038. }
  1039. copy( quaternion ) {
  1040. this._x = quaternion.x;
  1041. this._y = quaternion.y;
  1042. this._z = quaternion.z;
  1043. this._w = quaternion.w;
  1044. this._onChangeCallback();
  1045. return this;
  1046. }
  1047. setFromEuler( euler, update ) {
  1048. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1049. // http://www.mathworks.com/matlabcentral/fileexchange/
  1050. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1051. // content/SpinCalc.m
  1052. const cos = Math.cos;
  1053. const sin = Math.sin;
  1054. const c1 = cos( x / 2 );
  1055. const c2 = cos( y / 2 );
  1056. const c3 = cos( z / 2 );
  1057. const s1 = sin( x / 2 );
  1058. const s2 = sin( y / 2 );
  1059. const s3 = sin( z / 2 );
  1060. switch ( order ) {
  1061. case 'XYZ':
  1062. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1063. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1064. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1065. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1066. break;
  1067. case 'YXZ':
  1068. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1069. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1070. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1071. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1072. break;
  1073. case 'ZXY':
  1074. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1075. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1076. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1077. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1078. break;
  1079. case 'ZYX':
  1080. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1081. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1082. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1083. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1084. break;
  1085. case 'YZX':
  1086. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1087. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1088. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1089. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1090. break;
  1091. case 'XZY':
  1092. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1093. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1094. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1095. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1096. break;
  1097. default:
  1098. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  1099. }
  1100. if ( update !== false ) this._onChangeCallback();
  1101. return this;
  1102. }
  1103. setFromAxisAngle( axis, angle ) {
  1104. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1105. // assumes axis is normalized
  1106. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  1107. this._x = axis.x * s;
  1108. this._y = axis.y * s;
  1109. this._z = axis.z * s;
  1110. this._w = Math.cos( halfAngle );
  1111. this._onChangeCallback();
  1112. return this;
  1113. }
  1114. setFromRotationMatrix( m ) {
  1115. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1116. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1117. const te = m.elements,
  1118. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1119. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1120. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1121. trace = m11 + m22 + m33;
  1122. if ( trace > 0 ) {
  1123. const s = 0.5 / Math.sqrt( trace + 1.0 );
  1124. this._w = 0.25 / s;
  1125. this._x = ( m32 - m23 ) * s;
  1126. this._y = ( m13 - m31 ) * s;
  1127. this._z = ( m21 - m12 ) * s;
  1128. } else if ( m11 > m22 && m11 > m33 ) {
  1129. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1130. this._w = ( m32 - m23 ) / s;
  1131. this._x = 0.25 * s;
  1132. this._y = ( m12 + m21 ) / s;
  1133. this._z = ( m13 + m31 ) / s;
  1134. } else if ( m22 > m33 ) {
  1135. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1136. this._w = ( m13 - m31 ) / s;
  1137. this._x = ( m12 + m21 ) / s;
  1138. this._y = 0.25 * s;
  1139. this._z = ( m23 + m32 ) / s;
  1140. } else {
  1141. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1142. this._w = ( m21 - m12 ) / s;
  1143. this._x = ( m13 + m31 ) / s;
  1144. this._y = ( m23 + m32 ) / s;
  1145. this._z = 0.25 * s;
  1146. }
  1147. this._onChangeCallback();
  1148. return this;
  1149. }
  1150. setFromUnitVectors( vFrom, vTo ) {
  1151. // assumes direction vectors vFrom and vTo are normalized
  1152. let r = vFrom.dot( vTo ) + 1;
  1153. if ( r < Number.EPSILON ) {
  1154. // vFrom and vTo point in opposite directions
  1155. r = 0;
  1156. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1157. this._x = - vFrom.y;
  1158. this._y = vFrom.x;
  1159. this._z = 0;
  1160. this._w = r;
  1161. } else {
  1162. this._x = 0;
  1163. this._y = - vFrom.z;
  1164. this._z = vFrom.y;
  1165. this._w = r;
  1166. }
  1167. } else {
  1168. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1169. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1170. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1171. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1172. this._w = r;
  1173. }
  1174. return this.normalize();
  1175. }
  1176. angleTo( q ) {
  1177. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  1178. }
  1179. rotateTowards( q, step ) {
  1180. const angle = this.angleTo( q );
  1181. if ( angle === 0 ) return this;
  1182. const t = Math.min( 1, step / angle );
  1183. this.slerp( q, t );
  1184. return this;
  1185. }
  1186. identity() {
  1187. return this.set( 0, 0, 0, 1 );
  1188. }
  1189. invert() {
  1190. // quaternion is assumed to have unit length
  1191. return this.conjugate();
  1192. }
  1193. conjugate() {
  1194. this._x *= - 1;
  1195. this._y *= - 1;
  1196. this._z *= - 1;
  1197. this._onChangeCallback();
  1198. return this;
  1199. }
  1200. dot( v ) {
  1201. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1202. }
  1203. lengthSq() {
  1204. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1205. }
  1206. length() {
  1207. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1208. }
  1209. normalize() {
  1210. let l = this.length();
  1211. if ( l === 0 ) {
  1212. this._x = 0;
  1213. this._y = 0;
  1214. this._z = 0;
  1215. this._w = 1;
  1216. } else {
  1217. l = 1 / l;
  1218. this._x = this._x * l;
  1219. this._y = this._y * l;
  1220. this._z = this._z * l;
  1221. this._w = this._w * l;
  1222. }
  1223. this._onChangeCallback();
  1224. return this;
  1225. }
  1226. multiply( q ) {
  1227. return this.multiplyQuaternions( this, q );
  1228. }
  1229. premultiply( q ) {
  1230. return this.multiplyQuaternions( q, this );
  1231. }
  1232. multiplyQuaternions( a, b ) {
  1233. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1234. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1235. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1236. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1237. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1238. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1239. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1240. this._onChangeCallback();
  1241. return this;
  1242. }
  1243. slerp( qb, t ) {
  1244. if ( t === 0 ) return this;
  1245. if ( t === 1 ) return this.copy( qb );
  1246. const x = this._x, y = this._y, z = this._z, w = this._w;
  1247. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1248. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1249. if ( cosHalfTheta < 0 ) {
  1250. this._w = - qb._w;
  1251. this._x = - qb._x;
  1252. this._y = - qb._y;
  1253. this._z = - qb._z;
  1254. cosHalfTheta = - cosHalfTheta;
  1255. } else {
  1256. this.copy( qb );
  1257. }
  1258. if ( cosHalfTheta >= 1.0 ) {
  1259. this._w = w;
  1260. this._x = x;
  1261. this._y = y;
  1262. this._z = z;
  1263. return this;
  1264. }
  1265. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  1266. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  1267. const s = 1 - t;
  1268. this._w = s * w + t * this._w;
  1269. this._x = s * x + t * this._x;
  1270. this._y = s * y + t * this._y;
  1271. this._z = s * z + t * this._z;
  1272. this.normalize();
  1273. this._onChangeCallback();
  1274. return this;
  1275. }
  1276. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  1277. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1278. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1279. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1280. this._w = ( w * ratioA + this._w * ratioB );
  1281. this._x = ( x * ratioA + this._x * ratioB );
  1282. this._y = ( y * ratioA + this._y * ratioB );
  1283. this._z = ( z * ratioA + this._z * ratioB );
  1284. this._onChangeCallback();
  1285. return this;
  1286. }
  1287. slerpQuaternions( qa, qb, t ) {
  1288. return this.copy( qa ).slerp( qb, t );
  1289. }
  1290. random() {
  1291. // Derived from http://planning.cs.uiuc.edu/node198.html
  1292. // Note, this source uses w, x, y, z ordering,
  1293. // so we swap the order below.
  1294. const u1 = Math.random();
  1295. const sqrt1u1 = Math.sqrt( 1 - u1 );
  1296. const sqrtu1 = Math.sqrt( u1 );
  1297. const u2 = 2 * Math.PI * Math.random();
  1298. const u3 = 2 * Math.PI * Math.random();
  1299. return this.set(
  1300. sqrt1u1 * Math.cos( u2 ),
  1301. sqrtu1 * Math.sin( u3 ),
  1302. sqrtu1 * Math.cos( u3 ),
  1303. sqrt1u1 * Math.sin( u2 ),
  1304. );
  1305. }
  1306. equals( quaternion ) {
  1307. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1308. }
  1309. fromArray( array, offset = 0 ) {
  1310. this._x = array[ offset ];
  1311. this._y = array[ offset + 1 ];
  1312. this._z = array[ offset + 2 ];
  1313. this._w = array[ offset + 3 ];
  1314. this._onChangeCallback();
  1315. return this;
  1316. }
  1317. toArray( array = [], offset = 0 ) {
  1318. array[ offset ] = this._x;
  1319. array[ offset + 1 ] = this._y;
  1320. array[ offset + 2 ] = this._z;
  1321. array[ offset + 3 ] = this._w;
  1322. return array;
  1323. }
  1324. fromBufferAttribute( attribute, index ) {
  1325. this._x = attribute.getX( index );
  1326. this._y = attribute.getY( index );
  1327. this._z = attribute.getZ( index );
  1328. this._w = attribute.getW( index );
  1329. return this;
  1330. }
  1331. _onChange( callback ) {
  1332. this._onChangeCallback = callback;
  1333. return this;
  1334. }
  1335. _onChangeCallback() {}
  1336. *[ Symbol.iterator ]() {
  1337. yield this._x;
  1338. yield this._y;
  1339. yield this._z;
  1340. yield this._w;
  1341. }
  1342. }
  1343. class Vector3 {
  1344. constructor( x = 0, y = 0, z = 0 ) {
  1345. Vector3.prototype.isVector3 = true;
  1346. this.x = x;
  1347. this.y = y;
  1348. this.z = z;
  1349. }
  1350. set( x, y, z ) {
  1351. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  1352. this.x = x;
  1353. this.y = y;
  1354. this.z = z;
  1355. return this;
  1356. }
  1357. setScalar( scalar ) {
  1358. this.x = scalar;
  1359. this.y = scalar;
  1360. this.z = scalar;
  1361. return this;
  1362. }
  1363. setX( x ) {
  1364. this.x = x;
  1365. return this;
  1366. }
  1367. setY( y ) {
  1368. this.y = y;
  1369. return this;
  1370. }
  1371. setZ( z ) {
  1372. this.z = z;
  1373. return this;
  1374. }
  1375. setComponent( index, value ) {
  1376. switch ( index ) {
  1377. case 0: this.x = value; break;
  1378. case 1: this.y = value; break;
  1379. case 2: this.z = value; break;
  1380. default: throw new Error( 'index is out of range: ' + index );
  1381. }
  1382. return this;
  1383. }
  1384. getComponent( index ) {
  1385. switch ( index ) {
  1386. case 0: return this.x;
  1387. case 1: return this.y;
  1388. case 2: return this.z;
  1389. default: throw new Error( 'index is out of range: ' + index );
  1390. }
  1391. }
  1392. clone() {
  1393. return new this.constructor( this.x, this.y, this.z );
  1394. }
  1395. copy( v ) {
  1396. this.x = v.x;
  1397. this.y = v.y;
  1398. this.z = v.z;
  1399. return this;
  1400. }
  1401. add( v ) {
  1402. this.x += v.x;
  1403. this.y += v.y;
  1404. this.z += v.z;
  1405. return this;
  1406. }
  1407. addScalar( s ) {
  1408. this.x += s;
  1409. this.y += s;
  1410. this.z += s;
  1411. return this;
  1412. }
  1413. addVectors( a, b ) {
  1414. this.x = a.x + b.x;
  1415. this.y = a.y + b.y;
  1416. this.z = a.z + b.z;
  1417. return this;
  1418. }
  1419. addScaledVector( v, s ) {
  1420. this.x += v.x * s;
  1421. this.y += v.y * s;
  1422. this.z += v.z * s;
  1423. return this;
  1424. }
  1425. sub( v ) {
  1426. this.x -= v.x;
  1427. this.y -= v.y;
  1428. this.z -= v.z;
  1429. return this;
  1430. }
  1431. subScalar( s ) {
  1432. this.x -= s;
  1433. this.y -= s;
  1434. this.z -= s;
  1435. return this;
  1436. }
  1437. subVectors( a, b ) {
  1438. this.x = a.x - b.x;
  1439. this.y = a.y - b.y;
  1440. this.z = a.z - b.z;
  1441. return this;
  1442. }
  1443. multiply( v ) {
  1444. this.x *= v.x;
  1445. this.y *= v.y;
  1446. this.z *= v.z;
  1447. return this;
  1448. }
  1449. multiplyScalar( scalar ) {
  1450. this.x *= scalar;
  1451. this.y *= scalar;
  1452. this.z *= scalar;
  1453. return this;
  1454. }
  1455. multiplyVectors( a, b ) {
  1456. this.x = a.x * b.x;
  1457. this.y = a.y * b.y;
  1458. this.z = a.z * b.z;
  1459. return this;
  1460. }
  1461. applyEuler( euler ) {
  1462. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  1463. }
  1464. applyAxisAngle( axis, angle ) {
  1465. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  1466. }
  1467. applyMatrix3( m ) {
  1468. const x = this.x, y = this.y, z = this.z;
  1469. const e = m.elements;
  1470. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1471. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1472. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1473. return this;
  1474. }
  1475. applyNormalMatrix( m ) {
  1476. return this.applyMatrix3( m ).normalize();
  1477. }
  1478. applyMatrix4( m ) {
  1479. const x = this.x, y = this.y, z = this.z;
  1480. const e = m.elements;
  1481. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  1482. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  1483. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  1484. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  1485. return this;
  1486. }
  1487. applyQuaternion( q ) {
  1488. const x = this.x, y = this.y, z = this.z;
  1489. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1490. // calculate quat * vector
  1491. const ix = qw * x + qy * z - qz * y;
  1492. const iy = qw * y + qz * x - qx * z;
  1493. const iz = qw * z + qx * y - qy * x;
  1494. const iw = - qx * x - qy * y - qz * z;
  1495. // calculate result * inverse quat
  1496. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1497. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1498. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1499. return this;
  1500. }
  1501. project( camera ) {
  1502. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  1503. }
  1504. unproject( camera ) {
  1505. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  1506. }
  1507. transformDirection( m ) {
  1508. // input: THREE.Matrix4 affine matrix
  1509. // vector interpreted as a direction
  1510. const x = this.x, y = this.y, z = this.z;
  1511. const e = m.elements;
  1512. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1513. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1514. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1515. return this.normalize();
  1516. }
  1517. divide( v ) {
  1518. this.x /= v.x;
  1519. this.y /= v.y;
  1520. this.z /= v.z;
  1521. return this;
  1522. }
  1523. divideScalar( scalar ) {
  1524. return this.multiplyScalar( 1 / scalar );
  1525. }
  1526. min( v ) {
  1527. this.x = Math.min( this.x, v.x );
  1528. this.y = Math.min( this.y, v.y );
  1529. this.z = Math.min( this.z, v.z );
  1530. return this;
  1531. }
  1532. max( v ) {
  1533. this.x = Math.max( this.x, v.x );
  1534. this.y = Math.max( this.y, v.y );
  1535. this.z = Math.max( this.z, v.z );
  1536. return this;
  1537. }
  1538. clamp( min, max ) {
  1539. // assumes min < max, componentwise
  1540. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1541. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1542. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1543. return this;
  1544. }
  1545. clampScalar( minVal, maxVal ) {
  1546. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1547. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1548. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1549. return this;
  1550. }
  1551. clampLength( min, max ) {
  1552. const length = this.length();
  1553. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1554. }
  1555. floor() {
  1556. this.x = Math.floor( this.x );
  1557. this.y = Math.floor( this.y );
  1558. this.z = Math.floor( this.z );
  1559. return this;
  1560. }
  1561. ceil() {
  1562. this.x = Math.ceil( this.x );
  1563. this.y = Math.ceil( this.y );
  1564. this.z = Math.ceil( this.z );
  1565. return this;
  1566. }
  1567. round() {
  1568. this.x = Math.round( this.x );
  1569. this.y = Math.round( this.y );
  1570. this.z = Math.round( this.z );
  1571. return this;
  1572. }
  1573. roundToZero() {
  1574. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1575. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1576. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1577. return this;
  1578. }
  1579. negate() {
  1580. this.x = - this.x;
  1581. this.y = - this.y;
  1582. this.z = - this.z;
  1583. return this;
  1584. }
  1585. dot( v ) {
  1586. return this.x * v.x + this.y * v.y + this.z * v.z;
  1587. }
  1588. // TODO lengthSquared?
  1589. lengthSq() {
  1590. return this.x * this.x + this.y * this.y + this.z * this.z;
  1591. }
  1592. length() {
  1593. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1594. }
  1595. manhattanLength() {
  1596. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1597. }
  1598. normalize() {
  1599. return this.divideScalar( this.length() || 1 );
  1600. }
  1601. setLength( length ) {
  1602. return this.normalize().multiplyScalar( length );
  1603. }
  1604. lerp( v, alpha ) {
  1605. this.x += ( v.x - this.x ) * alpha;
  1606. this.y += ( v.y - this.y ) * alpha;
  1607. this.z += ( v.z - this.z ) * alpha;
  1608. return this;
  1609. }
  1610. lerpVectors( v1, v2, alpha ) {
  1611. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1612. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1613. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1614. return this;
  1615. }
  1616. cross( v ) {
  1617. return this.crossVectors( this, v );
  1618. }
  1619. crossVectors( a, b ) {
  1620. const ax = a.x, ay = a.y, az = a.z;
  1621. const bx = b.x, by = b.y, bz = b.z;
  1622. this.x = ay * bz - az * by;
  1623. this.y = az * bx - ax * bz;
  1624. this.z = ax * by - ay * bx;
  1625. return this;
  1626. }
  1627. projectOnVector( v ) {
  1628. const denominator = v.lengthSq();
  1629. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  1630. const scalar = v.dot( this ) / denominator;
  1631. return this.copy( v ).multiplyScalar( scalar );
  1632. }
  1633. projectOnPlane( planeNormal ) {
  1634. _vector$c.copy( this ).projectOnVector( planeNormal );
  1635. return this.sub( _vector$c );
  1636. }
  1637. reflect( normal ) {
  1638. // reflect incident vector off plane orthogonal to normal
  1639. // normal is assumed to have unit length
  1640. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1641. }
  1642. angleTo( v ) {
  1643. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  1644. if ( denominator === 0 ) return Math.PI / 2;
  1645. const theta = this.dot( v ) / denominator;
  1646. // clamp, to handle numerical problems
  1647. return Math.acos( clamp( theta, - 1, 1 ) );
  1648. }
  1649. distanceTo( v ) {
  1650. return Math.sqrt( this.distanceToSquared( v ) );
  1651. }
  1652. distanceToSquared( v ) {
  1653. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1654. return dx * dx + dy * dy + dz * dz;
  1655. }
  1656. manhattanDistanceTo( v ) {
  1657. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1658. }
  1659. setFromSpherical( s ) {
  1660. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  1661. }
  1662. setFromSphericalCoords( radius, phi, theta ) {
  1663. const sinPhiRadius = Math.sin( phi ) * radius;
  1664. this.x = sinPhiRadius * Math.sin( theta );
  1665. this.y = Math.cos( phi ) * radius;
  1666. this.z = sinPhiRadius * Math.cos( theta );
  1667. return this;
  1668. }
  1669. setFromCylindrical( c ) {
  1670. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  1671. }
  1672. setFromCylindricalCoords( radius, theta, y ) {
  1673. this.x = radius * Math.sin( theta );
  1674. this.y = y;
  1675. this.z = radius * Math.cos( theta );
  1676. return this;
  1677. }
  1678. setFromMatrixPosition( m ) {
  1679. const e = m.elements;
  1680. this.x = e[ 12 ];
  1681. this.y = e[ 13 ];
  1682. this.z = e[ 14 ];
  1683. return this;
  1684. }
  1685. setFromMatrixScale( m ) {
  1686. const sx = this.setFromMatrixColumn( m, 0 ).length();
  1687. const sy = this.setFromMatrixColumn( m, 1 ).length();
  1688. const sz = this.setFromMatrixColumn( m, 2 ).length();
  1689. this.x = sx;
  1690. this.y = sy;
  1691. this.z = sz;
  1692. return this;
  1693. }
  1694. setFromMatrixColumn( m, index ) {
  1695. return this.fromArray( m.elements, index * 4 );
  1696. }
  1697. setFromMatrix3Column( m, index ) {
  1698. return this.fromArray( m.elements, index * 3 );
  1699. }
  1700. setFromEuler( e ) {
  1701. this.x = e._x;
  1702. this.y = e._y;
  1703. this.z = e._z;
  1704. return this;
  1705. }
  1706. equals( v ) {
  1707. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1708. }
  1709. fromArray( array, offset = 0 ) {
  1710. this.x = array[ offset ];
  1711. this.y = array[ offset + 1 ];
  1712. this.z = array[ offset + 2 ];
  1713. return this;
  1714. }
  1715. toArray( array = [], offset = 0 ) {
  1716. array[ offset ] = this.x;
  1717. array[ offset + 1 ] = this.y;
  1718. array[ offset + 2 ] = this.z;
  1719. return array;
  1720. }
  1721. fromBufferAttribute( attribute, index ) {
  1722. this.x = attribute.getX( index );
  1723. this.y = attribute.getY( index );
  1724. this.z = attribute.getZ( index );
  1725. return this;
  1726. }
  1727. random() {
  1728. this.x = Math.random();
  1729. this.y = Math.random();
  1730. this.z = Math.random();
  1731. return this;
  1732. }
  1733. randomDirection() {
  1734. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  1735. const u = ( Math.random() - 0.5 ) * 2;
  1736. const t = Math.random() * Math.PI * 2;
  1737. const f = Math.sqrt( 1 - u ** 2 );
  1738. this.x = f * Math.cos( t );
  1739. this.y = f * Math.sin( t );
  1740. this.z = u;
  1741. return this;
  1742. }
  1743. *[ Symbol.iterator ]() {
  1744. yield this.x;
  1745. yield this.y;
  1746. yield this.z;
  1747. }
  1748. }
  1749. const _vector$c = /*@__PURE__*/ new Vector3();
  1750. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  1751. function SRGBToLinear( c ) {
  1752. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1753. }
  1754. function LinearToSRGB( c ) {
  1755. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1756. }
  1757. /**
  1758. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  1759. * or clipping. Based on W3C specifications for sRGB and Display P3,
  1760. * and ICC specifications for the D50 connection space. Values in/out
  1761. * are _linear_ sRGB and _linear_ Display P3.
  1762. *
  1763. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  1764. *
  1765. * Reference:
  1766. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  1767. */
  1768. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().fromArray( [
  1769. 0.8224621, 0.0331941, 0.0170827,
  1770. 0.1775380, 0.9668058, 0.0723974,
  1771. - 0.0000001, 0.0000001, 0.9105199
  1772. ] );
  1773. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().fromArray( [
  1774. 1.2249401, - 0.0420569, - 0.0196376,
  1775. - 0.2249404, 1.0420571, - 0.0786361,
  1776. 0.0000001, 0.0000000, 1.0982735
  1777. ] );
  1778. const _vector$b = /*@__PURE__*/ new Vector3();
  1779. function DisplayP3ToLinearSRGB( color ) {
  1780. color.convertSRGBToLinear();
  1781. _vector$b.set( color.r, color.g, color.b ).applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB );
  1782. return color.setRGB( _vector$b.x, _vector$b.y, _vector$b.z );
  1783. }
  1784. function LinearSRGBToDisplayP3( color ) {
  1785. _vector$b.set( color.r, color.g, color.b ).applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 );
  1786. return color.setRGB( _vector$b.x, _vector$b.y, _vector$b.z ).convertLinearToSRGB();
  1787. }
  1788. // Conversions from <source> to Linear-sRGB reference space.
  1789. const TO_LINEAR = {
  1790. [ LinearSRGBColorSpace ]: ( color ) => color,
  1791. [ SRGBColorSpace ]: ( color ) => color.convertSRGBToLinear(),
  1792. [ DisplayP3ColorSpace ]: DisplayP3ToLinearSRGB,
  1793. };
  1794. // Conversions to <target> from Linear-sRGB reference space.
  1795. const FROM_LINEAR = {
  1796. [ LinearSRGBColorSpace ]: ( color ) => color,
  1797. [ SRGBColorSpace ]: ( color ) => color.convertLinearToSRGB(),
  1798. [ DisplayP3ColorSpace ]: LinearSRGBToDisplayP3,
  1799. };
  1800. const ColorManagement = {
  1801. enabled: false,
  1802. get legacyMode() {
  1803. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  1804. return ! this.enabled;
  1805. },
  1806. set legacyMode( legacyMode ) {
  1807. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  1808. this.enabled = ! legacyMode;
  1809. },
  1810. get workingColorSpace() {
  1811. return LinearSRGBColorSpace;
  1812. },
  1813. set workingColorSpace( colorSpace ) {
  1814. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  1815. },
  1816. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1817. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1818. return color;
  1819. }
  1820. const sourceToLinear = TO_LINEAR[ sourceColorSpace ];
  1821. const targetFromLinear = FROM_LINEAR[ targetColorSpace ];
  1822. if ( sourceToLinear === undefined || targetFromLinear === undefined ) {
  1823. throw new Error( `Unsupported color space conversion, "${ sourceColorSpace }" to "${ targetColorSpace }".` );
  1824. }
  1825. return targetFromLinear( sourceToLinear( color ) );
  1826. },
  1827. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1828. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1829. },
  1830. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1831. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1832. },
  1833. };
  1834. let _canvas;
  1835. class ImageUtils {
  1836. static getDataURL( image ) {
  1837. if ( /^data:/i.test( image.src ) ) {
  1838. return image.src;
  1839. }
  1840. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1841. return image.src;
  1842. }
  1843. let canvas;
  1844. if ( image instanceof HTMLCanvasElement ) {
  1845. canvas = image;
  1846. } else {
  1847. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1848. _canvas.width = image.width;
  1849. _canvas.height = image.height;
  1850. const context = _canvas.getContext( '2d' );
  1851. if ( image instanceof ImageData ) {
  1852. context.putImageData( image, 0, 0 );
  1853. } else {
  1854. context.drawImage( image, 0, 0, image.width, image.height );
  1855. }
  1856. canvas = _canvas;
  1857. }
  1858. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1859. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1860. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1861. } else {
  1862. return canvas.toDataURL( 'image/png' );
  1863. }
  1864. }
  1865. static sRGBToLinear( image ) {
  1866. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1867. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1868. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1869. const canvas = createElementNS( 'canvas' );
  1870. canvas.width = image.width;
  1871. canvas.height = image.height;
  1872. const context = canvas.getContext( '2d' );
  1873. context.drawImage( image, 0, 0, image.width, image.height );
  1874. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1875. const data = imageData.data;
  1876. for ( let i = 0; i < data.length; i ++ ) {
  1877. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1878. }
  1879. context.putImageData( imageData, 0, 0 );
  1880. return canvas;
  1881. } else if ( image.data ) {
  1882. const data = image.data.slice( 0 );
  1883. for ( let i = 0; i < data.length; i ++ ) {
  1884. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1885. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1886. } else {
  1887. // assuming float
  1888. data[ i ] = SRGBToLinear( data[ i ] );
  1889. }
  1890. }
  1891. return {
  1892. data: data,
  1893. width: image.width,
  1894. height: image.height
  1895. };
  1896. } else {
  1897. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1898. return image;
  1899. }
  1900. }
  1901. }
  1902. class Source {
  1903. constructor( data = null ) {
  1904. this.isSource = true;
  1905. this.uuid = generateUUID();
  1906. this.data = data;
  1907. this.version = 0;
  1908. }
  1909. set needsUpdate( value ) {
  1910. if ( value === true ) this.version ++;
  1911. }
  1912. toJSON( meta ) {
  1913. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1914. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1915. return meta.images[ this.uuid ];
  1916. }
  1917. const output = {
  1918. uuid: this.uuid,
  1919. url: ''
  1920. };
  1921. const data = this.data;
  1922. if ( data !== null ) {
  1923. let url;
  1924. if ( Array.isArray( data ) ) {
  1925. // cube texture
  1926. url = [];
  1927. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1928. if ( data[ i ].isDataTexture ) {
  1929. url.push( serializeImage( data[ i ].image ) );
  1930. } else {
  1931. url.push( serializeImage( data[ i ] ) );
  1932. }
  1933. }
  1934. } else {
  1935. // texture
  1936. url = serializeImage( data );
  1937. }
  1938. output.url = url;
  1939. }
  1940. if ( ! isRootObject ) {
  1941. meta.images[ this.uuid ] = output;
  1942. }
  1943. return output;
  1944. }
  1945. }
  1946. function serializeImage( image ) {
  1947. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1948. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1949. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1950. // default images
  1951. return ImageUtils.getDataURL( image );
  1952. } else {
  1953. if ( image.data ) {
  1954. // images of DataTexture
  1955. return {
  1956. data: Array.from( image.data ),
  1957. width: image.width,
  1958. height: image.height,
  1959. type: image.data.constructor.name
  1960. };
  1961. } else {
  1962. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1963. return {};
  1964. }
  1965. }
  1966. }
  1967. let textureId = 0;
  1968. class Texture extends EventDispatcher {
  1969. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, encoding = LinearEncoding ) {
  1970. super();
  1971. this.isTexture = true;
  1972. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1973. this.uuid = generateUUID();
  1974. this.name = '';
  1975. this.source = new Source( image );
  1976. this.mipmaps = [];
  1977. this.mapping = mapping;
  1978. this.wrapS = wrapS;
  1979. this.wrapT = wrapT;
  1980. this.magFilter = magFilter;
  1981. this.minFilter = minFilter;
  1982. this.anisotropy = anisotropy;
  1983. this.format = format;
  1984. this.internalFormat = null;
  1985. this.type = type;
  1986. this.offset = new Vector2( 0, 0 );
  1987. this.repeat = new Vector2( 1, 1 );
  1988. this.center = new Vector2( 0, 0 );
  1989. this.rotation = 0;
  1990. this.matrixAutoUpdate = true;
  1991. this.matrix = new Matrix3();
  1992. this.generateMipmaps = true;
  1993. this.premultiplyAlpha = false;
  1994. this.flipY = true;
  1995. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1996. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1997. //
  1998. // Also changing the encoding after already used by a Material will not automatically make the Material
  1999. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  2000. this.encoding = encoding;
  2001. this.userData = {};
  2002. this.version = 0;
  2003. this.onUpdate = null;
  2004. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  2005. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  2006. }
  2007. get image() {
  2008. return this.source.data;
  2009. }
  2010. set image( value = null ) {
  2011. this.source.data = value;
  2012. }
  2013. updateMatrix() {
  2014. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  2015. }
  2016. clone() {
  2017. return new this.constructor().copy( this );
  2018. }
  2019. copy( source ) {
  2020. this.name = source.name;
  2021. this.source = source.source;
  2022. this.mipmaps = source.mipmaps.slice( 0 );
  2023. this.mapping = source.mapping;
  2024. this.wrapS = source.wrapS;
  2025. this.wrapT = source.wrapT;
  2026. this.magFilter = source.magFilter;
  2027. this.minFilter = source.minFilter;
  2028. this.anisotropy = source.anisotropy;
  2029. this.format = source.format;
  2030. this.internalFormat = source.internalFormat;
  2031. this.type = source.type;
  2032. this.offset.copy( source.offset );
  2033. this.repeat.copy( source.repeat );
  2034. this.center.copy( source.center );
  2035. this.rotation = source.rotation;
  2036. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2037. this.matrix.copy( source.matrix );
  2038. this.generateMipmaps = source.generateMipmaps;
  2039. this.premultiplyAlpha = source.premultiplyAlpha;
  2040. this.flipY = source.flipY;
  2041. this.unpackAlignment = source.unpackAlignment;
  2042. this.encoding = source.encoding;
  2043. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  2044. this.needsUpdate = true;
  2045. return this;
  2046. }
  2047. toJSON( meta ) {
  2048. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2049. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  2050. return meta.textures[ this.uuid ];
  2051. }
  2052. const output = {
  2053. metadata: {
  2054. version: 4.5,
  2055. type: 'Texture',
  2056. generator: 'Texture.toJSON'
  2057. },
  2058. uuid: this.uuid,
  2059. name: this.name,
  2060. image: this.source.toJSON( meta ).uuid,
  2061. mapping: this.mapping,
  2062. repeat: [ this.repeat.x, this.repeat.y ],
  2063. offset: [ this.offset.x, this.offset.y ],
  2064. center: [ this.center.x, this.center.y ],
  2065. rotation: this.rotation,
  2066. wrap: [ this.wrapS, this.wrapT ],
  2067. format: this.format,
  2068. internalFormat: this.internalFormat,
  2069. type: this.type,
  2070. encoding: this.encoding,
  2071. minFilter: this.minFilter,
  2072. magFilter: this.magFilter,
  2073. anisotropy: this.anisotropy,
  2074. flipY: this.flipY,
  2075. generateMipmaps: this.generateMipmaps,
  2076. premultiplyAlpha: this.premultiplyAlpha,
  2077. unpackAlignment: this.unpackAlignment
  2078. };
  2079. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  2080. if ( ! isRootObject ) {
  2081. meta.textures[ this.uuid ] = output;
  2082. }
  2083. return output;
  2084. }
  2085. dispose() {
  2086. this.dispatchEvent( { type: 'dispose' } );
  2087. }
  2088. transformUv( uv ) {
  2089. if ( this.mapping !== UVMapping ) return uv;
  2090. uv.applyMatrix3( this.matrix );
  2091. if ( uv.x < 0 || uv.x > 1 ) {
  2092. switch ( this.wrapS ) {
  2093. case RepeatWrapping:
  2094. uv.x = uv.x - Math.floor( uv.x );
  2095. break;
  2096. case ClampToEdgeWrapping:
  2097. uv.x = uv.x < 0 ? 0 : 1;
  2098. break;
  2099. case MirroredRepeatWrapping:
  2100. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  2101. uv.x = Math.ceil( uv.x ) - uv.x;
  2102. } else {
  2103. uv.x = uv.x - Math.floor( uv.x );
  2104. }
  2105. break;
  2106. }
  2107. }
  2108. if ( uv.y < 0 || uv.y > 1 ) {
  2109. switch ( this.wrapT ) {
  2110. case RepeatWrapping:
  2111. uv.y = uv.y - Math.floor( uv.y );
  2112. break;
  2113. case ClampToEdgeWrapping:
  2114. uv.y = uv.y < 0 ? 0 : 1;
  2115. break;
  2116. case MirroredRepeatWrapping:
  2117. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  2118. uv.y = Math.ceil( uv.y ) - uv.y;
  2119. } else {
  2120. uv.y = uv.y - Math.floor( uv.y );
  2121. }
  2122. break;
  2123. }
  2124. }
  2125. if ( this.flipY ) {
  2126. uv.y = 1 - uv.y;
  2127. }
  2128. return uv;
  2129. }
  2130. set needsUpdate( value ) {
  2131. if ( value === true ) {
  2132. this.version ++;
  2133. this.source.needsUpdate = true;
  2134. }
  2135. }
  2136. }
  2137. Texture.DEFAULT_IMAGE = null;
  2138. Texture.DEFAULT_MAPPING = UVMapping;
  2139. Texture.DEFAULT_ANISOTROPY = 1;
  2140. class Vector4 {
  2141. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2142. Vector4.prototype.isVector4 = true;
  2143. this.x = x;
  2144. this.y = y;
  2145. this.z = z;
  2146. this.w = w;
  2147. }
  2148. get width() {
  2149. return this.z;
  2150. }
  2151. set width( value ) {
  2152. this.z = value;
  2153. }
  2154. get height() {
  2155. return this.w;
  2156. }
  2157. set height( value ) {
  2158. this.w = value;
  2159. }
  2160. set( x, y, z, w ) {
  2161. this.x = x;
  2162. this.y = y;
  2163. this.z = z;
  2164. this.w = w;
  2165. return this;
  2166. }
  2167. setScalar( scalar ) {
  2168. this.x = scalar;
  2169. this.y = scalar;
  2170. this.z = scalar;
  2171. this.w = scalar;
  2172. return this;
  2173. }
  2174. setX( x ) {
  2175. this.x = x;
  2176. return this;
  2177. }
  2178. setY( y ) {
  2179. this.y = y;
  2180. return this;
  2181. }
  2182. setZ( z ) {
  2183. this.z = z;
  2184. return this;
  2185. }
  2186. setW( w ) {
  2187. this.w = w;
  2188. return this;
  2189. }
  2190. setComponent( index, value ) {
  2191. switch ( index ) {
  2192. case 0: this.x = value; break;
  2193. case 1: this.y = value; break;
  2194. case 2: this.z = value; break;
  2195. case 3: this.w = value; break;
  2196. default: throw new Error( 'index is out of range: ' + index );
  2197. }
  2198. return this;
  2199. }
  2200. getComponent( index ) {
  2201. switch ( index ) {
  2202. case 0: return this.x;
  2203. case 1: return this.y;
  2204. case 2: return this.z;
  2205. case 3: return this.w;
  2206. default: throw new Error( 'index is out of range: ' + index );
  2207. }
  2208. }
  2209. clone() {
  2210. return new this.constructor( this.x, this.y, this.z, this.w );
  2211. }
  2212. copy( v ) {
  2213. this.x = v.x;
  2214. this.y = v.y;
  2215. this.z = v.z;
  2216. this.w = ( v.w !== undefined ) ? v.w : 1;
  2217. return this;
  2218. }
  2219. add( v ) {
  2220. this.x += v.x;
  2221. this.y += v.y;
  2222. this.z += v.z;
  2223. this.w += v.w;
  2224. return this;
  2225. }
  2226. addScalar( s ) {
  2227. this.x += s;
  2228. this.y += s;
  2229. this.z += s;
  2230. this.w += s;
  2231. return this;
  2232. }
  2233. addVectors( a, b ) {
  2234. this.x = a.x + b.x;
  2235. this.y = a.y + b.y;
  2236. this.z = a.z + b.z;
  2237. this.w = a.w + b.w;
  2238. return this;
  2239. }
  2240. addScaledVector( v, s ) {
  2241. this.x += v.x * s;
  2242. this.y += v.y * s;
  2243. this.z += v.z * s;
  2244. this.w += v.w * s;
  2245. return this;
  2246. }
  2247. sub( v ) {
  2248. this.x -= v.x;
  2249. this.y -= v.y;
  2250. this.z -= v.z;
  2251. this.w -= v.w;
  2252. return this;
  2253. }
  2254. subScalar( s ) {
  2255. this.x -= s;
  2256. this.y -= s;
  2257. this.z -= s;
  2258. this.w -= s;
  2259. return this;
  2260. }
  2261. subVectors( a, b ) {
  2262. this.x = a.x - b.x;
  2263. this.y = a.y - b.y;
  2264. this.z = a.z - b.z;
  2265. this.w = a.w - b.w;
  2266. return this;
  2267. }
  2268. multiply( v ) {
  2269. this.x *= v.x;
  2270. this.y *= v.y;
  2271. this.z *= v.z;
  2272. this.w *= v.w;
  2273. return this;
  2274. }
  2275. multiplyScalar( scalar ) {
  2276. this.x *= scalar;
  2277. this.y *= scalar;
  2278. this.z *= scalar;
  2279. this.w *= scalar;
  2280. return this;
  2281. }
  2282. applyMatrix4( m ) {
  2283. const x = this.x, y = this.y, z = this.z, w = this.w;
  2284. const e = m.elements;
  2285. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  2286. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  2287. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  2288. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  2289. return this;
  2290. }
  2291. divideScalar( scalar ) {
  2292. return this.multiplyScalar( 1 / scalar );
  2293. }
  2294. setAxisAngleFromQuaternion( q ) {
  2295. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  2296. // q is assumed to be normalized
  2297. this.w = 2 * Math.acos( q.w );
  2298. const s = Math.sqrt( 1 - q.w * q.w );
  2299. if ( s < 0.0001 ) {
  2300. this.x = 1;
  2301. this.y = 0;
  2302. this.z = 0;
  2303. } else {
  2304. this.x = q.x / s;
  2305. this.y = q.y / s;
  2306. this.z = q.z / s;
  2307. }
  2308. return this;
  2309. }
  2310. setAxisAngleFromRotationMatrix( m ) {
  2311. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  2312. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2313. let angle, x, y, z; // variables for result
  2314. const epsilon = 0.01, // margin to allow for rounding errors
  2315. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  2316. te = m.elements,
  2317. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2318. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2319. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2320. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  2321. ( Math.abs( m13 - m31 ) < epsilon ) &&
  2322. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  2323. // singularity found
  2324. // first check for identity matrix which must have +1 for all terms
  2325. // in leading diagonal and zero in other terms
  2326. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  2327. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  2328. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  2329. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  2330. // this singularity is identity matrix so angle = 0
  2331. this.set( 1, 0, 0, 0 );
  2332. return this; // zero angle, arbitrary axis
  2333. }
  2334. // otherwise this singularity is angle = 180
  2335. angle = Math.PI;
  2336. const xx = ( m11 + 1 ) / 2;
  2337. const yy = ( m22 + 1 ) / 2;
  2338. const zz = ( m33 + 1 ) / 2;
  2339. const xy = ( m12 + m21 ) / 4;
  2340. const xz = ( m13 + m31 ) / 4;
  2341. const yz = ( m23 + m32 ) / 4;
  2342. if ( ( xx > yy ) && ( xx > zz ) ) {
  2343. // m11 is the largest diagonal term
  2344. if ( xx < epsilon ) {
  2345. x = 0;
  2346. y = 0.707106781;
  2347. z = 0.707106781;
  2348. } else {
  2349. x = Math.sqrt( xx );
  2350. y = xy / x;
  2351. z = xz / x;
  2352. }
  2353. } else if ( yy > zz ) {
  2354. // m22 is the largest diagonal term
  2355. if ( yy < epsilon ) {
  2356. x = 0.707106781;
  2357. y = 0;
  2358. z = 0.707106781;
  2359. } else {
  2360. y = Math.sqrt( yy );
  2361. x = xy / y;
  2362. z = yz / y;
  2363. }
  2364. } else {
  2365. // m33 is the largest diagonal term so base result on this
  2366. if ( zz < epsilon ) {
  2367. x = 0.707106781;
  2368. y = 0.707106781;
  2369. z = 0;
  2370. } else {
  2371. z = Math.sqrt( zz );
  2372. x = xz / z;
  2373. y = yz / z;
  2374. }
  2375. }
  2376. this.set( x, y, z, angle );
  2377. return this; // return 180 deg rotation
  2378. }
  2379. // as we have reached here there are no singularities so we can handle normally
  2380. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  2381. ( m13 - m31 ) * ( m13 - m31 ) +
  2382. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  2383. if ( Math.abs( s ) < 0.001 ) s = 1;
  2384. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2385. // caught by singularity test above, but I've left it in just in case
  2386. this.x = ( m32 - m23 ) / s;
  2387. this.y = ( m13 - m31 ) / s;
  2388. this.z = ( m21 - m12 ) / s;
  2389. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  2390. return this;
  2391. }
  2392. min( v ) {
  2393. this.x = Math.min( this.x, v.x );
  2394. this.y = Math.min( this.y, v.y );
  2395. this.z = Math.min( this.z, v.z );
  2396. this.w = Math.min( this.w, v.w );
  2397. return this;
  2398. }
  2399. max( v ) {
  2400. this.x = Math.max( this.x, v.x );
  2401. this.y = Math.max( this.y, v.y );
  2402. this.z = Math.max( this.z, v.z );
  2403. this.w = Math.max( this.w, v.w );
  2404. return this;
  2405. }
  2406. clamp( min, max ) {
  2407. // assumes min < max, componentwise
  2408. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2409. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2410. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2411. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  2412. return this;
  2413. }
  2414. clampScalar( minVal, maxVal ) {
  2415. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2416. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2417. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2418. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  2419. return this;
  2420. }
  2421. clampLength( min, max ) {
  2422. const length = this.length();
  2423. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2424. }
  2425. floor() {
  2426. this.x = Math.floor( this.x );
  2427. this.y = Math.floor( this.y );
  2428. this.z = Math.floor( this.z );
  2429. this.w = Math.floor( this.w );
  2430. return this;
  2431. }
  2432. ceil() {
  2433. this.x = Math.ceil( this.x );
  2434. this.y = Math.ceil( this.y );
  2435. this.z = Math.ceil( this.z );
  2436. this.w = Math.ceil( this.w );
  2437. return this;
  2438. }
  2439. round() {
  2440. this.x = Math.round( this.x );
  2441. this.y = Math.round( this.y );
  2442. this.z = Math.round( this.z );
  2443. this.w = Math.round( this.w );
  2444. return this;
  2445. }
  2446. roundToZero() {
  2447. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2448. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2449. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2450. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  2451. return this;
  2452. }
  2453. negate() {
  2454. this.x = - this.x;
  2455. this.y = - this.y;
  2456. this.z = - this.z;
  2457. this.w = - this.w;
  2458. return this;
  2459. }
  2460. dot( v ) {
  2461. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2462. }
  2463. lengthSq() {
  2464. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2465. }
  2466. length() {
  2467. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2468. }
  2469. manhattanLength() {
  2470. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  2471. }
  2472. normalize() {
  2473. return this.divideScalar( this.length() || 1 );
  2474. }
  2475. setLength( length ) {
  2476. return this.normalize().multiplyScalar( length );
  2477. }
  2478. lerp( v, alpha ) {
  2479. this.x += ( v.x - this.x ) * alpha;
  2480. this.y += ( v.y - this.y ) * alpha;
  2481. this.z += ( v.z - this.z ) * alpha;
  2482. this.w += ( v.w - this.w ) * alpha;
  2483. return this;
  2484. }
  2485. lerpVectors( v1, v2, alpha ) {
  2486. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2487. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2488. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2489. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  2490. return this;
  2491. }
  2492. equals( v ) {
  2493. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  2494. }
  2495. fromArray( array, offset = 0 ) {
  2496. this.x = array[ offset ];
  2497. this.y = array[ offset + 1 ];
  2498. this.z = array[ offset + 2 ];
  2499. this.w = array[ offset + 3 ];
  2500. return this;
  2501. }
  2502. toArray( array = [], offset = 0 ) {
  2503. array[ offset ] = this.x;
  2504. array[ offset + 1 ] = this.y;
  2505. array[ offset + 2 ] = this.z;
  2506. array[ offset + 3 ] = this.w;
  2507. return array;
  2508. }
  2509. fromBufferAttribute( attribute, index ) {
  2510. this.x = attribute.getX( index );
  2511. this.y = attribute.getY( index );
  2512. this.z = attribute.getZ( index );
  2513. this.w = attribute.getW( index );
  2514. return this;
  2515. }
  2516. random() {
  2517. this.x = Math.random();
  2518. this.y = Math.random();
  2519. this.z = Math.random();
  2520. this.w = Math.random();
  2521. return this;
  2522. }
  2523. *[ Symbol.iterator ]() {
  2524. yield this.x;
  2525. yield this.y;
  2526. yield this.z;
  2527. yield this.w;
  2528. }
  2529. }
  2530. /*
  2531. In options, we can specify:
  2532. * Texture parameters for an auto-generated target texture
  2533. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2534. */
  2535. class WebGLRenderTarget extends EventDispatcher {
  2536. constructor( width = 1, height = 1, options = {} ) {
  2537. super();
  2538. this.isWebGLRenderTarget = true;
  2539. this.width = width;
  2540. this.height = height;
  2541. this.depth = 1;
  2542. this.scissor = new Vector4( 0, 0, width, height );
  2543. this.scissorTest = false;
  2544. this.viewport = new Vector4( 0, 0, width, height );
  2545. const image = { width: width, height: height, depth: 1 };
  2546. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2547. this.texture.isRenderTargetTexture = true;
  2548. this.texture.flipY = false;
  2549. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2550. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2551. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2552. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2553. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2554. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2555. this.samples = options.samples !== undefined ? options.samples : 0;
  2556. }
  2557. setSize( width, height, depth = 1 ) {
  2558. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2559. this.width = width;
  2560. this.height = height;
  2561. this.depth = depth;
  2562. this.texture.image.width = width;
  2563. this.texture.image.height = height;
  2564. this.texture.image.depth = depth;
  2565. this.dispose();
  2566. }
  2567. this.viewport.set( 0, 0, width, height );
  2568. this.scissor.set( 0, 0, width, height );
  2569. }
  2570. clone() {
  2571. return new this.constructor().copy( this );
  2572. }
  2573. copy( source ) {
  2574. this.width = source.width;
  2575. this.height = source.height;
  2576. this.depth = source.depth;
  2577. this.viewport.copy( source.viewport );
  2578. this.texture = source.texture.clone();
  2579. this.texture.isRenderTargetTexture = true;
  2580. // ensure image object is not shared, see #20328
  2581. const image = Object.assign( {}, source.texture.image );
  2582. this.texture.source = new Source( image );
  2583. this.depthBuffer = source.depthBuffer;
  2584. this.stencilBuffer = source.stencilBuffer;
  2585. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2586. this.samples = source.samples;
  2587. return this;
  2588. }
  2589. dispose() {
  2590. this.dispatchEvent( { type: 'dispose' } );
  2591. }
  2592. }
  2593. class DataArrayTexture extends Texture {
  2594. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2595. super( null );
  2596. this.isDataArrayTexture = true;
  2597. this.image = { data, width, height, depth };
  2598. this.magFilter = NearestFilter;
  2599. this.minFilter = NearestFilter;
  2600. this.wrapR = ClampToEdgeWrapping;
  2601. this.generateMipmaps = false;
  2602. this.flipY = false;
  2603. this.unpackAlignment = 1;
  2604. }
  2605. }
  2606. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2607. constructor( width = 1, height = 1, depth = 1 ) {
  2608. super( width, height );
  2609. this.isWebGLArrayRenderTarget = true;
  2610. this.depth = depth;
  2611. this.texture = new DataArrayTexture( null, width, height, depth );
  2612. this.texture.isRenderTargetTexture = true;
  2613. }
  2614. }
  2615. class Data3DTexture extends Texture {
  2616. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2617. // We're going to add .setXXX() methods for setting properties later.
  2618. // Users can still set in DataTexture3D directly.
  2619. //
  2620. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2621. // texture.anisotropy = 16;
  2622. //
  2623. // See #14839
  2624. super( null );
  2625. this.isData3DTexture = true;
  2626. this.image = { data, width, height, depth };
  2627. this.magFilter = NearestFilter;
  2628. this.minFilter = NearestFilter;
  2629. this.wrapR = ClampToEdgeWrapping;
  2630. this.generateMipmaps = false;
  2631. this.flipY = false;
  2632. this.unpackAlignment = 1;
  2633. }
  2634. }
  2635. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2636. constructor( width = 1, height = 1, depth = 1 ) {
  2637. super( width, height );
  2638. this.isWebGL3DRenderTarget = true;
  2639. this.depth = depth;
  2640. this.texture = new Data3DTexture( null, width, height, depth );
  2641. this.texture.isRenderTargetTexture = true;
  2642. }
  2643. }
  2644. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2645. constructor( width = 1, height = 1, count = 1, options = {} ) {
  2646. super( width, height, options );
  2647. this.isWebGLMultipleRenderTargets = true;
  2648. const texture = this.texture;
  2649. this.texture = [];
  2650. for ( let i = 0; i < count; i ++ ) {
  2651. this.texture[ i ] = texture.clone();
  2652. this.texture[ i ].isRenderTargetTexture = true;
  2653. }
  2654. }
  2655. setSize( width, height, depth = 1 ) {
  2656. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2657. this.width = width;
  2658. this.height = height;
  2659. this.depth = depth;
  2660. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2661. this.texture[ i ].image.width = width;
  2662. this.texture[ i ].image.height = height;
  2663. this.texture[ i ].image.depth = depth;
  2664. }
  2665. this.dispose();
  2666. }
  2667. this.viewport.set( 0, 0, width, height );
  2668. this.scissor.set( 0, 0, width, height );
  2669. return this;
  2670. }
  2671. copy( source ) {
  2672. this.dispose();
  2673. this.width = source.width;
  2674. this.height = source.height;
  2675. this.depth = source.depth;
  2676. this.viewport.set( 0, 0, this.width, this.height );
  2677. this.scissor.set( 0, 0, this.width, this.height );
  2678. this.depthBuffer = source.depthBuffer;
  2679. this.stencilBuffer = source.stencilBuffer;
  2680. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2681. this.texture.length = 0;
  2682. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2683. this.texture[ i ] = source.texture[ i ].clone();
  2684. this.texture[ i ].isRenderTargetTexture = true;
  2685. }
  2686. return this;
  2687. }
  2688. }
  2689. class Box3 {
  2690. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2691. this.isBox3 = true;
  2692. this.min = min;
  2693. this.max = max;
  2694. }
  2695. set( min, max ) {
  2696. this.min.copy( min );
  2697. this.max.copy( max );
  2698. return this;
  2699. }
  2700. setFromArray( array ) {
  2701. this.makeEmpty();
  2702. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2703. this.expandByPoint( _vector$a.fromArray( array, i ) );
  2704. }
  2705. return this;
  2706. }
  2707. setFromBufferAttribute( attribute ) {
  2708. this.makeEmpty();
  2709. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2710. this.expandByPoint( _vector$a.fromBufferAttribute( attribute, i ) );
  2711. }
  2712. return this;
  2713. }
  2714. setFromPoints( points ) {
  2715. this.makeEmpty();
  2716. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2717. this.expandByPoint( points[ i ] );
  2718. }
  2719. return this;
  2720. }
  2721. setFromCenterAndSize( center, size ) {
  2722. const halfSize = _vector$a.copy( size ).multiplyScalar( 0.5 );
  2723. this.min.copy( center ).sub( halfSize );
  2724. this.max.copy( center ).add( halfSize );
  2725. return this;
  2726. }
  2727. setFromObject( object, precise = false ) {
  2728. this.makeEmpty();
  2729. return this.expandByObject( object, precise );
  2730. }
  2731. clone() {
  2732. return new this.constructor().copy( this );
  2733. }
  2734. copy( box ) {
  2735. this.min.copy( box.min );
  2736. this.max.copy( box.max );
  2737. return this;
  2738. }
  2739. makeEmpty() {
  2740. this.min.x = this.min.y = this.min.z = + Infinity;
  2741. this.max.x = this.max.y = this.max.z = - Infinity;
  2742. return this;
  2743. }
  2744. isEmpty() {
  2745. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2746. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2747. }
  2748. getCenter( target ) {
  2749. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2750. }
  2751. getSize( target ) {
  2752. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2753. }
  2754. expandByPoint( point ) {
  2755. this.min.min( point );
  2756. this.max.max( point );
  2757. return this;
  2758. }
  2759. expandByVector( vector ) {
  2760. this.min.sub( vector );
  2761. this.max.add( vector );
  2762. return this;
  2763. }
  2764. expandByScalar( scalar ) {
  2765. this.min.addScalar( - scalar );
  2766. this.max.addScalar( scalar );
  2767. return this;
  2768. }
  2769. expandByObject( object, precise = false ) {
  2770. // Computes the world-axis-aligned bounding box of an object (including its children),
  2771. // accounting for both the object's, and children's, world transforms
  2772. object.updateWorldMatrix( false, false );
  2773. if ( object.boundingBox !== undefined ) {
  2774. if ( object.boundingBox === null ) {
  2775. object.computeBoundingBox();
  2776. }
  2777. _box$3.copy( object.boundingBox );
  2778. _box$3.applyMatrix4( object.matrixWorld );
  2779. this.union( _box$3 );
  2780. } else {
  2781. const geometry = object.geometry;
  2782. if ( geometry !== undefined ) {
  2783. if ( precise && geometry.attributes !== undefined && geometry.attributes.position !== undefined ) {
  2784. const position = geometry.attributes.position;
  2785. for ( let i = 0, l = position.count; i < l; i ++ ) {
  2786. _vector$a.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  2787. this.expandByPoint( _vector$a );
  2788. }
  2789. } else {
  2790. if ( geometry.boundingBox === null ) {
  2791. geometry.computeBoundingBox();
  2792. }
  2793. _box$3.copy( geometry.boundingBox );
  2794. _box$3.applyMatrix4( object.matrixWorld );
  2795. this.union( _box$3 );
  2796. }
  2797. }
  2798. }
  2799. const children = object.children;
  2800. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2801. this.expandByObject( children[ i ], precise );
  2802. }
  2803. return this;
  2804. }
  2805. containsPoint( point ) {
  2806. return point.x < this.min.x || point.x > this.max.x ||
  2807. point.y < this.min.y || point.y > this.max.y ||
  2808. point.z < this.min.z || point.z > this.max.z ? false : true;
  2809. }
  2810. containsBox( box ) {
  2811. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2812. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2813. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2814. }
  2815. getParameter( point, target ) {
  2816. // This can potentially have a divide by zero if the box
  2817. // has a size dimension of 0.
  2818. return target.set(
  2819. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2820. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2821. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2822. );
  2823. }
  2824. intersectsBox( box ) {
  2825. // using 6 splitting planes to rule out intersections.
  2826. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2827. box.max.y < this.min.y || box.min.y > this.max.y ||
  2828. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2829. }
  2830. intersectsSphere( sphere ) {
  2831. // Find the point on the AABB closest to the sphere center.
  2832. this.clampPoint( sphere.center, _vector$a );
  2833. // If that point is inside the sphere, the AABB and sphere intersect.
  2834. return _vector$a.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2835. }
  2836. intersectsPlane( plane ) {
  2837. // We compute the minimum and maximum dot product values. If those values
  2838. // are on the same side (back or front) of the plane, then there is no intersection.
  2839. let min, max;
  2840. if ( plane.normal.x > 0 ) {
  2841. min = plane.normal.x * this.min.x;
  2842. max = plane.normal.x * this.max.x;
  2843. } else {
  2844. min = plane.normal.x * this.max.x;
  2845. max = plane.normal.x * this.min.x;
  2846. }
  2847. if ( plane.normal.y > 0 ) {
  2848. min += plane.normal.y * this.min.y;
  2849. max += plane.normal.y * this.max.y;
  2850. } else {
  2851. min += plane.normal.y * this.max.y;
  2852. max += plane.normal.y * this.min.y;
  2853. }
  2854. if ( plane.normal.z > 0 ) {
  2855. min += plane.normal.z * this.min.z;
  2856. max += plane.normal.z * this.max.z;
  2857. } else {
  2858. min += plane.normal.z * this.max.z;
  2859. max += plane.normal.z * this.min.z;
  2860. }
  2861. return ( min <= - plane.constant && max >= - plane.constant );
  2862. }
  2863. intersectsTriangle( triangle ) {
  2864. if ( this.isEmpty() ) {
  2865. return false;
  2866. }
  2867. // compute box center and extents
  2868. this.getCenter( _center );
  2869. _extents.subVectors( this.max, _center );
  2870. // translate triangle to aabb origin
  2871. _v0$2.subVectors( triangle.a, _center );
  2872. _v1$7.subVectors( triangle.b, _center );
  2873. _v2$4.subVectors( triangle.c, _center );
  2874. // compute edge vectors for triangle
  2875. _f0.subVectors( _v1$7, _v0$2 );
  2876. _f1.subVectors( _v2$4, _v1$7 );
  2877. _f2.subVectors( _v0$2, _v2$4 );
  2878. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2879. // 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
  2880. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2881. let axes = [
  2882. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2883. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2884. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2885. ];
  2886. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2887. return false;
  2888. }
  2889. // test 3 face normals from the aabb
  2890. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2891. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2892. return false;
  2893. }
  2894. // finally testing the face normal of the triangle
  2895. // use already existing triangle edge vectors here
  2896. _triangleNormal.crossVectors( _f0, _f1 );
  2897. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2898. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2899. }
  2900. clampPoint( point, target ) {
  2901. return target.copy( point ).clamp( this.min, this.max );
  2902. }
  2903. distanceToPoint( point ) {
  2904. return this.clampPoint( point, _vector$a ).distanceTo( point );
  2905. }
  2906. getBoundingSphere( target ) {
  2907. if ( this.isEmpty() ) {
  2908. target.makeEmpty();
  2909. } else {
  2910. this.getCenter( target.center );
  2911. target.radius = this.getSize( _vector$a ).length() * 0.5;
  2912. }
  2913. return target;
  2914. }
  2915. intersect( box ) {
  2916. this.min.max( box.min );
  2917. this.max.min( box.max );
  2918. // 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.
  2919. if ( this.isEmpty() ) this.makeEmpty();
  2920. return this;
  2921. }
  2922. union( box ) {
  2923. this.min.min( box.min );
  2924. this.max.max( box.max );
  2925. return this;
  2926. }
  2927. applyMatrix4( matrix ) {
  2928. // transform of empty box is an empty box.
  2929. if ( this.isEmpty() ) return this;
  2930. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2931. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2932. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2933. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2934. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2935. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2936. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2937. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2938. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2939. this.setFromPoints( _points );
  2940. return this;
  2941. }
  2942. translate( offset ) {
  2943. this.min.add( offset );
  2944. this.max.add( offset );
  2945. return this;
  2946. }
  2947. equals( box ) {
  2948. return box.min.equals( this.min ) && box.max.equals( this.max );
  2949. }
  2950. }
  2951. const _points = [
  2952. /*@__PURE__*/ new Vector3(),
  2953. /*@__PURE__*/ new Vector3(),
  2954. /*@__PURE__*/ new Vector3(),
  2955. /*@__PURE__*/ new Vector3(),
  2956. /*@__PURE__*/ new Vector3(),
  2957. /*@__PURE__*/ new Vector3(),
  2958. /*@__PURE__*/ new Vector3(),
  2959. /*@__PURE__*/ new Vector3()
  2960. ];
  2961. const _vector$a = /*@__PURE__*/ new Vector3();
  2962. const _box$3 = /*@__PURE__*/ new Box3();
  2963. // triangle centered vertices
  2964. const _v0$2 = /*@__PURE__*/ new Vector3();
  2965. const _v1$7 = /*@__PURE__*/ new Vector3();
  2966. const _v2$4 = /*@__PURE__*/ new Vector3();
  2967. // triangle edge vectors
  2968. const _f0 = /*@__PURE__*/ new Vector3();
  2969. const _f1 = /*@__PURE__*/ new Vector3();
  2970. const _f2 = /*@__PURE__*/ new Vector3();
  2971. const _center = /*@__PURE__*/ new Vector3();
  2972. const _extents = /*@__PURE__*/ new Vector3();
  2973. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2974. const _testAxis = /*@__PURE__*/ new Vector3();
  2975. function satForAxes( axes, v0, v1, v2, extents ) {
  2976. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2977. _testAxis.fromArray( axes, i );
  2978. // project the aabb onto the separating axis
  2979. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2980. // project all 3 vertices of the triangle onto the separating axis
  2981. const p0 = v0.dot( _testAxis );
  2982. const p1 = v1.dot( _testAxis );
  2983. const p2 = v2.dot( _testAxis );
  2984. // actual test, basically see if either of the most extreme of the triangle points intersects r
  2985. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  2986. // points of the projected triangle are outside the projected half-length of the aabb
  2987. // the axis is separating and we can exit
  2988. return false;
  2989. }
  2990. }
  2991. return true;
  2992. }
  2993. const _box$2 = /*@__PURE__*/ new Box3();
  2994. const _v1$6 = /*@__PURE__*/ new Vector3();
  2995. const _v2$3 = /*@__PURE__*/ new Vector3();
  2996. class Sphere {
  2997. constructor( center = new Vector3(), radius = - 1 ) {
  2998. this.center = center;
  2999. this.radius = radius;
  3000. }
  3001. set( center, radius ) {
  3002. this.center.copy( center );
  3003. this.radius = radius;
  3004. return this;
  3005. }
  3006. setFromPoints( points, optionalCenter ) {
  3007. const center = this.center;
  3008. if ( optionalCenter !== undefined ) {
  3009. center.copy( optionalCenter );
  3010. } else {
  3011. _box$2.setFromPoints( points ).getCenter( center );
  3012. }
  3013. let maxRadiusSq = 0;
  3014. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3015. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3016. }
  3017. this.radius = Math.sqrt( maxRadiusSq );
  3018. return this;
  3019. }
  3020. copy( sphere ) {
  3021. this.center.copy( sphere.center );
  3022. this.radius = sphere.radius;
  3023. return this;
  3024. }
  3025. isEmpty() {
  3026. return ( this.radius < 0 );
  3027. }
  3028. makeEmpty() {
  3029. this.center.set( 0, 0, 0 );
  3030. this.radius = - 1;
  3031. return this;
  3032. }
  3033. containsPoint( point ) {
  3034. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3035. }
  3036. distanceToPoint( point ) {
  3037. return ( point.distanceTo( this.center ) - this.radius );
  3038. }
  3039. intersectsSphere( sphere ) {
  3040. const radiusSum = this.radius + sphere.radius;
  3041. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3042. }
  3043. intersectsBox( box ) {
  3044. return box.intersectsSphere( this );
  3045. }
  3046. intersectsPlane( plane ) {
  3047. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3048. }
  3049. clampPoint( point, target ) {
  3050. const deltaLengthSq = this.center.distanceToSquared( point );
  3051. target.copy( point );
  3052. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3053. target.sub( this.center ).normalize();
  3054. target.multiplyScalar( this.radius ).add( this.center );
  3055. }
  3056. return target;
  3057. }
  3058. getBoundingBox( target ) {
  3059. if ( this.isEmpty() ) {
  3060. // Empty sphere produces empty bounding box
  3061. target.makeEmpty();
  3062. return target;
  3063. }
  3064. target.set( this.center, this.center );
  3065. target.expandByScalar( this.radius );
  3066. return target;
  3067. }
  3068. applyMatrix4( matrix ) {
  3069. this.center.applyMatrix4( matrix );
  3070. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3071. return this;
  3072. }
  3073. translate( offset ) {
  3074. this.center.add( offset );
  3075. return this;
  3076. }
  3077. expandByPoint( point ) {
  3078. if ( this.isEmpty() ) {
  3079. this.center.copy( point );
  3080. this.radius = 0;
  3081. return this;
  3082. }
  3083. _v1$6.subVectors( point, this.center );
  3084. const lengthSq = _v1$6.lengthSq();
  3085. if ( lengthSq > ( this.radius * this.radius ) ) {
  3086. // calculate the minimal sphere
  3087. const length = Math.sqrt( lengthSq );
  3088. const delta = ( length - this.radius ) * 0.5;
  3089. this.center.addScaledVector( _v1$6, delta / length );
  3090. this.radius += delta;
  3091. }
  3092. return this;
  3093. }
  3094. union( sphere ) {
  3095. if ( sphere.isEmpty() ) {
  3096. return this;
  3097. }
  3098. if ( this.isEmpty() ) {
  3099. this.copy( sphere );
  3100. return this;
  3101. }
  3102. if ( this.center.equals( sphere.center ) === true ) {
  3103. this.radius = Math.max( this.radius, sphere.radius );
  3104. } else {
  3105. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3106. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3107. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3108. }
  3109. return this;
  3110. }
  3111. equals( sphere ) {
  3112. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3113. }
  3114. clone() {
  3115. return new this.constructor().copy( this );
  3116. }
  3117. }
  3118. const _vector$9 = /*@__PURE__*/ new Vector3();
  3119. const _segCenter = /*@__PURE__*/ new Vector3();
  3120. const _segDir = /*@__PURE__*/ new Vector3();
  3121. const _diff = /*@__PURE__*/ new Vector3();
  3122. const _edge1 = /*@__PURE__*/ new Vector3();
  3123. const _edge2 = /*@__PURE__*/ new Vector3();
  3124. const _normal$1 = /*@__PURE__*/ new Vector3();
  3125. class Ray {
  3126. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3127. this.origin = origin;
  3128. this.direction = direction;
  3129. }
  3130. set( origin, direction ) {
  3131. this.origin.copy( origin );
  3132. this.direction.copy( direction );
  3133. return this;
  3134. }
  3135. copy( ray ) {
  3136. this.origin.copy( ray.origin );
  3137. this.direction.copy( ray.direction );
  3138. return this;
  3139. }
  3140. at( t, target ) {
  3141. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3142. }
  3143. lookAt( v ) {
  3144. this.direction.copy( v ).sub( this.origin ).normalize();
  3145. return this;
  3146. }
  3147. recast( t ) {
  3148. this.origin.copy( this.at( t, _vector$9 ) );
  3149. return this;
  3150. }
  3151. closestPointToPoint( point, target ) {
  3152. target.subVectors( point, this.origin );
  3153. const directionDistance = target.dot( this.direction );
  3154. if ( directionDistance < 0 ) {
  3155. return target.copy( this.origin );
  3156. }
  3157. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3158. }
  3159. distanceToPoint( point ) {
  3160. return Math.sqrt( this.distanceSqToPoint( point ) );
  3161. }
  3162. distanceSqToPoint( point ) {
  3163. const directionDistance = _vector$9.subVectors( point, this.origin ).dot( this.direction );
  3164. // point behind the ray
  3165. if ( directionDistance < 0 ) {
  3166. return this.origin.distanceToSquared( point );
  3167. }
  3168. _vector$9.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3169. return _vector$9.distanceToSquared( point );
  3170. }
  3171. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3172. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3173. // It returns the min distance between the ray and the segment
  3174. // defined by v0 and v1
  3175. // It can also set two optional targets :
  3176. // - The closest point on the ray
  3177. // - The closest point on the segment
  3178. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3179. _segDir.copy( v1 ).sub( v0 ).normalize();
  3180. _diff.copy( this.origin ).sub( _segCenter );
  3181. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3182. const a01 = - this.direction.dot( _segDir );
  3183. const b0 = _diff.dot( this.direction );
  3184. const b1 = - _diff.dot( _segDir );
  3185. const c = _diff.lengthSq();
  3186. const det = Math.abs( 1 - a01 * a01 );
  3187. let s0, s1, sqrDist, extDet;
  3188. if ( det > 0 ) {
  3189. // The ray and segment are not parallel.
  3190. s0 = a01 * b1 - b0;
  3191. s1 = a01 * b0 - b1;
  3192. extDet = segExtent * det;
  3193. if ( s0 >= 0 ) {
  3194. if ( s1 >= - extDet ) {
  3195. if ( s1 <= extDet ) {
  3196. // region 0
  3197. // Minimum at interior points of ray and segment.
  3198. const invDet = 1 / det;
  3199. s0 *= invDet;
  3200. s1 *= invDet;
  3201. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3202. } else {
  3203. // region 1
  3204. s1 = segExtent;
  3205. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3206. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3207. }
  3208. } else {
  3209. // region 5
  3210. s1 = - segExtent;
  3211. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3212. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3213. }
  3214. } else {
  3215. if ( s1 <= - extDet ) {
  3216. // region 4
  3217. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3218. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3219. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3220. } else if ( s1 <= extDet ) {
  3221. // region 3
  3222. s0 = 0;
  3223. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3224. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3225. } else {
  3226. // region 2
  3227. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3228. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3229. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3230. }
  3231. }
  3232. } else {
  3233. // Ray and segment are parallel.
  3234. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3235. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3236. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3237. }
  3238. if ( optionalPointOnRay ) {
  3239. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3240. }
  3241. if ( optionalPointOnSegment ) {
  3242. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3243. }
  3244. return sqrDist;
  3245. }
  3246. intersectSphere( sphere, target ) {
  3247. _vector$9.subVectors( sphere.center, this.origin );
  3248. const tca = _vector$9.dot( this.direction );
  3249. const d2 = _vector$9.dot( _vector$9 ) - tca * tca;
  3250. const radius2 = sphere.radius * sphere.radius;
  3251. if ( d2 > radius2 ) return null;
  3252. const thc = Math.sqrt( radius2 - d2 );
  3253. // t0 = first intersect point - entrance on front of sphere
  3254. const t0 = tca - thc;
  3255. // t1 = second intersect point - exit point on back of sphere
  3256. const t1 = tca + thc;
  3257. // test to see if t1 is behind the ray - if so, return null
  3258. if ( t1 < 0 ) return null;
  3259. // test to see if t0 is behind the ray:
  3260. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3261. // in order to always return an intersect point that is in front of the ray.
  3262. if ( t0 < 0 ) return this.at( t1, target );
  3263. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3264. return this.at( t0, target );
  3265. }
  3266. intersectsSphere( sphere ) {
  3267. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3268. }
  3269. distanceToPlane( plane ) {
  3270. const denominator = plane.normal.dot( this.direction );
  3271. if ( denominator === 0 ) {
  3272. // line is coplanar, return origin
  3273. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3274. return 0;
  3275. }
  3276. // Null is preferable to undefined since undefined means.... it is undefined
  3277. return null;
  3278. }
  3279. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3280. // Return if the ray never intersects the plane
  3281. return t >= 0 ? t : null;
  3282. }
  3283. intersectPlane( plane, target ) {
  3284. const t = this.distanceToPlane( plane );
  3285. if ( t === null ) {
  3286. return null;
  3287. }
  3288. return this.at( t, target );
  3289. }
  3290. intersectsPlane( plane ) {
  3291. // check if the ray lies on the plane first
  3292. const distToPoint = plane.distanceToPoint( this.origin );
  3293. if ( distToPoint === 0 ) {
  3294. return true;
  3295. }
  3296. const denominator = plane.normal.dot( this.direction );
  3297. if ( denominator * distToPoint < 0 ) {
  3298. return true;
  3299. }
  3300. // ray origin is behind the plane (and is pointing behind it)
  3301. return false;
  3302. }
  3303. intersectBox( box, target ) {
  3304. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3305. const invdirx = 1 / this.direction.x,
  3306. invdiry = 1 / this.direction.y,
  3307. invdirz = 1 / this.direction.z;
  3308. const origin = this.origin;
  3309. if ( invdirx >= 0 ) {
  3310. tmin = ( box.min.x - origin.x ) * invdirx;
  3311. tmax = ( box.max.x - origin.x ) * invdirx;
  3312. } else {
  3313. tmin = ( box.max.x - origin.x ) * invdirx;
  3314. tmax = ( box.min.x - origin.x ) * invdirx;
  3315. }
  3316. if ( invdiry >= 0 ) {
  3317. tymin = ( box.min.y - origin.y ) * invdiry;
  3318. tymax = ( box.max.y - origin.y ) * invdiry;
  3319. } else {
  3320. tymin = ( box.max.y - origin.y ) * invdiry;
  3321. tymax = ( box.min.y - origin.y ) * invdiry;
  3322. }
  3323. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3324. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3325. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3326. if ( invdirz >= 0 ) {
  3327. tzmin = ( box.min.z - origin.z ) * invdirz;
  3328. tzmax = ( box.max.z - origin.z ) * invdirz;
  3329. } else {
  3330. tzmin = ( box.max.z - origin.z ) * invdirz;
  3331. tzmax = ( box.min.z - origin.z ) * invdirz;
  3332. }
  3333. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3334. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3335. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3336. //return point closest to the ray (positive side)
  3337. if ( tmax < 0 ) return null;
  3338. return this.at( tmin >= 0 ? tmin : tmax, target );
  3339. }
  3340. intersectsBox( box ) {
  3341. return this.intersectBox( box, _vector$9 ) !== null;
  3342. }
  3343. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3344. // Compute the offset origin, edges, and normal.
  3345. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3346. _edge1.subVectors( b, a );
  3347. _edge2.subVectors( c, a );
  3348. _normal$1.crossVectors( _edge1, _edge2 );
  3349. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3350. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3351. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3352. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3353. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3354. let DdN = this.direction.dot( _normal$1 );
  3355. let sign;
  3356. if ( DdN > 0 ) {
  3357. if ( backfaceCulling ) return null;
  3358. sign = 1;
  3359. } else if ( DdN < 0 ) {
  3360. sign = - 1;
  3361. DdN = - DdN;
  3362. } else {
  3363. return null;
  3364. }
  3365. _diff.subVectors( this.origin, a );
  3366. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3367. // b1 < 0, no intersection
  3368. if ( DdQxE2 < 0 ) {
  3369. return null;
  3370. }
  3371. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3372. // b2 < 0, no intersection
  3373. if ( DdE1xQ < 0 ) {
  3374. return null;
  3375. }
  3376. // b1+b2 > 1, no intersection
  3377. if ( DdQxE2 + DdE1xQ > DdN ) {
  3378. return null;
  3379. }
  3380. // Line intersects triangle, check if ray does.
  3381. const QdN = - sign * _diff.dot( _normal$1 );
  3382. // t < 0, no intersection
  3383. if ( QdN < 0 ) {
  3384. return null;
  3385. }
  3386. // Ray intersects triangle.
  3387. return this.at( QdN / DdN, target );
  3388. }
  3389. applyMatrix4( matrix4 ) {
  3390. this.origin.applyMatrix4( matrix4 );
  3391. this.direction.transformDirection( matrix4 );
  3392. return this;
  3393. }
  3394. equals( ray ) {
  3395. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3396. }
  3397. clone() {
  3398. return new this.constructor().copy( this );
  3399. }
  3400. }
  3401. class Matrix4 {
  3402. constructor() {
  3403. Matrix4.prototype.isMatrix4 = true;
  3404. this.elements = [
  3405. 1, 0, 0, 0,
  3406. 0, 1, 0, 0,
  3407. 0, 0, 1, 0,
  3408. 0, 0, 0, 1
  3409. ];
  3410. }
  3411. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3412. const te = this.elements;
  3413. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3414. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3415. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3416. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3417. return this;
  3418. }
  3419. identity() {
  3420. this.set(
  3421. 1, 0, 0, 0,
  3422. 0, 1, 0, 0,
  3423. 0, 0, 1, 0,
  3424. 0, 0, 0, 1
  3425. );
  3426. return this;
  3427. }
  3428. clone() {
  3429. return new Matrix4().fromArray( this.elements );
  3430. }
  3431. copy( m ) {
  3432. const te = this.elements;
  3433. const me = m.elements;
  3434. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3435. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3436. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3437. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3438. return this;
  3439. }
  3440. copyPosition( m ) {
  3441. const te = this.elements, me = m.elements;
  3442. te[ 12 ] = me[ 12 ];
  3443. te[ 13 ] = me[ 13 ];
  3444. te[ 14 ] = me[ 14 ];
  3445. return this;
  3446. }
  3447. setFromMatrix3( m ) {
  3448. const me = m.elements;
  3449. this.set(
  3450. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3451. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3452. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3453. 0, 0, 0, 1
  3454. );
  3455. return this;
  3456. }
  3457. extractBasis( xAxis, yAxis, zAxis ) {
  3458. xAxis.setFromMatrixColumn( this, 0 );
  3459. yAxis.setFromMatrixColumn( this, 1 );
  3460. zAxis.setFromMatrixColumn( this, 2 );
  3461. return this;
  3462. }
  3463. makeBasis( xAxis, yAxis, zAxis ) {
  3464. this.set(
  3465. xAxis.x, yAxis.x, zAxis.x, 0,
  3466. xAxis.y, yAxis.y, zAxis.y, 0,
  3467. xAxis.z, yAxis.z, zAxis.z, 0,
  3468. 0, 0, 0, 1
  3469. );
  3470. return this;
  3471. }
  3472. extractRotation( m ) {
  3473. // this method does not support reflection matrices
  3474. const te = this.elements;
  3475. const me = m.elements;
  3476. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3477. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3478. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3479. te[ 0 ] = me[ 0 ] * scaleX;
  3480. te[ 1 ] = me[ 1 ] * scaleX;
  3481. te[ 2 ] = me[ 2 ] * scaleX;
  3482. te[ 3 ] = 0;
  3483. te[ 4 ] = me[ 4 ] * scaleY;
  3484. te[ 5 ] = me[ 5 ] * scaleY;
  3485. te[ 6 ] = me[ 6 ] * scaleY;
  3486. te[ 7 ] = 0;
  3487. te[ 8 ] = me[ 8 ] * scaleZ;
  3488. te[ 9 ] = me[ 9 ] * scaleZ;
  3489. te[ 10 ] = me[ 10 ] * scaleZ;
  3490. te[ 11 ] = 0;
  3491. te[ 12 ] = 0;
  3492. te[ 13 ] = 0;
  3493. te[ 14 ] = 0;
  3494. te[ 15 ] = 1;
  3495. return this;
  3496. }
  3497. makeRotationFromEuler( euler ) {
  3498. const te = this.elements;
  3499. const x = euler.x, y = euler.y, z = euler.z;
  3500. const a = Math.cos( x ), b = Math.sin( x );
  3501. const c = Math.cos( y ), d = Math.sin( y );
  3502. const e = Math.cos( z ), f = Math.sin( z );
  3503. if ( euler.order === 'XYZ' ) {
  3504. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3505. te[ 0 ] = c * e;
  3506. te[ 4 ] = - c * f;
  3507. te[ 8 ] = d;
  3508. te[ 1 ] = af + be * d;
  3509. te[ 5 ] = ae - bf * d;
  3510. te[ 9 ] = - b * c;
  3511. te[ 2 ] = bf - ae * d;
  3512. te[ 6 ] = be + af * d;
  3513. te[ 10 ] = a * c;
  3514. } else if ( euler.order === 'YXZ' ) {
  3515. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3516. te[ 0 ] = ce + df * b;
  3517. te[ 4 ] = de * b - cf;
  3518. te[ 8 ] = a * d;
  3519. te[ 1 ] = a * f;
  3520. te[ 5 ] = a * e;
  3521. te[ 9 ] = - b;
  3522. te[ 2 ] = cf * b - de;
  3523. te[ 6 ] = df + ce * b;
  3524. te[ 10 ] = a * c;
  3525. } else if ( euler.order === 'ZXY' ) {
  3526. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3527. te[ 0 ] = ce - df * b;
  3528. te[ 4 ] = - a * f;
  3529. te[ 8 ] = de + cf * b;
  3530. te[ 1 ] = cf + de * b;
  3531. te[ 5 ] = a * e;
  3532. te[ 9 ] = df - ce * b;
  3533. te[ 2 ] = - a * d;
  3534. te[ 6 ] = b;
  3535. te[ 10 ] = a * c;
  3536. } else if ( euler.order === 'ZYX' ) {
  3537. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3538. te[ 0 ] = c * e;
  3539. te[ 4 ] = be * d - af;
  3540. te[ 8 ] = ae * d + bf;
  3541. te[ 1 ] = c * f;
  3542. te[ 5 ] = bf * d + ae;
  3543. te[ 9 ] = af * d - be;
  3544. te[ 2 ] = - d;
  3545. te[ 6 ] = b * c;
  3546. te[ 10 ] = a * c;
  3547. } else if ( euler.order === 'YZX' ) {
  3548. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3549. te[ 0 ] = c * e;
  3550. te[ 4 ] = bd - ac * f;
  3551. te[ 8 ] = bc * f + ad;
  3552. te[ 1 ] = f;
  3553. te[ 5 ] = a * e;
  3554. te[ 9 ] = - b * e;
  3555. te[ 2 ] = - d * e;
  3556. te[ 6 ] = ad * f + bc;
  3557. te[ 10 ] = ac - bd * f;
  3558. } else if ( euler.order === 'XZY' ) {
  3559. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3560. te[ 0 ] = c * e;
  3561. te[ 4 ] = - f;
  3562. te[ 8 ] = d * e;
  3563. te[ 1 ] = ac * f + bd;
  3564. te[ 5 ] = a * e;
  3565. te[ 9 ] = ad * f - bc;
  3566. te[ 2 ] = bc * f - ad;
  3567. te[ 6 ] = b * e;
  3568. te[ 10 ] = bd * f + ac;
  3569. }
  3570. // bottom row
  3571. te[ 3 ] = 0;
  3572. te[ 7 ] = 0;
  3573. te[ 11 ] = 0;
  3574. // last column
  3575. te[ 12 ] = 0;
  3576. te[ 13 ] = 0;
  3577. te[ 14 ] = 0;
  3578. te[ 15 ] = 1;
  3579. return this;
  3580. }
  3581. makeRotationFromQuaternion( q ) {
  3582. return this.compose( _zero, q, _one );
  3583. }
  3584. lookAt( eye, target, up ) {
  3585. const te = this.elements;
  3586. _z.subVectors( eye, target );
  3587. if ( _z.lengthSq() === 0 ) {
  3588. // eye and target are in the same position
  3589. _z.z = 1;
  3590. }
  3591. _z.normalize();
  3592. _x.crossVectors( up, _z );
  3593. if ( _x.lengthSq() === 0 ) {
  3594. // up and z are parallel
  3595. if ( Math.abs( up.z ) === 1 ) {
  3596. _z.x += 0.0001;
  3597. } else {
  3598. _z.z += 0.0001;
  3599. }
  3600. _z.normalize();
  3601. _x.crossVectors( up, _z );
  3602. }
  3603. _x.normalize();
  3604. _y.crossVectors( _z, _x );
  3605. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3606. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3607. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3608. return this;
  3609. }
  3610. multiply( m ) {
  3611. return this.multiplyMatrices( this, m );
  3612. }
  3613. premultiply( m ) {
  3614. return this.multiplyMatrices( m, this );
  3615. }
  3616. multiplyMatrices( a, b ) {
  3617. const ae = a.elements;
  3618. const be = b.elements;
  3619. const te = this.elements;
  3620. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3621. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3622. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3623. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3624. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3625. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3626. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3627. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3628. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3629. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3630. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3631. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3632. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3633. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3634. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3635. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3636. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3637. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3638. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3639. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3640. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3641. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3642. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3643. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3644. return this;
  3645. }
  3646. multiplyScalar( s ) {
  3647. const te = this.elements;
  3648. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3649. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3650. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3651. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3652. return this;
  3653. }
  3654. determinant() {
  3655. const te = this.elements;
  3656. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3657. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3658. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3659. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3660. //TODO: make this more efficient
  3661. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3662. return (
  3663. n41 * (
  3664. + n14 * n23 * n32
  3665. - n13 * n24 * n32
  3666. - n14 * n22 * n33
  3667. + n12 * n24 * n33
  3668. + n13 * n22 * n34
  3669. - n12 * n23 * n34
  3670. ) +
  3671. n42 * (
  3672. + n11 * n23 * n34
  3673. - n11 * n24 * n33
  3674. + n14 * n21 * n33
  3675. - n13 * n21 * n34
  3676. + n13 * n24 * n31
  3677. - n14 * n23 * n31
  3678. ) +
  3679. n43 * (
  3680. + n11 * n24 * n32
  3681. - n11 * n22 * n34
  3682. - n14 * n21 * n32
  3683. + n12 * n21 * n34
  3684. + n14 * n22 * n31
  3685. - n12 * n24 * n31
  3686. ) +
  3687. n44 * (
  3688. - n13 * n22 * n31
  3689. - n11 * n23 * n32
  3690. + n11 * n22 * n33
  3691. + n13 * n21 * n32
  3692. - n12 * n21 * n33
  3693. + n12 * n23 * n31
  3694. )
  3695. );
  3696. }
  3697. transpose() {
  3698. const te = this.elements;
  3699. let tmp;
  3700. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3701. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3702. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3703. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3704. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3705. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3706. return this;
  3707. }
  3708. setPosition( x, y, z ) {
  3709. const te = this.elements;
  3710. if ( x.isVector3 ) {
  3711. te[ 12 ] = x.x;
  3712. te[ 13 ] = x.y;
  3713. te[ 14 ] = x.z;
  3714. } else {
  3715. te[ 12 ] = x;
  3716. te[ 13 ] = y;
  3717. te[ 14 ] = z;
  3718. }
  3719. return this;
  3720. }
  3721. invert() {
  3722. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3723. const te = this.elements,
  3724. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3725. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3726. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3727. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3728. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3729. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3730. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3731. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3732. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3733. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3734. const detInv = 1 / det;
  3735. te[ 0 ] = t11 * detInv;
  3736. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3737. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3738. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3739. te[ 4 ] = t12 * detInv;
  3740. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3741. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3742. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3743. te[ 8 ] = t13 * detInv;
  3744. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3745. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3746. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3747. te[ 12 ] = t14 * detInv;
  3748. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3749. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3750. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3751. return this;
  3752. }
  3753. scale( v ) {
  3754. const te = this.elements;
  3755. const x = v.x, y = v.y, z = v.z;
  3756. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3757. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3758. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3759. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3760. return this;
  3761. }
  3762. getMaxScaleOnAxis() {
  3763. const te = this.elements;
  3764. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3765. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3766. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3767. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3768. }
  3769. makeTranslation( x, y, z ) {
  3770. this.set(
  3771. 1, 0, 0, x,
  3772. 0, 1, 0, y,
  3773. 0, 0, 1, z,
  3774. 0, 0, 0, 1
  3775. );
  3776. return this;
  3777. }
  3778. makeRotationX( theta ) {
  3779. const c = Math.cos( theta ), s = Math.sin( theta );
  3780. this.set(
  3781. 1, 0, 0, 0,
  3782. 0, c, - s, 0,
  3783. 0, s, c, 0,
  3784. 0, 0, 0, 1
  3785. );
  3786. return this;
  3787. }
  3788. makeRotationY( theta ) {
  3789. const c = Math.cos( theta ), s = Math.sin( theta );
  3790. this.set(
  3791. c, 0, s, 0,
  3792. 0, 1, 0, 0,
  3793. - s, 0, c, 0,
  3794. 0, 0, 0, 1
  3795. );
  3796. return this;
  3797. }
  3798. makeRotationZ( theta ) {
  3799. const c = Math.cos( theta ), s = Math.sin( theta );
  3800. this.set(
  3801. c, - s, 0, 0,
  3802. s, c, 0, 0,
  3803. 0, 0, 1, 0,
  3804. 0, 0, 0, 1
  3805. );
  3806. return this;
  3807. }
  3808. makeRotationAxis( axis, angle ) {
  3809. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3810. const c = Math.cos( angle );
  3811. const s = Math.sin( angle );
  3812. const t = 1 - c;
  3813. const x = axis.x, y = axis.y, z = axis.z;
  3814. const tx = t * x, ty = t * y;
  3815. this.set(
  3816. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3817. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3818. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3819. 0, 0, 0, 1
  3820. );
  3821. return this;
  3822. }
  3823. makeScale( x, y, z ) {
  3824. this.set(
  3825. x, 0, 0, 0,
  3826. 0, y, 0, 0,
  3827. 0, 0, z, 0,
  3828. 0, 0, 0, 1
  3829. );
  3830. return this;
  3831. }
  3832. makeShear( xy, xz, yx, yz, zx, zy ) {
  3833. this.set(
  3834. 1, yx, zx, 0,
  3835. xy, 1, zy, 0,
  3836. xz, yz, 1, 0,
  3837. 0, 0, 0, 1
  3838. );
  3839. return this;
  3840. }
  3841. compose( position, quaternion, scale ) {
  3842. const te = this.elements;
  3843. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3844. const x2 = x + x, y2 = y + y, z2 = z + z;
  3845. const xx = x * x2, xy = x * y2, xz = x * z2;
  3846. const yy = y * y2, yz = y * z2, zz = z * z2;
  3847. const wx = w * x2, wy = w * y2, wz = w * z2;
  3848. const sx = scale.x, sy = scale.y, sz = scale.z;
  3849. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3850. te[ 1 ] = ( xy + wz ) * sx;
  3851. te[ 2 ] = ( xz - wy ) * sx;
  3852. te[ 3 ] = 0;
  3853. te[ 4 ] = ( xy - wz ) * sy;
  3854. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3855. te[ 6 ] = ( yz + wx ) * sy;
  3856. te[ 7 ] = 0;
  3857. te[ 8 ] = ( xz + wy ) * sz;
  3858. te[ 9 ] = ( yz - wx ) * sz;
  3859. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3860. te[ 11 ] = 0;
  3861. te[ 12 ] = position.x;
  3862. te[ 13 ] = position.y;
  3863. te[ 14 ] = position.z;
  3864. te[ 15 ] = 1;
  3865. return this;
  3866. }
  3867. decompose( position, quaternion, scale ) {
  3868. const te = this.elements;
  3869. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3870. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3871. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3872. // if determine is negative, we need to invert one scale
  3873. const det = this.determinant();
  3874. if ( det < 0 ) sx = - sx;
  3875. position.x = te[ 12 ];
  3876. position.y = te[ 13 ];
  3877. position.z = te[ 14 ];
  3878. // scale the rotation part
  3879. _m1$2.copy( this );
  3880. const invSX = 1 / sx;
  3881. const invSY = 1 / sy;
  3882. const invSZ = 1 / sz;
  3883. _m1$2.elements[ 0 ] *= invSX;
  3884. _m1$2.elements[ 1 ] *= invSX;
  3885. _m1$2.elements[ 2 ] *= invSX;
  3886. _m1$2.elements[ 4 ] *= invSY;
  3887. _m1$2.elements[ 5 ] *= invSY;
  3888. _m1$2.elements[ 6 ] *= invSY;
  3889. _m1$2.elements[ 8 ] *= invSZ;
  3890. _m1$2.elements[ 9 ] *= invSZ;
  3891. _m1$2.elements[ 10 ] *= invSZ;
  3892. quaternion.setFromRotationMatrix( _m1$2 );
  3893. scale.x = sx;
  3894. scale.y = sy;
  3895. scale.z = sz;
  3896. return this;
  3897. }
  3898. makePerspective( left, right, top, bottom, near, far ) {
  3899. const te = this.elements;
  3900. const x = 2 * near / ( right - left );
  3901. const y = 2 * near / ( top - bottom );
  3902. const a = ( right + left ) / ( right - left );
  3903. const b = ( top + bottom ) / ( top - bottom );
  3904. const c = - ( far + near ) / ( far - near );
  3905. const d = - 2 * far * near / ( far - near );
  3906. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3907. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3908. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3909. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3910. return this;
  3911. }
  3912. makeOrthographic( left, right, top, bottom, near, far ) {
  3913. const te = this.elements;
  3914. const w = 1.0 / ( right - left );
  3915. const h = 1.0 / ( top - bottom );
  3916. const p = 1.0 / ( far - near );
  3917. const x = ( right + left ) * w;
  3918. const y = ( top + bottom ) * h;
  3919. const z = ( far + near ) * p;
  3920. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3921. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3922. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3923. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3924. return this;
  3925. }
  3926. equals( matrix ) {
  3927. const te = this.elements;
  3928. const me = matrix.elements;
  3929. for ( let i = 0; i < 16; i ++ ) {
  3930. if ( te[ i ] !== me[ i ] ) return false;
  3931. }
  3932. return true;
  3933. }
  3934. fromArray( array, offset = 0 ) {
  3935. for ( let i = 0; i < 16; i ++ ) {
  3936. this.elements[ i ] = array[ i + offset ];
  3937. }
  3938. return this;
  3939. }
  3940. toArray( array = [], offset = 0 ) {
  3941. const te = this.elements;
  3942. array[ offset ] = te[ 0 ];
  3943. array[ offset + 1 ] = te[ 1 ];
  3944. array[ offset + 2 ] = te[ 2 ];
  3945. array[ offset + 3 ] = te[ 3 ];
  3946. array[ offset + 4 ] = te[ 4 ];
  3947. array[ offset + 5 ] = te[ 5 ];
  3948. array[ offset + 6 ] = te[ 6 ];
  3949. array[ offset + 7 ] = te[ 7 ];
  3950. array[ offset + 8 ] = te[ 8 ];
  3951. array[ offset + 9 ] = te[ 9 ];
  3952. array[ offset + 10 ] = te[ 10 ];
  3953. array[ offset + 11 ] = te[ 11 ];
  3954. array[ offset + 12 ] = te[ 12 ];
  3955. array[ offset + 13 ] = te[ 13 ];
  3956. array[ offset + 14 ] = te[ 14 ];
  3957. array[ offset + 15 ] = te[ 15 ];
  3958. return array;
  3959. }
  3960. }
  3961. const _v1$5 = /*@__PURE__*/ new Vector3();
  3962. const _m1$2 = /*@__PURE__*/ new Matrix4();
  3963. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3964. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3965. const _x = /*@__PURE__*/ new Vector3();
  3966. const _y = /*@__PURE__*/ new Vector3();
  3967. const _z = /*@__PURE__*/ new Vector3();
  3968. const _matrix = /*@__PURE__*/ new Matrix4();
  3969. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  3970. class Euler {
  3971. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  3972. this.isEuler = true;
  3973. this._x = x;
  3974. this._y = y;
  3975. this._z = z;
  3976. this._order = order;
  3977. }
  3978. get x() {
  3979. return this._x;
  3980. }
  3981. set x( value ) {
  3982. this._x = value;
  3983. this._onChangeCallback();
  3984. }
  3985. get y() {
  3986. return this._y;
  3987. }
  3988. set y( value ) {
  3989. this._y = value;
  3990. this._onChangeCallback();
  3991. }
  3992. get z() {
  3993. return this._z;
  3994. }
  3995. set z( value ) {
  3996. this._z = value;
  3997. this._onChangeCallback();
  3998. }
  3999. get order() {
  4000. return this._order;
  4001. }
  4002. set order( value ) {
  4003. this._order = value;
  4004. this._onChangeCallback();
  4005. }
  4006. set( x, y, z, order = this._order ) {
  4007. this._x = x;
  4008. this._y = y;
  4009. this._z = z;
  4010. this._order = order;
  4011. this._onChangeCallback();
  4012. return this;
  4013. }
  4014. clone() {
  4015. return new this.constructor( this._x, this._y, this._z, this._order );
  4016. }
  4017. copy( euler ) {
  4018. this._x = euler._x;
  4019. this._y = euler._y;
  4020. this._z = euler._z;
  4021. this._order = euler._order;
  4022. this._onChangeCallback();
  4023. return this;
  4024. }
  4025. setFromRotationMatrix( m, order = this._order, update = true ) {
  4026. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4027. const te = m.elements;
  4028. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4029. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4030. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4031. switch ( order ) {
  4032. case 'XYZ':
  4033. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4034. if ( Math.abs( m13 ) < 0.9999999 ) {
  4035. this._x = Math.atan2( - m23, m33 );
  4036. this._z = Math.atan2( - m12, m11 );
  4037. } else {
  4038. this._x = Math.atan2( m32, m22 );
  4039. this._z = 0;
  4040. }
  4041. break;
  4042. case 'YXZ':
  4043. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4044. if ( Math.abs( m23 ) < 0.9999999 ) {
  4045. this._y = Math.atan2( m13, m33 );
  4046. this._z = Math.atan2( m21, m22 );
  4047. } else {
  4048. this._y = Math.atan2( - m31, m11 );
  4049. this._z = 0;
  4050. }
  4051. break;
  4052. case 'ZXY':
  4053. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4054. if ( Math.abs( m32 ) < 0.9999999 ) {
  4055. this._y = Math.atan2( - m31, m33 );
  4056. this._z = Math.atan2( - m12, m22 );
  4057. } else {
  4058. this._y = 0;
  4059. this._z = Math.atan2( m21, m11 );
  4060. }
  4061. break;
  4062. case 'ZYX':
  4063. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4064. if ( Math.abs( m31 ) < 0.9999999 ) {
  4065. this._x = Math.atan2( m32, m33 );
  4066. this._z = Math.atan2( m21, m11 );
  4067. } else {
  4068. this._x = 0;
  4069. this._z = Math.atan2( - m12, m22 );
  4070. }
  4071. break;
  4072. case 'YZX':
  4073. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4074. if ( Math.abs( m21 ) < 0.9999999 ) {
  4075. this._x = Math.atan2( - m23, m22 );
  4076. this._y = Math.atan2( - m31, m11 );
  4077. } else {
  4078. this._x = 0;
  4079. this._y = Math.atan2( m13, m33 );
  4080. }
  4081. break;
  4082. case 'XZY':
  4083. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4084. if ( Math.abs( m12 ) < 0.9999999 ) {
  4085. this._x = Math.atan2( m32, m22 );
  4086. this._y = Math.atan2( m13, m11 );
  4087. } else {
  4088. this._x = Math.atan2( - m23, m33 );
  4089. this._y = 0;
  4090. }
  4091. break;
  4092. default:
  4093. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4094. }
  4095. this._order = order;
  4096. if ( update === true ) this._onChangeCallback();
  4097. return this;
  4098. }
  4099. setFromQuaternion( q, order, update ) {
  4100. _matrix.makeRotationFromQuaternion( q );
  4101. return this.setFromRotationMatrix( _matrix, order, update );
  4102. }
  4103. setFromVector3( v, order = this._order ) {
  4104. return this.set( v.x, v.y, v.z, order );
  4105. }
  4106. reorder( newOrder ) {
  4107. // WARNING: this discards revolution information -bhouston
  4108. _quaternion$3.setFromEuler( this );
  4109. return this.setFromQuaternion( _quaternion$3, newOrder );
  4110. }
  4111. equals( euler ) {
  4112. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4113. }
  4114. fromArray( array ) {
  4115. this._x = array[ 0 ];
  4116. this._y = array[ 1 ];
  4117. this._z = array[ 2 ];
  4118. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4119. this._onChangeCallback();
  4120. return this;
  4121. }
  4122. toArray( array = [], offset = 0 ) {
  4123. array[ offset ] = this._x;
  4124. array[ offset + 1 ] = this._y;
  4125. array[ offset + 2 ] = this._z;
  4126. array[ offset + 3 ] = this._order;
  4127. return array;
  4128. }
  4129. _onChange( callback ) {
  4130. this._onChangeCallback = callback;
  4131. return this;
  4132. }
  4133. _onChangeCallback() {}
  4134. *[ Symbol.iterator ]() {
  4135. yield this._x;
  4136. yield this._y;
  4137. yield this._z;
  4138. yield this._order;
  4139. }
  4140. }
  4141. Euler.DEFAULT_ORDER = 'XYZ';
  4142. class Layers {
  4143. constructor() {
  4144. this.mask = 1 | 0;
  4145. }
  4146. set( channel ) {
  4147. this.mask = ( 1 << channel | 0 ) >>> 0;
  4148. }
  4149. enable( channel ) {
  4150. this.mask |= 1 << channel | 0;
  4151. }
  4152. enableAll() {
  4153. this.mask = 0xffffffff | 0;
  4154. }
  4155. toggle( channel ) {
  4156. this.mask ^= 1 << channel | 0;
  4157. }
  4158. disable( channel ) {
  4159. this.mask &= ~ ( 1 << channel | 0 );
  4160. }
  4161. disableAll() {
  4162. this.mask = 0;
  4163. }
  4164. test( layers ) {
  4165. return ( this.mask & layers.mask ) !== 0;
  4166. }
  4167. isEnabled( channel ) {
  4168. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4169. }
  4170. }
  4171. let _object3DId = 0;
  4172. const _v1$4 = /*@__PURE__*/ new Vector3();
  4173. const _q1 = /*@__PURE__*/ new Quaternion();
  4174. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4175. const _target = /*@__PURE__*/ new Vector3();
  4176. const _position$3 = /*@__PURE__*/ new Vector3();
  4177. const _scale$2 = /*@__PURE__*/ new Vector3();
  4178. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4179. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4180. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4181. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4182. const _addedEvent = { type: 'added' };
  4183. const _removedEvent = { type: 'removed' };
  4184. class Object3D extends EventDispatcher {
  4185. constructor() {
  4186. super();
  4187. this.isObject3D = true;
  4188. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4189. this.uuid = generateUUID();
  4190. this.name = '';
  4191. this.type = 'Object3D';
  4192. this.parent = null;
  4193. this.children = [];
  4194. this.up = Object3D.DEFAULT_UP.clone();
  4195. const position = new Vector3();
  4196. const rotation = new Euler();
  4197. const quaternion = new Quaternion();
  4198. const scale = new Vector3( 1, 1, 1 );
  4199. function onRotationChange() {
  4200. quaternion.setFromEuler( rotation, false );
  4201. }
  4202. function onQuaternionChange() {
  4203. rotation.setFromQuaternion( quaternion, undefined, false );
  4204. }
  4205. rotation._onChange( onRotationChange );
  4206. quaternion._onChange( onQuaternionChange );
  4207. Object.defineProperties( this, {
  4208. position: {
  4209. configurable: true,
  4210. enumerable: true,
  4211. value: position
  4212. },
  4213. rotation: {
  4214. configurable: true,
  4215. enumerable: true,
  4216. value: rotation
  4217. },
  4218. quaternion: {
  4219. configurable: true,
  4220. enumerable: true,
  4221. value: quaternion
  4222. },
  4223. scale: {
  4224. configurable: true,
  4225. enumerable: true,
  4226. value: scale
  4227. },
  4228. modelViewMatrix: {
  4229. value: new Matrix4()
  4230. },
  4231. normalMatrix: {
  4232. value: new Matrix3()
  4233. }
  4234. } );
  4235. this.matrix = new Matrix4();
  4236. this.matrixWorld = new Matrix4();
  4237. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4238. this.matrixWorldNeedsUpdate = false;
  4239. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4240. this.layers = new Layers();
  4241. this.visible = true;
  4242. this.castShadow = false;
  4243. this.receiveShadow = false;
  4244. this.frustumCulled = true;
  4245. this.renderOrder = 0;
  4246. this.animations = [];
  4247. this.userData = {};
  4248. }
  4249. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4250. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4251. applyMatrix4( matrix ) {
  4252. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4253. this.matrix.premultiply( matrix );
  4254. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4255. }
  4256. applyQuaternion( q ) {
  4257. this.quaternion.premultiply( q );
  4258. return this;
  4259. }
  4260. setRotationFromAxisAngle( axis, angle ) {
  4261. // assumes axis is normalized
  4262. this.quaternion.setFromAxisAngle( axis, angle );
  4263. }
  4264. setRotationFromEuler( euler ) {
  4265. this.quaternion.setFromEuler( euler, true );
  4266. }
  4267. setRotationFromMatrix( m ) {
  4268. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4269. this.quaternion.setFromRotationMatrix( m );
  4270. }
  4271. setRotationFromQuaternion( q ) {
  4272. // assumes q is normalized
  4273. this.quaternion.copy( q );
  4274. }
  4275. rotateOnAxis( axis, angle ) {
  4276. // rotate object on axis in object space
  4277. // axis is assumed to be normalized
  4278. _q1.setFromAxisAngle( axis, angle );
  4279. this.quaternion.multiply( _q1 );
  4280. return this;
  4281. }
  4282. rotateOnWorldAxis( axis, angle ) {
  4283. // rotate object on axis in world space
  4284. // axis is assumed to be normalized
  4285. // method assumes no rotated parent
  4286. _q1.setFromAxisAngle( axis, angle );
  4287. this.quaternion.premultiply( _q1 );
  4288. return this;
  4289. }
  4290. rotateX( angle ) {
  4291. return this.rotateOnAxis( _xAxis, angle );
  4292. }
  4293. rotateY( angle ) {
  4294. return this.rotateOnAxis( _yAxis, angle );
  4295. }
  4296. rotateZ( angle ) {
  4297. return this.rotateOnAxis( _zAxis, angle );
  4298. }
  4299. translateOnAxis( axis, distance ) {
  4300. // translate object by distance along axis in object space
  4301. // axis is assumed to be normalized
  4302. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4303. this.position.add( _v1$4.multiplyScalar( distance ) );
  4304. return this;
  4305. }
  4306. translateX( distance ) {
  4307. return this.translateOnAxis( _xAxis, distance );
  4308. }
  4309. translateY( distance ) {
  4310. return this.translateOnAxis( _yAxis, distance );
  4311. }
  4312. translateZ( distance ) {
  4313. return this.translateOnAxis( _zAxis, distance );
  4314. }
  4315. localToWorld( vector ) {
  4316. this.updateWorldMatrix( true, false );
  4317. return vector.applyMatrix4( this.matrixWorld );
  4318. }
  4319. worldToLocal( vector ) {
  4320. this.updateWorldMatrix( true, false );
  4321. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4322. }
  4323. lookAt( x, y, z ) {
  4324. // This method does not support objects having non-uniformly-scaled parent(s)
  4325. if ( x.isVector3 ) {
  4326. _target.copy( x );
  4327. } else {
  4328. _target.set( x, y, z );
  4329. }
  4330. const parent = this.parent;
  4331. this.updateWorldMatrix( true, false );
  4332. _position$3.setFromMatrixPosition( this.matrixWorld );
  4333. if ( this.isCamera || this.isLight ) {
  4334. _m1$1.lookAt( _position$3, _target, this.up );
  4335. } else {
  4336. _m1$1.lookAt( _target, _position$3, this.up );
  4337. }
  4338. this.quaternion.setFromRotationMatrix( _m1$1 );
  4339. if ( parent ) {
  4340. _m1$1.extractRotation( parent.matrixWorld );
  4341. _q1.setFromRotationMatrix( _m1$1 );
  4342. this.quaternion.premultiply( _q1.invert() );
  4343. }
  4344. }
  4345. add( object ) {
  4346. if ( arguments.length > 1 ) {
  4347. for ( let i = 0; i < arguments.length; i ++ ) {
  4348. this.add( arguments[ i ] );
  4349. }
  4350. return this;
  4351. }
  4352. if ( object === this ) {
  4353. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4354. return this;
  4355. }
  4356. if ( object && object.isObject3D ) {
  4357. if ( object.parent !== null ) {
  4358. object.parent.remove( object );
  4359. }
  4360. object.parent = this;
  4361. this.children.push( object );
  4362. object.dispatchEvent( _addedEvent );
  4363. } else {
  4364. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4365. }
  4366. return this;
  4367. }
  4368. remove( object ) {
  4369. if ( arguments.length > 1 ) {
  4370. for ( let i = 0; i < arguments.length; i ++ ) {
  4371. this.remove( arguments[ i ] );
  4372. }
  4373. return this;
  4374. }
  4375. const index = this.children.indexOf( object );
  4376. if ( index !== - 1 ) {
  4377. object.parent = null;
  4378. this.children.splice( index, 1 );
  4379. object.dispatchEvent( _removedEvent );
  4380. }
  4381. return this;
  4382. }
  4383. removeFromParent() {
  4384. const parent = this.parent;
  4385. if ( parent !== null ) {
  4386. parent.remove( this );
  4387. }
  4388. return this;
  4389. }
  4390. clear() {
  4391. for ( let i = 0; i < this.children.length; i ++ ) {
  4392. const object = this.children[ i ];
  4393. object.parent = null;
  4394. object.dispatchEvent( _removedEvent );
  4395. }
  4396. this.children.length = 0;
  4397. return this;
  4398. }
  4399. attach( object ) {
  4400. // adds object as a child of this, while maintaining the object's world transform
  4401. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4402. this.updateWorldMatrix( true, false );
  4403. _m1$1.copy( this.matrixWorld ).invert();
  4404. if ( object.parent !== null ) {
  4405. object.parent.updateWorldMatrix( true, false );
  4406. _m1$1.multiply( object.parent.matrixWorld );
  4407. }
  4408. object.applyMatrix4( _m1$1 );
  4409. this.add( object );
  4410. object.updateWorldMatrix( false, true );
  4411. return this;
  4412. }
  4413. getObjectById( id ) {
  4414. return this.getObjectByProperty( 'id', id );
  4415. }
  4416. getObjectByName( name ) {
  4417. return this.getObjectByProperty( 'name', name );
  4418. }
  4419. getObjectByProperty( name, value ) {
  4420. if ( this[ name ] === value ) return this;
  4421. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4422. const child = this.children[ i ];
  4423. const object = child.getObjectByProperty( name, value );
  4424. if ( object !== undefined ) {
  4425. return object;
  4426. }
  4427. }
  4428. return undefined;
  4429. }
  4430. getObjectsByProperty( name, value ) {
  4431. let result = [];
  4432. if ( this[ name ] === value ) result.push( this );
  4433. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4434. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4435. if ( childResult.length > 0 ) {
  4436. result = result.concat( childResult );
  4437. }
  4438. }
  4439. return result;
  4440. }
  4441. getWorldPosition( target ) {
  4442. this.updateWorldMatrix( true, false );
  4443. return target.setFromMatrixPosition( this.matrixWorld );
  4444. }
  4445. getWorldQuaternion( target ) {
  4446. this.updateWorldMatrix( true, false );
  4447. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4448. return target;
  4449. }
  4450. getWorldScale( target ) {
  4451. this.updateWorldMatrix( true, false );
  4452. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4453. return target;
  4454. }
  4455. getWorldDirection( target ) {
  4456. this.updateWorldMatrix( true, false );
  4457. const e = this.matrixWorld.elements;
  4458. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4459. }
  4460. raycast( /* raycaster, intersects */ ) {}
  4461. traverse( callback ) {
  4462. callback( this );
  4463. const children = this.children;
  4464. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4465. children[ i ].traverse( callback );
  4466. }
  4467. }
  4468. traverseVisible( callback ) {
  4469. if ( this.visible === false ) return;
  4470. callback( this );
  4471. const children = this.children;
  4472. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4473. children[ i ].traverseVisible( callback );
  4474. }
  4475. }
  4476. traverseAncestors( callback ) {
  4477. const parent = this.parent;
  4478. if ( parent !== null ) {
  4479. callback( parent );
  4480. parent.traverseAncestors( callback );
  4481. }
  4482. }
  4483. updateMatrix() {
  4484. this.matrix.compose( this.position, this.quaternion, this.scale );
  4485. this.matrixWorldNeedsUpdate = true;
  4486. }
  4487. updateMatrixWorld( force ) {
  4488. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4489. if ( this.matrixWorldNeedsUpdate || force ) {
  4490. if ( this.parent === null ) {
  4491. this.matrixWorld.copy( this.matrix );
  4492. } else {
  4493. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4494. }
  4495. this.matrixWorldNeedsUpdate = false;
  4496. force = true;
  4497. }
  4498. // update children
  4499. const children = this.children;
  4500. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4501. const child = children[ i ];
  4502. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4503. child.updateMatrixWorld( force );
  4504. }
  4505. }
  4506. }
  4507. updateWorldMatrix( updateParents, updateChildren ) {
  4508. const parent = this.parent;
  4509. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4510. parent.updateWorldMatrix( true, false );
  4511. }
  4512. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4513. if ( this.parent === null ) {
  4514. this.matrixWorld.copy( this.matrix );
  4515. } else {
  4516. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4517. }
  4518. // update children
  4519. if ( updateChildren === true ) {
  4520. const children = this.children;
  4521. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4522. const child = children[ i ];
  4523. if ( child.matrixWorldAutoUpdate === true ) {
  4524. child.updateWorldMatrix( false, true );
  4525. }
  4526. }
  4527. }
  4528. }
  4529. toJSON( meta ) {
  4530. // meta is a string when called from JSON.stringify
  4531. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4532. const output = {};
  4533. // meta is a hash used to collect geometries, materials.
  4534. // not providing it implies that this is the root object
  4535. // being serialized.
  4536. if ( isRootObject ) {
  4537. // initialize meta obj
  4538. meta = {
  4539. geometries: {},
  4540. materials: {},
  4541. textures: {},
  4542. images: {},
  4543. shapes: {},
  4544. skeletons: {},
  4545. animations: {},
  4546. nodes: {}
  4547. };
  4548. output.metadata = {
  4549. version: 4.5,
  4550. type: 'Object',
  4551. generator: 'Object3D.toJSON'
  4552. };
  4553. }
  4554. // standard Object3D serialization
  4555. const object = {};
  4556. object.uuid = this.uuid;
  4557. object.type = this.type;
  4558. if ( this.name !== '' ) object.name = this.name;
  4559. if ( this.castShadow === true ) object.castShadow = true;
  4560. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4561. if ( this.visible === false ) object.visible = false;
  4562. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4563. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4564. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4565. object.layers = this.layers.mask;
  4566. object.matrix = this.matrix.toArray();
  4567. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4568. // object specific properties
  4569. if ( this.isInstancedMesh ) {
  4570. object.type = 'InstancedMesh';
  4571. object.count = this.count;
  4572. object.instanceMatrix = this.instanceMatrix.toJSON();
  4573. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4574. }
  4575. //
  4576. function serialize( library, element ) {
  4577. if ( library[ element.uuid ] === undefined ) {
  4578. library[ element.uuid ] = element.toJSON( meta );
  4579. }
  4580. return element.uuid;
  4581. }
  4582. if ( this.isScene ) {
  4583. if ( this.background ) {
  4584. if ( this.background.isColor ) {
  4585. object.background = this.background.toJSON();
  4586. } else if ( this.background.isTexture ) {
  4587. object.background = this.background.toJSON( meta ).uuid;
  4588. }
  4589. }
  4590. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4591. object.environment = this.environment.toJSON( meta ).uuid;
  4592. }
  4593. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4594. object.geometry = serialize( meta.geometries, this.geometry );
  4595. const parameters = this.geometry.parameters;
  4596. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4597. const shapes = parameters.shapes;
  4598. if ( Array.isArray( shapes ) ) {
  4599. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4600. const shape = shapes[ i ];
  4601. serialize( meta.shapes, shape );
  4602. }
  4603. } else {
  4604. serialize( meta.shapes, shapes );
  4605. }
  4606. }
  4607. }
  4608. if ( this.isSkinnedMesh ) {
  4609. object.bindMode = this.bindMode;
  4610. object.bindMatrix = this.bindMatrix.toArray();
  4611. if ( this.skeleton !== undefined ) {
  4612. serialize( meta.skeletons, this.skeleton );
  4613. object.skeleton = this.skeleton.uuid;
  4614. }
  4615. }
  4616. if ( this.material !== undefined ) {
  4617. if ( Array.isArray( this.material ) ) {
  4618. const uuids = [];
  4619. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4620. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4621. }
  4622. object.material = uuids;
  4623. } else {
  4624. object.material = serialize( meta.materials, this.material );
  4625. }
  4626. }
  4627. //
  4628. if ( this.children.length > 0 ) {
  4629. object.children = [];
  4630. for ( let i = 0; i < this.children.length; i ++ ) {
  4631. object.children.push( this.children[ i ].toJSON( meta ).object );
  4632. }
  4633. }
  4634. //
  4635. if ( this.animations.length > 0 ) {
  4636. object.animations = [];
  4637. for ( let i = 0; i < this.animations.length; i ++ ) {
  4638. const animation = this.animations[ i ];
  4639. object.animations.push( serialize( meta.animations, animation ) );
  4640. }
  4641. }
  4642. if ( isRootObject ) {
  4643. const geometries = extractFromCache( meta.geometries );
  4644. const materials = extractFromCache( meta.materials );
  4645. const textures = extractFromCache( meta.textures );
  4646. const images = extractFromCache( meta.images );
  4647. const shapes = extractFromCache( meta.shapes );
  4648. const skeletons = extractFromCache( meta.skeletons );
  4649. const animations = extractFromCache( meta.animations );
  4650. const nodes = extractFromCache( meta.nodes );
  4651. if ( geometries.length > 0 ) output.geometries = geometries;
  4652. if ( materials.length > 0 ) output.materials = materials;
  4653. if ( textures.length > 0 ) output.textures = textures;
  4654. if ( images.length > 0 ) output.images = images;
  4655. if ( shapes.length > 0 ) output.shapes = shapes;
  4656. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4657. if ( animations.length > 0 ) output.animations = animations;
  4658. if ( nodes.length > 0 ) output.nodes = nodes;
  4659. }
  4660. output.object = object;
  4661. return output;
  4662. // extract data from the cache hash
  4663. // remove metadata on each item
  4664. // and return as array
  4665. function extractFromCache( cache ) {
  4666. const values = [];
  4667. for ( const key in cache ) {
  4668. const data = cache[ key ];
  4669. delete data.metadata;
  4670. values.push( data );
  4671. }
  4672. return values;
  4673. }
  4674. }
  4675. clone( recursive ) {
  4676. return new this.constructor().copy( this, recursive );
  4677. }
  4678. copy( source, recursive = true ) {
  4679. this.name = source.name;
  4680. this.up.copy( source.up );
  4681. this.position.copy( source.position );
  4682. this.rotation.order = source.rotation.order;
  4683. this.quaternion.copy( source.quaternion );
  4684. this.scale.copy( source.scale );
  4685. this.matrix.copy( source.matrix );
  4686. this.matrixWorld.copy( source.matrixWorld );
  4687. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4688. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4689. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4690. this.layers.mask = source.layers.mask;
  4691. this.visible = source.visible;
  4692. this.castShadow = source.castShadow;
  4693. this.receiveShadow = source.receiveShadow;
  4694. this.frustumCulled = source.frustumCulled;
  4695. this.renderOrder = source.renderOrder;
  4696. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4697. if ( recursive === true ) {
  4698. for ( let i = 0; i < source.children.length; i ++ ) {
  4699. const child = source.children[ i ];
  4700. this.add( child.clone() );
  4701. }
  4702. }
  4703. return this;
  4704. }
  4705. }
  4706. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4707. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4708. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4709. const _v0$1 = /*@__PURE__*/ new Vector3();
  4710. const _v1$3 = /*@__PURE__*/ new Vector3();
  4711. const _v2$2 = /*@__PURE__*/ new Vector3();
  4712. const _v3$1 = /*@__PURE__*/ new Vector3();
  4713. const _vab = /*@__PURE__*/ new Vector3();
  4714. const _vac = /*@__PURE__*/ new Vector3();
  4715. const _vbc = /*@__PURE__*/ new Vector3();
  4716. const _vap = /*@__PURE__*/ new Vector3();
  4717. const _vbp = /*@__PURE__*/ new Vector3();
  4718. const _vcp = /*@__PURE__*/ new Vector3();
  4719. class Triangle {
  4720. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4721. this.a = a;
  4722. this.b = b;
  4723. this.c = c;
  4724. }
  4725. static getNormal( a, b, c, target ) {
  4726. target.subVectors( c, b );
  4727. _v0$1.subVectors( a, b );
  4728. target.cross( _v0$1 );
  4729. const targetLengthSq = target.lengthSq();
  4730. if ( targetLengthSq > 0 ) {
  4731. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4732. }
  4733. return target.set( 0, 0, 0 );
  4734. }
  4735. // static/instance method to calculate barycentric coordinates
  4736. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4737. static getBarycoord( point, a, b, c, target ) {
  4738. _v0$1.subVectors( c, a );
  4739. _v1$3.subVectors( b, a );
  4740. _v2$2.subVectors( point, a );
  4741. const dot00 = _v0$1.dot( _v0$1 );
  4742. const dot01 = _v0$1.dot( _v1$3 );
  4743. const dot02 = _v0$1.dot( _v2$2 );
  4744. const dot11 = _v1$3.dot( _v1$3 );
  4745. const dot12 = _v1$3.dot( _v2$2 );
  4746. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4747. // collinear or singular triangle
  4748. if ( denom === 0 ) {
  4749. // arbitrary location outside of triangle?
  4750. // not sure if this is the best idea, maybe should be returning undefined
  4751. return target.set( - 2, - 1, - 1 );
  4752. }
  4753. const invDenom = 1 / denom;
  4754. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4755. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4756. // barycentric coordinates must always sum to 1
  4757. return target.set( 1 - u - v, v, u );
  4758. }
  4759. static containsPoint( point, a, b, c ) {
  4760. this.getBarycoord( point, a, b, c, _v3$1 );
  4761. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4762. }
  4763. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  4764. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4765. target.set( 0, 0 );
  4766. target.addScaledVector( uv1, _v3$1.x );
  4767. target.addScaledVector( uv2, _v3$1.y );
  4768. target.addScaledVector( uv3, _v3$1.z );
  4769. return target;
  4770. }
  4771. static isFrontFacing( a, b, c, direction ) {
  4772. _v0$1.subVectors( c, b );
  4773. _v1$3.subVectors( a, b );
  4774. // strictly front facing
  4775. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4776. }
  4777. set( a, b, c ) {
  4778. this.a.copy( a );
  4779. this.b.copy( b );
  4780. this.c.copy( c );
  4781. return this;
  4782. }
  4783. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4784. this.a.copy( points[ i0 ] );
  4785. this.b.copy( points[ i1 ] );
  4786. this.c.copy( points[ i2 ] );
  4787. return this;
  4788. }
  4789. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4790. this.a.fromBufferAttribute( attribute, i0 );
  4791. this.b.fromBufferAttribute( attribute, i1 );
  4792. this.c.fromBufferAttribute( attribute, i2 );
  4793. return this;
  4794. }
  4795. clone() {
  4796. return new this.constructor().copy( this );
  4797. }
  4798. copy( triangle ) {
  4799. this.a.copy( triangle.a );
  4800. this.b.copy( triangle.b );
  4801. this.c.copy( triangle.c );
  4802. return this;
  4803. }
  4804. getArea() {
  4805. _v0$1.subVectors( this.c, this.b );
  4806. _v1$3.subVectors( this.a, this.b );
  4807. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4808. }
  4809. getMidpoint( target ) {
  4810. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4811. }
  4812. getNormal( target ) {
  4813. return Triangle.getNormal( this.a, this.b, this.c, target );
  4814. }
  4815. getPlane( target ) {
  4816. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4817. }
  4818. getBarycoord( point, target ) {
  4819. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4820. }
  4821. getUV( point, uv1, uv2, uv3, target ) {
  4822. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4823. }
  4824. containsPoint( point ) {
  4825. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4826. }
  4827. isFrontFacing( direction ) {
  4828. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4829. }
  4830. intersectsBox( box ) {
  4831. return box.intersectsTriangle( this );
  4832. }
  4833. closestPointToPoint( p, target ) {
  4834. const a = this.a, b = this.b, c = this.c;
  4835. let v, w;
  4836. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4837. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4838. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4839. // basically, we're distinguishing which of the voronoi regions of the triangle
  4840. // the point lies in with the minimum amount of redundant computation.
  4841. _vab.subVectors( b, a );
  4842. _vac.subVectors( c, a );
  4843. _vap.subVectors( p, a );
  4844. const d1 = _vab.dot( _vap );
  4845. const d2 = _vac.dot( _vap );
  4846. if ( d1 <= 0 && d2 <= 0 ) {
  4847. // vertex region of A; barycentric coords (1, 0, 0)
  4848. return target.copy( a );
  4849. }
  4850. _vbp.subVectors( p, b );
  4851. const d3 = _vab.dot( _vbp );
  4852. const d4 = _vac.dot( _vbp );
  4853. if ( d3 >= 0 && d4 <= d3 ) {
  4854. // vertex region of B; barycentric coords (0, 1, 0)
  4855. return target.copy( b );
  4856. }
  4857. const vc = d1 * d4 - d3 * d2;
  4858. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4859. v = d1 / ( d1 - d3 );
  4860. // edge region of AB; barycentric coords (1-v, v, 0)
  4861. return target.copy( a ).addScaledVector( _vab, v );
  4862. }
  4863. _vcp.subVectors( p, c );
  4864. const d5 = _vab.dot( _vcp );
  4865. const d6 = _vac.dot( _vcp );
  4866. if ( d6 >= 0 && d5 <= d6 ) {
  4867. // vertex region of C; barycentric coords (0, 0, 1)
  4868. return target.copy( c );
  4869. }
  4870. const vb = d5 * d2 - d1 * d6;
  4871. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4872. w = d2 / ( d2 - d6 );
  4873. // edge region of AC; barycentric coords (1-w, 0, w)
  4874. return target.copy( a ).addScaledVector( _vac, w );
  4875. }
  4876. const va = d3 * d6 - d5 * d4;
  4877. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4878. _vbc.subVectors( c, b );
  4879. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4880. // edge region of BC; barycentric coords (0, 1-w, w)
  4881. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4882. }
  4883. // face region
  4884. const denom = 1 / ( va + vb + vc );
  4885. // u = va * denom
  4886. v = vb * denom;
  4887. w = vc * denom;
  4888. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4889. }
  4890. equals( triangle ) {
  4891. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4892. }
  4893. }
  4894. let materialId = 0;
  4895. class Material extends EventDispatcher {
  4896. constructor() {
  4897. super();
  4898. this.isMaterial = true;
  4899. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4900. this.uuid = generateUUID();
  4901. this.name = '';
  4902. this.type = 'Material';
  4903. this.blending = NormalBlending;
  4904. this.side = FrontSide;
  4905. this.vertexColors = false;
  4906. this.opacity = 1;
  4907. this.transparent = false;
  4908. this.blendSrc = SrcAlphaFactor;
  4909. this.blendDst = OneMinusSrcAlphaFactor;
  4910. this.blendEquation = AddEquation;
  4911. this.blendSrcAlpha = null;
  4912. this.blendDstAlpha = null;
  4913. this.blendEquationAlpha = null;
  4914. this.depthFunc = LessEqualDepth;
  4915. this.depthTest = true;
  4916. this.depthWrite = true;
  4917. this.stencilWriteMask = 0xff;
  4918. this.stencilFunc = AlwaysStencilFunc;
  4919. this.stencilRef = 0;
  4920. this.stencilFuncMask = 0xff;
  4921. this.stencilFail = KeepStencilOp;
  4922. this.stencilZFail = KeepStencilOp;
  4923. this.stencilZPass = KeepStencilOp;
  4924. this.stencilWrite = false;
  4925. this.clippingPlanes = null;
  4926. this.clipIntersection = false;
  4927. this.clipShadows = false;
  4928. this.shadowSide = null;
  4929. this.colorWrite = true;
  4930. this.precision = null; // override the renderer's default precision for this material
  4931. this.polygonOffset = false;
  4932. this.polygonOffsetFactor = 0;
  4933. this.polygonOffsetUnits = 0;
  4934. this.dithering = false;
  4935. this.alphaToCoverage = false;
  4936. this.premultipliedAlpha = false;
  4937. this.forceSinglePass = false;
  4938. this.visible = true;
  4939. this.toneMapped = true;
  4940. this.userData = {};
  4941. this.version = 0;
  4942. this._alphaTest = 0;
  4943. }
  4944. get alphaTest() {
  4945. return this._alphaTest;
  4946. }
  4947. set alphaTest( value ) {
  4948. if ( this._alphaTest > 0 !== value > 0 ) {
  4949. this.version ++;
  4950. }
  4951. this._alphaTest = value;
  4952. }
  4953. onBuild( /* shaderobject, renderer */ ) {}
  4954. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  4955. onBeforeCompile( /* shaderobject, renderer */ ) {}
  4956. customProgramCacheKey() {
  4957. return this.onBeforeCompile.toString();
  4958. }
  4959. setValues( values ) {
  4960. if ( values === undefined ) return;
  4961. for ( const key in values ) {
  4962. const newValue = values[ key ];
  4963. if ( newValue === undefined ) {
  4964. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  4965. continue;
  4966. }
  4967. const currentValue = this[ key ];
  4968. if ( currentValue === undefined ) {
  4969. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  4970. continue;
  4971. }
  4972. if ( currentValue && currentValue.isColor ) {
  4973. currentValue.set( newValue );
  4974. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4975. currentValue.copy( newValue );
  4976. } else {
  4977. this[ key ] = newValue;
  4978. }
  4979. }
  4980. }
  4981. toJSON( meta ) {
  4982. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4983. if ( isRootObject ) {
  4984. meta = {
  4985. textures: {},
  4986. images: {}
  4987. };
  4988. }
  4989. const data = {
  4990. metadata: {
  4991. version: 4.5,
  4992. type: 'Material',
  4993. generator: 'Material.toJSON'
  4994. }
  4995. };
  4996. // standard Material serialization
  4997. data.uuid = this.uuid;
  4998. data.type = this.type;
  4999. if ( this.name !== '' ) data.name = this.name;
  5000. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5001. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5002. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5003. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5004. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5005. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5006. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5007. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5008. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5009. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5010. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5011. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5012. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5013. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5014. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5015. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5016. }
  5017. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5018. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5019. }
  5020. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5021. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5022. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5023. }
  5024. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5025. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5026. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5027. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5028. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5029. }
  5030. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5031. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5032. }
  5033. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5034. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5035. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5036. if ( this.lightMap && this.lightMap.isTexture ) {
  5037. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5038. data.lightMapIntensity = this.lightMapIntensity;
  5039. }
  5040. if ( this.aoMap && this.aoMap.isTexture ) {
  5041. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5042. data.aoMapIntensity = this.aoMapIntensity;
  5043. }
  5044. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5045. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5046. data.bumpScale = this.bumpScale;
  5047. }
  5048. if ( this.normalMap && this.normalMap.isTexture ) {
  5049. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5050. data.normalMapType = this.normalMapType;
  5051. data.normalScale = this.normalScale.toArray();
  5052. }
  5053. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5054. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5055. data.displacementScale = this.displacementScale;
  5056. data.displacementBias = this.displacementBias;
  5057. }
  5058. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5059. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5060. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5061. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5062. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5063. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5064. if ( this.envMap && this.envMap.isTexture ) {
  5065. data.envMap = this.envMap.toJSON( meta ).uuid;
  5066. if ( this.combine !== undefined ) data.combine = this.combine;
  5067. }
  5068. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5069. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5070. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5071. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5072. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5073. }
  5074. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5075. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5076. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5077. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5078. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5079. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5080. if ( this.size !== undefined ) data.size = this.size;
  5081. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5082. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5083. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5084. if ( this.side !== FrontSide ) data.side = this.side;
  5085. if ( this.vertexColors ) data.vertexColors = true;
  5086. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5087. if ( this.transparent === true ) data.transparent = this.transparent;
  5088. data.depthFunc = this.depthFunc;
  5089. data.depthTest = this.depthTest;
  5090. data.depthWrite = this.depthWrite;
  5091. data.colorWrite = this.colorWrite;
  5092. data.stencilWrite = this.stencilWrite;
  5093. data.stencilWriteMask = this.stencilWriteMask;
  5094. data.stencilFunc = this.stencilFunc;
  5095. data.stencilRef = this.stencilRef;
  5096. data.stencilFuncMask = this.stencilFuncMask;
  5097. data.stencilFail = this.stencilFail;
  5098. data.stencilZFail = this.stencilZFail;
  5099. data.stencilZPass = this.stencilZPass;
  5100. // rotation (SpriteMaterial)
  5101. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5102. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5103. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5104. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5105. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5106. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5107. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5108. if ( this.scale !== undefined ) data.scale = this.scale;
  5109. if ( this.dithering === true ) data.dithering = true;
  5110. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5111. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5112. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5113. if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;
  5114. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5115. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5116. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5117. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5118. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5119. if ( this.visible === false ) data.visible = false;
  5120. if ( this.toneMapped === false ) data.toneMapped = false;
  5121. if ( this.fog === false ) data.fog = false;
  5122. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5123. // TODO: Copied from Object3D.toJSON
  5124. function extractFromCache( cache ) {
  5125. const values = [];
  5126. for ( const key in cache ) {
  5127. const data = cache[ key ];
  5128. delete data.metadata;
  5129. values.push( data );
  5130. }
  5131. return values;
  5132. }
  5133. if ( isRootObject ) {
  5134. const textures = extractFromCache( meta.textures );
  5135. const images = extractFromCache( meta.images );
  5136. if ( textures.length > 0 ) data.textures = textures;
  5137. if ( images.length > 0 ) data.images = images;
  5138. }
  5139. return data;
  5140. }
  5141. clone() {
  5142. return new this.constructor().copy( this );
  5143. }
  5144. copy( source ) {
  5145. this.name = source.name;
  5146. this.blending = source.blending;
  5147. this.side = source.side;
  5148. this.vertexColors = source.vertexColors;
  5149. this.opacity = source.opacity;
  5150. this.transparent = source.transparent;
  5151. this.blendSrc = source.blendSrc;
  5152. this.blendDst = source.blendDst;
  5153. this.blendEquation = source.blendEquation;
  5154. this.blendSrcAlpha = source.blendSrcAlpha;
  5155. this.blendDstAlpha = source.blendDstAlpha;
  5156. this.blendEquationAlpha = source.blendEquationAlpha;
  5157. this.depthFunc = source.depthFunc;
  5158. this.depthTest = source.depthTest;
  5159. this.depthWrite = source.depthWrite;
  5160. this.stencilWriteMask = source.stencilWriteMask;
  5161. this.stencilFunc = source.stencilFunc;
  5162. this.stencilRef = source.stencilRef;
  5163. this.stencilFuncMask = source.stencilFuncMask;
  5164. this.stencilFail = source.stencilFail;
  5165. this.stencilZFail = source.stencilZFail;
  5166. this.stencilZPass = source.stencilZPass;
  5167. this.stencilWrite = source.stencilWrite;
  5168. const srcPlanes = source.clippingPlanes;
  5169. let dstPlanes = null;
  5170. if ( srcPlanes !== null ) {
  5171. const n = srcPlanes.length;
  5172. dstPlanes = new Array( n );
  5173. for ( let i = 0; i !== n; ++ i ) {
  5174. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5175. }
  5176. }
  5177. this.clippingPlanes = dstPlanes;
  5178. this.clipIntersection = source.clipIntersection;
  5179. this.clipShadows = source.clipShadows;
  5180. this.shadowSide = source.shadowSide;
  5181. this.colorWrite = source.colorWrite;
  5182. this.precision = source.precision;
  5183. this.polygonOffset = source.polygonOffset;
  5184. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5185. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5186. this.dithering = source.dithering;
  5187. this.alphaTest = source.alphaTest;
  5188. this.alphaToCoverage = source.alphaToCoverage;
  5189. this.premultipliedAlpha = source.premultipliedAlpha;
  5190. this.forceSinglePass = source.forceSinglePass;
  5191. this.visible = source.visible;
  5192. this.toneMapped = source.toneMapped;
  5193. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5194. return this;
  5195. }
  5196. dispose() {
  5197. this.dispatchEvent( { type: 'dispose' } );
  5198. }
  5199. set needsUpdate( value ) {
  5200. if ( value === true ) this.version ++;
  5201. }
  5202. }
  5203. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5204. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5205. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5206. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5207. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5208. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5209. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5210. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5211. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5212. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5213. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5214. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5215. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5216. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5217. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5218. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5219. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5220. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5221. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5222. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5223. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5224. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5225. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5226. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5227. const _hslA = { h: 0, s: 0, l: 0 };
  5228. const _hslB = { h: 0, s: 0, l: 0 };
  5229. function hue2rgb( p, q, t ) {
  5230. if ( t < 0 ) t += 1;
  5231. if ( t > 1 ) t -= 1;
  5232. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5233. if ( t < 1 / 2 ) return q;
  5234. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5235. return p;
  5236. }
  5237. class Color {
  5238. constructor( r, g, b ) {
  5239. this.isColor = true;
  5240. this.r = 1;
  5241. this.g = 1;
  5242. this.b = 1;
  5243. if ( g === undefined && b === undefined ) {
  5244. // r is THREE.Color, hex or string
  5245. return this.set( r );
  5246. }
  5247. return this.setRGB( r, g, b );
  5248. }
  5249. set( value ) {
  5250. if ( value && value.isColor ) {
  5251. this.copy( value );
  5252. } else if ( typeof value === 'number' ) {
  5253. this.setHex( value );
  5254. } else if ( typeof value === 'string' ) {
  5255. this.setStyle( value );
  5256. }
  5257. return this;
  5258. }
  5259. setScalar( scalar ) {
  5260. this.r = scalar;
  5261. this.g = scalar;
  5262. this.b = scalar;
  5263. return this;
  5264. }
  5265. setHex( hex, colorSpace = SRGBColorSpace ) {
  5266. hex = Math.floor( hex );
  5267. this.r = ( hex >> 16 & 255 ) / 255;
  5268. this.g = ( hex >> 8 & 255 ) / 255;
  5269. this.b = ( hex & 255 ) / 255;
  5270. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5271. return this;
  5272. }
  5273. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5274. this.r = r;
  5275. this.g = g;
  5276. this.b = b;
  5277. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5278. return this;
  5279. }
  5280. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5281. // h,s,l ranges are in 0.0 - 1.0
  5282. h = euclideanModulo( h, 1 );
  5283. s = clamp( s, 0, 1 );
  5284. l = clamp( l, 0, 1 );
  5285. if ( s === 0 ) {
  5286. this.r = this.g = this.b = l;
  5287. } else {
  5288. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5289. const q = ( 2 * l ) - p;
  5290. this.r = hue2rgb( q, p, h + 1 / 3 );
  5291. this.g = hue2rgb( q, p, h );
  5292. this.b = hue2rgb( q, p, h - 1 / 3 );
  5293. }
  5294. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5295. return this;
  5296. }
  5297. setStyle( style, colorSpace = SRGBColorSpace ) {
  5298. function handleAlpha( string ) {
  5299. if ( string === undefined ) return;
  5300. if ( parseFloat( string ) < 1 ) {
  5301. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5302. }
  5303. }
  5304. let m;
  5305. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5306. // rgb / hsl
  5307. let color;
  5308. const name = m[ 1 ];
  5309. const components = m[ 2 ];
  5310. switch ( name ) {
  5311. case 'rgb':
  5312. case 'rgba':
  5313. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5314. // rgb(255,0,0) rgba(255,0,0,0.5)
  5315. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5316. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5317. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5318. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5319. handleAlpha( color[ 4 ] );
  5320. return this;
  5321. }
  5322. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5323. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5324. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5325. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5326. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5327. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5328. handleAlpha( color[ 4 ] );
  5329. return this;
  5330. }
  5331. break;
  5332. case 'hsl':
  5333. case 'hsla':
  5334. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5335. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5336. const h = parseFloat( color[ 1 ] ) / 360;
  5337. const s = parseFloat( color[ 2 ] ) / 100;
  5338. const l = parseFloat( color[ 3 ] ) / 100;
  5339. handleAlpha( color[ 4 ] );
  5340. return this.setHSL( h, s, l, colorSpace );
  5341. }
  5342. break;
  5343. default:
  5344. console.warn( 'THREE.Color: Unknown color model ' + style );
  5345. }
  5346. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5347. // hex color
  5348. const hex = m[ 1 ];
  5349. const size = hex.length;
  5350. if ( size === 3 ) {
  5351. // #ff0
  5352. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5353. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5354. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5355. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5356. return this;
  5357. } else if ( size === 6 ) {
  5358. // #ff0000
  5359. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5360. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5361. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5362. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5363. return this;
  5364. } else {
  5365. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5366. }
  5367. } else if ( style && style.length > 0 ) {
  5368. return this.setColorName( style, colorSpace );
  5369. }
  5370. return this;
  5371. }
  5372. setColorName( style, colorSpace = SRGBColorSpace ) {
  5373. // color keywords
  5374. const hex = _colorKeywords[ style.toLowerCase() ];
  5375. if ( hex !== undefined ) {
  5376. // red
  5377. this.setHex( hex, colorSpace );
  5378. } else {
  5379. // unknown color
  5380. console.warn( 'THREE.Color: Unknown color ' + style );
  5381. }
  5382. return this;
  5383. }
  5384. clone() {
  5385. return new this.constructor( this.r, this.g, this.b );
  5386. }
  5387. copy( color ) {
  5388. this.r = color.r;
  5389. this.g = color.g;
  5390. this.b = color.b;
  5391. return this;
  5392. }
  5393. copySRGBToLinear( color ) {
  5394. this.r = SRGBToLinear( color.r );
  5395. this.g = SRGBToLinear( color.g );
  5396. this.b = SRGBToLinear( color.b );
  5397. return this;
  5398. }
  5399. copyLinearToSRGB( color ) {
  5400. this.r = LinearToSRGB( color.r );
  5401. this.g = LinearToSRGB( color.g );
  5402. this.b = LinearToSRGB( color.b );
  5403. return this;
  5404. }
  5405. convertSRGBToLinear() {
  5406. this.copySRGBToLinear( this );
  5407. return this;
  5408. }
  5409. convertLinearToSRGB() {
  5410. this.copyLinearToSRGB( this );
  5411. return this;
  5412. }
  5413. getHex( colorSpace = SRGBColorSpace ) {
  5414. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5415. return clamp( _color.r * 255, 0, 255 ) << 16 ^ clamp( _color.g * 255, 0, 255 ) << 8 ^ clamp( _color.b * 255, 0, 255 ) << 0;
  5416. }
  5417. getHexString( colorSpace = SRGBColorSpace ) {
  5418. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5419. }
  5420. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5421. // h,s,l ranges are in 0.0 - 1.0
  5422. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5423. const r = _color.r, g = _color.g, b = _color.b;
  5424. const max = Math.max( r, g, b );
  5425. const min = Math.min( r, g, b );
  5426. let hue, saturation;
  5427. const lightness = ( min + max ) / 2.0;
  5428. if ( min === max ) {
  5429. hue = 0;
  5430. saturation = 0;
  5431. } else {
  5432. const delta = max - min;
  5433. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5434. switch ( max ) {
  5435. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5436. case g: hue = ( b - r ) / delta + 2; break;
  5437. case b: hue = ( r - g ) / delta + 4; break;
  5438. }
  5439. hue /= 6;
  5440. }
  5441. target.h = hue;
  5442. target.s = saturation;
  5443. target.l = lightness;
  5444. return target;
  5445. }
  5446. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5447. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5448. target.r = _color.r;
  5449. target.g = _color.g;
  5450. target.b = _color.b;
  5451. return target;
  5452. }
  5453. getStyle( colorSpace = SRGBColorSpace ) {
  5454. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5455. const r = _color.r, g = _color.g, b = _color.b;
  5456. if ( colorSpace !== SRGBColorSpace ) {
  5457. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5458. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5459. }
  5460. return `rgb(${( r * 255 ) | 0},${( g * 255 ) | 0},${( b * 255 ) | 0})`;
  5461. }
  5462. offsetHSL( h, s, l ) {
  5463. this.getHSL( _hslA );
  5464. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5465. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5466. return this;
  5467. }
  5468. add( color ) {
  5469. this.r += color.r;
  5470. this.g += color.g;
  5471. this.b += color.b;
  5472. return this;
  5473. }
  5474. addColors( color1, color2 ) {
  5475. this.r = color1.r + color2.r;
  5476. this.g = color1.g + color2.g;
  5477. this.b = color1.b + color2.b;
  5478. return this;
  5479. }
  5480. addScalar( s ) {
  5481. this.r += s;
  5482. this.g += s;
  5483. this.b += s;
  5484. return this;
  5485. }
  5486. sub( color ) {
  5487. this.r = Math.max( 0, this.r - color.r );
  5488. this.g = Math.max( 0, this.g - color.g );
  5489. this.b = Math.max( 0, this.b - color.b );
  5490. return this;
  5491. }
  5492. multiply( color ) {
  5493. this.r *= color.r;
  5494. this.g *= color.g;
  5495. this.b *= color.b;
  5496. return this;
  5497. }
  5498. multiplyScalar( s ) {
  5499. this.r *= s;
  5500. this.g *= s;
  5501. this.b *= s;
  5502. return this;
  5503. }
  5504. lerp( color, alpha ) {
  5505. this.r += ( color.r - this.r ) * alpha;
  5506. this.g += ( color.g - this.g ) * alpha;
  5507. this.b += ( color.b - this.b ) * alpha;
  5508. return this;
  5509. }
  5510. lerpColors( color1, color2, alpha ) {
  5511. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5512. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5513. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5514. return this;
  5515. }
  5516. lerpHSL( color, alpha ) {
  5517. this.getHSL( _hslA );
  5518. color.getHSL( _hslB );
  5519. const h = lerp( _hslA.h, _hslB.h, alpha );
  5520. const s = lerp( _hslA.s, _hslB.s, alpha );
  5521. const l = lerp( _hslA.l, _hslB.l, alpha );
  5522. this.setHSL( h, s, l );
  5523. return this;
  5524. }
  5525. equals( c ) {
  5526. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5527. }
  5528. fromArray( array, offset = 0 ) {
  5529. this.r = array[ offset ];
  5530. this.g = array[ offset + 1 ];
  5531. this.b = array[ offset + 2 ];
  5532. return this;
  5533. }
  5534. toArray( array = [], offset = 0 ) {
  5535. array[ offset ] = this.r;
  5536. array[ offset + 1 ] = this.g;
  5537. array[ offset + 2 ] = this.b;
  5538. return array;
  5539. }
  5540. fromBufferAttribute( attribute, index ) {
  5541. this.r = attribute.getX( index );
  5542. this.g = attribute.getY( index );
  5543. this.b = attribute.getZ( index );
  5544. return this;
  5545. }
  5546. toJSON() {
  5547. return this.getHex();
  5548. }
  5549. *[ Symbol.iterator ]() {
  5550. yield this.r;
  5551. yield this.g;
  5552. yield this.b;
  5553. }
  5554. }
  5555. const _color = /*@__PURE__*/ new Color();
  5556. Color.NAMES = _colorKeywords;
  5557. class MeshBasicMaterial extends Material {
  5558. constructor( parameters ) {
  5559. super();
  5560. this.isMeshBasicMaterial = true;
  5561. this.type = 'MeshBasicMaterial';
  5562. this.color = new Color( 0xffffff ); // emissive
  5563. this.map = null;
  5564. this.lightMap = null;
  5565. this.lightMapIntensity = 1.0;
  5566. this.aoMap = null;
  5567. this.aoMapIntensity = 1.0;
  5568. this.specularMap = null;
  5569. this.alphaMap = null;
  5570. this.envMap = null;
  5571. this.combine = MultiplyOperation;
  5572. this.reflectivity = 1;
  5573. this.refractionRatio = 0.98;
  5574. this.wireframe = false;
  5575. this.wireframeLinewidth = 1;
  5576. this.wireframeLinecap = 'round';
  5577. this.wireframeLinejoin = 'round';
  5578. this.fog = true;
  5579. this.setValues( parameters );
  5580. }
  5581. copy( source ) {
  5582. super.copy( source );
  5583. this.color.copy( source.color );
  5584. this.map = source.map;
  5585. this.lightMap = source.lightMap;
  5586. this.lightMapIntensity = source.lightMapIntensity;
  5587. this.aoMap = source.aoMap;
  5588. this.aoMapIntensity = source.aoMapIntensity;
  5589. this.specularMap = source.specularMap;
  5590. this.alphaMap = source.alphaMap;
  5591. this.envMap = source.envMap;
  5592. this.combine = source.combine;
  5593. this.reflectivity = source.reflectivity;
  5594. this.refractionRatio = source.refractionRatio;
  5595. this.wireframe = source.wireframe;
  5596. this.wireframeLinewidth = source.wireframeLinewidth;
  5597. this.wireframeLinecap = source.wireframeLinecap;
  5598. this.wireframeLinejoin = source.wireframeLinejoin;
  5599. this.fog = source.fog;
  5600. return this;
  5601. }
  5602. }
  5603. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5604. const _tables = /*@__PURE__*/ _generateTables();
  5605. function _generateTables() {
  5606. // float32 to float16 helpers
  5607. const buffer = new ArrayBuffer( 4 );
  5608. const floatView = new Float32Array( buffer );
  5609. const uint32View = new Uint32Array( buffer );
  5610. const baseTable = new Uint32Array( 512 );
  5611. const shiftTable = new Uint32Array( 512 );
  5612. for ( let i = 0; i < 256; ++ i ) {
  5613. const e = i - 127;
  5614. // very small number (0, -0)
  5615. if ( e < - 27 ) {
  5616. baseTable[ i ] = 0x0000;
  5617. baseTable[ i | 0x100 ] = 0x8000;
  5618. shiftTable[ i ] = 24;
  5619. shiftTable[ i | 0x100 ] = 24;
  5620. // small number (denorm)
  5621. } else if ( e < - 14 ) {
  5622. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5623. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5624. shiftTable[ i ] = - e - 1;
  5625. shiftTable[ i | 0x100 ] = - e - 1;
  5626. // normal number
  5627. } else if ( e <= 15 ) {
  5628. baseTable[ i ] = ( e + 15 ) << 10;
  5629. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5630. shiftTable[ i ] = 13;
  5631. shiftTable[ i | 0x100 ] = 13;
  5632. // large number (Infinity, -Infinity)
  5633. } else if ( e < 128 ) {
  5634. baseTable[ i ] = 0x7c00;
  5635. baseTable[ i | 0x100 ] = 0xfc00;
  5636. shiftTable[ i ] = 24;
  5637. shiftTable[ i | 0x100 ] = 24;
  5638. // stay (NaN, Infinity, -Infinity)
  5639. } else {
  5640. baseTable[ i ] = 0x7c00;
  5641. baseTable[ i | 0x100 ] = 0xfc00;
  5642. shiftTable[ i ] = 13;
  5643. shiftTable[ i | 0x100 ] = 13;
  5644. }
  5645. }
  5646. // float16 to float32 helpers
  5647. const mantissaTable = new Uint32Array( 2048 );
  5648. const exponentTable = new Uint32Array( 64 );
  5649. const offsetTable = new Uint32Array( 64 );
  5650. for ( let i = 1; i < 1024; ++ i ) {
  5651. let m = i << 13; // zero pad mantissa bits
  5652. let e = 0; // zero exponent
  5653. // normalized
  5654. while ( ( m & 0x00800000 ) === 0 ) {
  5655. m <<= 1;
  5656. e -= 0x00800000; // decrement exponent
  5657. }
  5658. m &= ~ 0x00800000; // clear leading 1 bit
  5659. e += 0x38800000; // adjust bias
  5660. mantissaTable[ i ] = m | e;
  5661. }
  5662. for ( let i = 1024; i < 2048; ++ i ) {
  5663. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5664. }
  5665. for ( let i = 1; i < 31; ++ i ) {
  5666. exponentTable[ i ] = i << 23;
  5667. }
  5668. exponentTable[ 31 ] = 0x47800000;
  5669. exponentTable[ 32 ] = 0x80000000;
  5670. for ( let i = 33; i < 63; ++ i ) {
  5671. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5672. }
  5673. exponentTable[ 63 ] = 0xc7800000;
  5674. for ( let i = 1; i < 64; ++ i ) {
  5675. if ( i !== 32 ) {
  5676. offsetTable[ i ] = 1024;
  5677. }
  5678. }
  5679. return {
  5680. floatView: floatView,
  5681. uint32View: uint32View,
  5682. baseTable: baseTable,
  5683. shiftTable: shiftTable,
  5684. mantissaTable: mantissaTable,
  5685. exponentTable: exponentTable,
  5686. offsetTable: offsetTable
  5687. };
  5688. }
  5689. // float32 to float16
  5690. function toHalfFloat( val ) {
  5691. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5692. val = clamp( val, - 65504, 65504 );
  5693. _tables.floatView[ 0 ] = val;
  5694. const f = _tables.uint32View[ 0 ];
  5695. const e = ( f >> 23 ) & 0x1ff;
  5696. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5697. }
  5698. // float16 to float32
  5699. function fromHalfFloat( val ) {
  5700. const m = val >> 10;
  5701. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5702. return _tables.floatView[ 0 ];
  5703. }
  5704. const DataUtils = {
  5705. toHalfFloat: toHalfFloat,
  5706. fromHalfFloat: fromHalfFloat,
  5707. };
  5708. const _vector$8 = /*@__PURE__*/ new Vector3();
  5709. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5710. class BufferAttribute {
  5711. constructor( array, itemSize, normalized = false ) {
  5712. if ( Array.isArray( array ) ) {
  5713. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5714. }
  5715. this.isBufferAttribute = true;
  5716. this.name = '';
  5717. this.array = array;
  5718. this.itemSize = itemSize;
  5719. this.count = array !== undefined ? array.length / itemSize : 0;
  5720. this.normalized = normalized;
  5721. this.usage = StaticDrawUsage;
  5722. this.updateRange = { offset: 0, count: - 1 };
  5723. this.version = 0;
  5724. }
  5725. onUploadCallback() {}
  5726. set needsUpdate( value ) {
  5727. if ( value === true ) this.version ++;
  5728. }
  5729. setUsage( value ) {
  5730. this.usage = value;
  5731. return this;
  5732. }
  5733. copy( source ) {
  5734. this.name = source.name;
  5735. this.array = new source.array.constructor( source.array );
  5736. this.itemSize = source.itemSize;
  5737. this.count = source.count;
  5738. this.normalized = source.normalized;
  5739. this.usage = source.usage;
  5740. return this;
  5741. }
  5742. copyAt( index1, attribute, index2 ) {
  5743. index1 *= this.itemSize;
  5744. index2 *= attribute.itemSize;
  5745. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5746. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5747. }
  5748. return this;
  5749. }
  5750. copyArray( array ) {
  5751. this.array.set( array );
  5752. return this;
  5753. }
  5754. applyMatrix3( m ) {
  5755. if ( this.itemSize === 2 ) {
  5756. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5757. _vector2$1.fromBufferAttribute( this, i );
  5758. _vector2$1.applyMatrix3( m );
  5759. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5760. }
  5761. } else if ( this.itemSize === 3 ) {
  5762. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5763. _vector$8.fromBufferAttribute( this, i );
  5764. _vector$8.applyMatrix3( m );
  5765. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5766. }
  5767. }
  5768. return this;
  5769. }
  5770. applyMatrix4( m ) {
  5771. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5772. _vector$8.fromBufferAttribute( this, i );
  5773. _vector$8.applyMatrix4( m );
  5774. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5775. }
  5776. return this;
  5777. }
  5778. applyNormalMatrix( m ) {
  5779. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5780. _vector$8.fromBufferAttribute( this, i );
  5781. _vector$8.applyNormalMatrix( m );
  5782. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5783. }
  5784. return this;
  5785. }
  5786. transformDirection( m ) {
  5787. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5788. _vector$8.fromBufferAttribute( this, i );
  5789. _vector$8.transformDirection( m );
  5790. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5791. }
  5792. return this;
  5793. }
  5794. set( value, offset = 0 ) {
  5795. // Matching BufferAttribute constructor, do not normalize the array.
  5796. this.array.set( value, offset );
  5797. return this;
  5798. }
  5799. getX( index ) {
  5800. let x = this.array[ index * this.itemSize ];
  5801. if ( this.normalized ) x = denormalize( x, this.array );
  5802. return x;
  5803. }
  5804. setX( index, x ) {
  5805. if ( this.normalized ) x = normalize( x, this.array );
  5806. this.array[ index * this.itemSize ] = x;
  5807. return this;
  5808. }
  5809. getY( index ) {
  5810. let y = this.array[ index * this.itemSize + 1 ];
  5811. if ( this.normalized ) y = denormalize( y, this.array );
  5812. return y;
  5813. }
  5814. setY( index, y ) {
  5815. if ( this.normalized ) y = normalize( y, this.array );
  5816. this.array[ index * this.itemSize + 1 ] = y;
  5817. return this;
  5818. }
  5819. getZ( index ) {
  5820. let z = this.array[ index * this.itemSize + 2 ];
  5821. if ( this.normalized ) z = denormalize( z, this.array );
  5822. return z;
  5823. }
  5824. setZ( index, z ) {
  5825. if ( this.normalized ) z = normalize( z, this.array );
  5826. this.array[ index * this.itemSize + 2 ] = z;
  5827. return this;
  5828. }
  5829. getW( index ) {
  5830. let w = this.array[ index * this.itemSize + 3 ];
  5831. if ( this.normalized ) w = denormalize( w, this.array );
  5832. return w;
  5833. }
  5834. setW( index, w ) {
  5835. if ( this.normalized ) w = normalize( w, this.array );
  5836. this.array[ index * this.itemSize + 3 ] = w;
  5837. return this;
  5838. }
  5839. setXY( index, x, y ) {
  5840. index *= this.itemSize;
  5841. if ( this.normalized ) {
  5842. x = normalize( x, this.array );
  5843. y = normalize( y, this.array );
  5844. }
  5845. this.array[ index + 0 ] = x;
  5846. this.array[ index + 1 ] = y;
  5847. return this;
  5848. }
  5849. setXYZ( index, x, y, z ) {
  5850. index *= this.itemSize;
  5851. if ( this.normalized ) {
  5852. x = normalize( x, this.array );
  5853. y = normalize( y, this.array );
  5854. z = normalize( z, this.array );
  5855. }
  5856. this.array[ index + 0 ] = x;
  5857. this.array[ index + 1 ] = y;
  5858. this.array[ index + 2 ] = z;
  5859. return this;
  5860. }
  5861. setXYZW( index, x, y, z, w ) {
  5862. index *= this.itemSize;
  5863. if ( this.normalized ) {
  5864. x = normalize( x, this.array );
  5865. y = normalize( y, this.array );
  5866. z = normalize( z, this.array );
  5867. w = normalize( w, this.array );
  5868. }
  5869. this.array[ index + 0 ] = x;
  5870. this.array[ index + 1 ] = y;
  5871. this.array[ index + 2 ] = z;
  5872. this.array[ index + 3 ] = w;
  5873. return this;
  5874. }
  5875. onUpload( callback ) {
  5876. this.onUploadCallback = callback;
  5877. return this;
  5878. }
  5879. clone() {
  5880. return new this.constructor( this.array, this.itemSize ).copy( this );
  5881. }
  5882. toJSON() {
  5883. const data = {
  5884. itemSize: this.itemSize,
  5885. type: this.array.constructor.name,
  5886. array: Array.from( this.array ),
  5887. normalized: this.normalized
  5888. };
  5889. if ( this.name !== '' ) data.name = this.name;
  5890. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5891. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5892. return data;
  5893. }
  5894. // @deprecated
  5895. copyColorsArray() {
  5896. console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );
  5897. }
  5898. copyVector2sArray() {
  5899. console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );
  5900. }
  5901. copyVector3sArray() {
  5902. console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );
  5903. }
  5904. copyVector4sArray() {
  5905. console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );
  5906. }
  5907. }
  5908. //
  5909. class Int8BufferAttribute extends BufferAttribute {
  5910. constructor( array, itemSize, normalized ) {
  5911. super( new Int8Array( array ), itemSize, normalized );
  5912. }
  5913. }
  5914. class Uint8BufferAttribute extends BufferAttribute {
  5915. constructor( array, itemSize, normalized ) {
  5916. super( new Uint8Array( array ), itemSize, normalized );
  5917. }
  5918. }
  5919. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5920. constructor( array, itemSize, normalized ) {
  5921. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5922. }
  5923. }
  5924. class Int16BufferAttribute extends BufferAttribute {
  5925. constructor( array, itemSize, normalized ) {
  5926. super( new Int16Array( array ), itemSize, normalized );
  5927. }
  5928. }
  5929. class Uint16BufferAttribute extends BufferAttribute {
  5930. constructor( array, itemSize, normalized ) {
  5931. super( new Uint16Array( array ), itemSize, normalized );
  5932. }
  5933. }
  5934. class Int32BufferAttribute extends BufferAttribute {
  5935. constructor( array, itemSize, normalized ) {
  5936. super( new Int32Array( array ), itemSize, normalized );
  5937. }
  5938. }
  5939. class Uint32BufferAttribute extends BufferAttribute {
  5940. constructor( array, itemSize, normalized ) {
  5941. super( new Uint32Array( array ), itemSize, normalized );
  5942. }
  5943. }
  5944. class Float16BufferAttribute extends BufferAttribute {
  5945. constructor( array, itemSize, normalized ) {
  5946. super( new Uint16Array( array ), itemSize, normalized );
  5947. this.isFloat16BufferAttribute = true;
  5948. }
  5949. getX( index ) {
  5950. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  5951. if ( this.normalized ) x = denormalize( x, this.array );
  5952. return x;
  5953. }
  5954. setX( index, x ) {
  5955. if ( this.normalized ) x = normalize( x, this.array );
  5956. this.array[ index * this.itemSize ] = toHalfFloat( x );
  5957. return this;
  5958. }
  5959. getY( index ) {
  5960. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  5961. if ( this.normalized ) y = denormalize( y, this.array );
  5962. return y;
  5963. }
  5964. setY( index, y ) {
  5965. if ( this.normalized ) y = normalize( y, this.array );
  5966. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  5967. return this;
  5968. }
  5969. getZ( index ) {
  5970. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  5971. if ( this.normalized ) z = denormalize( z, this.array );
  5972. return z;
  5973. }
  5974. setZ( index, z ) {
  5975. if ( this.normalized ) z = normalize( z, this.array );
  5976. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  5977. return this;
  5978. }
  5979. getW( index ) {
  5980. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  5981. if ( this.normalized ) w = denormalize( w, this.array );
  5982. return w;
  5983. }
  5984. setW( index, w ) {
  5985. if ( this.normalized ) w = normalize( w, this.array );
  5986. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  5987. return this;
  5988. }
  5989. setXY( index, x, y ) {
  5990. index *= this.itemSize;
  5991. if ( this.normalized ) {
  5992. x = normalize( x, this.array );
  5993. y = normalize( y, this.array );
  5994. }
  5995. this.array[ index + 0 ] = toHalfFloat( x );
  5996. this.array[ index + 1 ] = toHalfFloat( y );
  5997. return this;
  5998. }
  5999. setXYZ( index, x, y, z ) {
  6000. index *= this.itemSize;
  6001. if ( this.normalized ) {
  6002. x = normalize( x, this.array );
  6003. y = normalize( y, this.array );
  6004. z = normalize( z, this.array );
  6005. }
  6006. this.array[ index + 0 ] = toHalfFloat( x );
  6007. this.array[ index + 1 ] = toHalfFloat( y );
  6008. this.array[ index + 2 ] = toHalfFloat( z );
  6009. return this;
  6010. }
  6011. setXYZW( index, x, y, z, w ) {
  6012. index *= this.itemSize;
  6013. if ( this.normalized ) {
  6014. x = normalize( x, this.array );
  6015. y = normalize( y, this.array );
  6016. z = normalize( z, this.array );
  6017. w = normalize( w, this.array );
  6018. }
  6019. this.array[ index + 0 ] = toHalfFloat( x );
  6020. this.array[ index + 1 ] = toHalfFloat( y );
  6021. this.array[ index + 2 ] = toHalfFloat( z );
  6022. this.array[ index + 3 ] = toHalfFloat( w );
  6023. return this;
  6024. }
  6025. }
  6026. class Float32BufferAttribute extends BufferAttribute {
  6027. constructor( array, itemSize, normalized ) {
  6028. super( new Float32Array( array ), itemSize, normalized );
  6029. }
  6030. }
  6031. class Float64BufferAttribute extends BufferAttribute {
  6032. constructor( array, itemSize, normalized ) {
  6033. super( new Float64Array( array ), itemSize, normalized );
  6034. }
  6035. }
  6036. let _id$1 = 0;
  6037. const _m1 = /*@__PURE__*/ new Matrix4();
  6038. const _obj = /*@__PURE__*/ new Object3D();
  6039. const _offset = /*@__PURE__*/ new Vector3();
  6040. const _box$1 = /*@__PURE__*/ new Box3();
  6041. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6042. const _vector$7 = /*@__PURE__*/ new Vector3();
  6043. class BufferGeometry extends EventDispatcher {
  6044. constructor() {
  6045. super();
  6046. this.isBufferGeometry = true;
  6047. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  6048. this.uuid = generateUUID();
  6049. this.name = '';
  6050. this.type = 'BufferGeometry';
  6051. this.index = null;
  6052. this.attributes = {};
  6053. this.morphAttributes = {};
  6054. this.morphTargetsRelative = false;
  6055. this.groups = [];
  6056. this.boundingBox = null;
  6057. this.boundingSphere = null;
  6058. this.drawRange = { start: 0, count: Infinity };
  6059. this.userData = {};
  6060. }
  6061. getIndex() {
  6062. return this.index;
  6063. }
  6064. setIndex( index ) {
  6065. if ( Array.isArray( index ) ) {
  6066. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6067. } else {
  6068. this.index = index;
  6069. }
  6070. return this;
  6071. }
  6072. getAttribute( name ) {
  6073. return this.attributes[ name ];
  6074. }
  6075. setAttribute( name, attribute ) {
  6076. this.attributes[ name ] = attribute;
  6077. return this;
  6078. }
  6079. deleteAttribute( name ) {
  6080. delete this.attributes[ name ];
  6081. return this;
  6082. }
  6083. hasAttribute( name ) {
  6084. return this.attributes[ name ] !== undefined;
  6085. }
  6086. addGroup( start, count, materialIndex = 0 ) {
  6087. this.groups.push( {
  6088. start: start,
  6089. count: count,
  6090. materialIndex: materialIndex
  6091. } );
  6092. }
  6093. clearGroups() {
  6094. this.groups = [];
  6095. }
  6096. setDrawRange( start, count ) {
  6097. this.drawRange.start = start;
  6098. this.drawRange.count = count;
  6099. }
  6100. applyMatrix4( matrix ) {
  6101. const position = this.attributes.position;
  6102. if ( position !== undefined ) {
  6103. position.applyMatrix4( matrix );
  6104. position.needsUpdate = true;
  6105. }
  6106. const normal = this.attributes.normal;
  6107. if ( normal !== undefined ) {
  6108. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6109. normal.applyNormalMatrix( normalMatrix );
  6110. normal.needsUpdate = true;
  6111. }
  6112. const tangent = this.attributes.tangent;
  6113. if ( tangent !== undefined ) {
  6114. tangent.transformDirection( matrix );
  6115. tangent.needsUpdate = true;
  6116. }
  6117. if ( this.boundingBox !== null ) {
  6118. this.computeBoundingBox();
  6119. }
  6120. if ( this.boundingSphere !== null ) {
  6121. this.computeBoundingSphere();
  6122. }
  6123. return this;
  6124. }
  6125. applyQuaternion( q ) {
  6126. _m1.makeRotationFromQuaternion( q );
  6127. this.applyMatrix4( _m1 );
  6128. return this;
  6129. }
  6130. rotateX( angle ) {
  6131. // rotate geometry around world x-axis
  6132. _m1.makeRotationX( angle );
  6133. this.applyMatrix4( _m1 );
  6134. return this;
  6135. }
  6136. rotateY( angle ) {
  6137. // rotate geometry around world y-axis
  6138. _m1.makeRotationY( angle );
  6139. this.applyMatrix4( _m1 );
  6140. return this;
  6141. }
  6142. rotateZ( angle ) {
  6143. // rotate geometry around world z-axis
  6144. _m1.makeRotationZ( angle );
  6145. this.applyMatrix4( _m1 );
  6146. return this;
  6147. }
  6148. translate( x, y, z ) {
  6149. // translate geometry
  6150. _m1.makeTranslation( x, y, z );
  6151. this.applyMatrix4( _m1 );
  6152. return this;
  6153. }
  6154. scale( x, y, z ) {
  6155. // scale geometry
  6156. _m1.makeScale( x, y, z );
  6157. this.applyMatrix4( _m1 );
  6158. return this;
  6159. }
  6160. lookAt( vector ) {
  6161. _obj.lookAt( vector );
  6162. _obj.updateMatrix();
  6163. this.applyMatrix4( _obj.matrix );
  6164. return this;
  6165. }
  6166. center() {
  6167. this.computeBoundingBox();
  6168. this.boundingBox.getCenter( _offset ).negate();
  6169. this.translate( _offset.x, _offset.y, _offset.z );
  6170. return this;
  6171. }
  6172. setFromPoints( points ) {
  6173. const position = [];
  6174. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6175. const point = points[ i ];
  6176. position.push( point.x, point.y, point.z || 0 );
  6177. }
  6178. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6179. return this;
  6180. }
  6181. computeBoundingBox() {
  6182. if ( this.boundingBox === null ) {
  6183. this.boundingBox = new Box3();
  6184. }
  6185. const position = this.attributes.position;
  6186. const morphAttributesPosition = this.morphAttributes.position;
  6187. if ( position && position.isGLBufferAttribute ) {
  6188. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6189. this.boundingBox.set(
  6190. new Vector3( - Infinity, - Infinity, - Infinity ),
  6191. new Vector3( + Infinity, + Infinity, + Infinity )
  6192. );
  6193. return;
  6194. }
  6195. if ( position !== undefined ) {
  6196. this.boundingBox.setFromBufferAttribute( position );
  6197. // process morph attributes if present
  6198. if ( morphAttributesPosition ) {
  6199. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6200. const morphAttribute = morphAttributesPosition[ i ];
  6201. _box$1.setFromBufferAttribute( morphAttribute );
  6202. if ( this.morphTargetsRelative ) {
  6203. _vector$7.addVectors( this.boundingBox.min, _box$1.min );
  6204. this.boundingBox.expandByPoint( _vector$7 );
  6205. _vector$7.addVectors( this.boundingBox.max, _box$1.max );
  6206. this.boundingBox.expandByPoint( _vector$7 );
  6207. } else {
  6208. this.boundingBox.expandByPoint( _box$1.min );
  6209. this.boundingBox.expandByPoint( _box$1.max );
  6210. }
  6211. }
  6212. }
  6213. } else {
  6214. this.boundingBox.makeEmpty();
  6215. }
  6216. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6217. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6218. }
  6219. }
  6220. computeBoundingSphere() {
  6221. if ( this.boundingSphere === null ) {
  6222. this.boundingSphere = new Sphere();
  6223. }
  6224. const position = this.attributes.position;
  6225. const morphAttributesPosition = this.morphAttributes.position;
  6226. if ( position && position.isGLBufferAttribute ) {
  6227. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6228. this.boundingSphere.set( new Vector3(), Infinity );
  6229. return;
  6230. }
  6231. if ( position ) {
  6232. // first, find the center of the bounding sphere
  6233. const center = this.boundingSphere.center;
  6234. _box$1.setFromBufferAttribute( position );
  6235. // process morph attributes if present
  6236. if ( morphAttributesPosition ) {
  6237. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6238. const morphAttribute = morphAttributesPosition[ i ];
  6239. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6240. if ( this.morphTargetsRelative ) {
  6241. _vector$7.addVectors( _box$1.min, _boxMorphTargets.min );
  6242. _box$1.expandByPoint( _vector$7 );
  6243. _vector$7.addVectors( _box$1.max, _boxMorphTargets.max );
  6244. _box$1.expandByPoint( _vector$7 );
  6245. } else {
  6246. _box$1.expandByPoint( _boxMorphTargets.min );
  6247. _box$1.expandByPoint( _boxMorphTargets.max );
  6248. }
  6249. }
  6250. }
  6251. _box$1.getCenter( center );
  6252. // second, try to find a boundingSphere with a radius smaller than the
  6253. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6254. let maxRadiusSq = 0;
  6255. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6256. _vector$7.fromBufferAttribute( position, i );
  6257. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6258. }
  6259. // process morph attributes if present
  6260. if ( morphAttributesPosition ) {
  6261. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6262. const morphAttribute = morphAttributesPosition[ i ];
  6263. const morphTargetsRelative = this.morphTargetsRelative;
  6264. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6265. _vector$7.fromBufferAttribute( morphAttribute, j );
  6266. if ( morphTargetsRelative ) {
  6267. _offset.fromBufferAttribute( position, j );
  6268. _vector$7.add( _offset );
  6269. }
  6270. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6271. }
  6272. }
  6273. }
  6274. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6275. if ( isNaN( this.boundingSphere.radius ) ) {
  6276. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6277. }
  6278. }
  6279. }
  6280. computeTangents() {
  6281. const index = this.index;
  6282. const attributes = this.attributes;
  6283. // based on http://www.terathon.com/code/tangent.html
  6284. // (per vertex tangents)
  6285. if ( index === null ||
  6286. attributes.position === undefined ||
  6287. attributes.normal === undefined ||
  6288. attributes.uv === undefined ) {
  6289. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6290. return;
  6291. }
  6292. const indices = index.array;
  6293. const positions = attributes.position.array;
  6294. const normals = attributes.normal.array;
  6295. const uvs = attributes.uv.array;
  6296. const nVertices = positions.length / 3;
  6297. if ( this.hasAttribute( 'tangent' ) === false ) {
  6298. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6299. }
  6300. const tangents = this.getAttribute( 'tangent' ).array;
  6301. const tan1 = [], tan2 = [];
  6302. for ( let i = 0; i < nVertices; i ++ ) {
  6303. tan1[ i ] = new Vector3();
  6304. tan2[ i ] = new Vector3();
  6305. }
  6306. const vA = new Vector3(),
  6307. vB = new Vector3(),
  6308. vC = new Vector3(),
  6309. uvA = new Vector2(),
  6310. uvB = new Vector2(),
  6311. uvC = new Vector2(),
  6312. sdir = new Vector3(),
  6313. tdir = new Vector3();
  6314. function handleTriangle( a, b, c ) {
  6315. vA.fromArray( positions, a * 3 );
  6316. vB.fromArray( positions, b * 3 );
  6317. vC.fromArray( positions, c * 3 );
  6318. uvA.fromArray( uvs, a * 2 );
  6319. uvB.fromArray( uvs, b * 2 );
  6320. uvC.fromArray( uvs, c * 2 );
  6321. vB.sub( vA );
  6322. vC.sub( vA );
  6323. uvB.sub( uvA );
  6324. uvC.sub( uvA );
  6325. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6326. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6327. if ( ! isFinite( r ) ) return;
  6328. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6329. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6330. tan1[ a ].add( sdir );
  6331. tan1[ b ].add( sdir );
  6332. tan1[ c ].add( sdir );
  6333. tan2[ a ].add( tdir );
  6334. tan2[ b ].add( tdir );
  6335. tan2[ c ].add( tdir );
  6336. }
  6337. let groups = this.groups;
  6338. if ( groups.length === 0 ) {
  6339. groups = [ {
  6340. start: 0,
  6341. count: indices.length
  6342. } ];
  6343. }
  6344. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6345. const group = groups[ i ];
  6346. const start = group.start;
  6347. const count = group.count;
  6348. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6349. handleTriangle(
  6350. indices[ j + 0 ],
  6351. indices[ j + 1 ],
  6352. indices[ j + 2 ]
  6353. );
  6354. }
  6355. }
  6356. const tmp = new Vector3(), tmp2 = new Vector3();
  6357. const n = new Vector3(), n2 = new Vector3();
  6358. function handleVertex( v ) {
  6359. n.fromArray( normals, v * 3 );
  6360. n2.copy( n );
  6361. const t = tan1[ v ];
  6362. // Gram-Schmidt orthogonalize
  6363. tmp.copy( t );
  6364. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6365. // Calculate handedness
  6366. tmp2.crossVectors( n2, t );
  6367. const test = tmp2.dot( tan2[ v ] );
  6368. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6369. tangents[ v * 4 ] = tmp.x;
  6370. tangents[ v * 4 + 1 ] = tmp.y;
  6371. tangents[ v * 4 + 2 ] = tmp.z;
  6372. tangents[ v * 4 + 3 ] = w;
  6373. }
  6374. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6375. const group = groups[ i ];
  6376. const start = group.start;
  6377. const count = group.count;
  6378. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6379. handleVertex( indices[ j + 0 ] );
  6380. handleVertex( indices[ j + 1 ] );
  6381. handleVertex( indices[ j + 2 ] );
  6382. }
  6383. }
  6384. }
  6385. computeVertexNormals() {
  6386. const index = this.index;
  6387. const positionAttribute = this.getAttribute( 'position' );
  6388. if ( positionAttribute !== undefined ) {
  6389. let normalAttribute = this.getAttribute( 'normal' );
  6390. if ( normalAttribute === undefined ) {
  6391. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6392. this.setAttribute( 'normal', normalAttribute );
  6393. } else {
  6394. // reset existing normals to zero
  6395. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6396. normalAttribute.setXYZ( i, 0, 0, 0 );
  6397. }
  6398. }
  6399. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6400. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6401. const cb = new Vector3(), ab = new Vector3();
  6402. // indexed elements
  6403. if ( index ) {
  6404. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6405. const vA = index.getX( i + 0 );
  6406. const vB = index.getX( i + 1 );
  6407. const vC = index.getX( i + 2 );
  6408. pA.fromBufferAttribute( positionAttribute, vA );
  6409. pB.fromBufferAttribute( positionAttribute, vB );
  6410. pC.fromBufferAttribute( positionAttribute, vC );
  6411. cb.subVectors( pC, pB );
  6412. ab.subVectors( pA, pB );
  6413. cb.cross( ab );
  6414. nA.fromBufferAttribute( normalAttribute, vA );
  6415. nB.fromBufferAttribute( normalAttribute, vB );
  6416. nC.fromBufferAttribute( normalAttribute, vC );
  6417. nA.add( cb );
  6418. nB.add( cb );
  6419. nC.add( cb );
  6420. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6421. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6422. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6423. }
  6424. } else {
  6425. // non-indexed elements (unconnected triangle soup)
  6426. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6427. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6428. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6429. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6430. cb.subVectors( pC, pB );
  6431. ab.subVectors( pA, pB );
  6432. cb.cross( ab );
  6433. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6434. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6435. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6436. }
  6437. }
  6438. this.normalizeNormals();
  6439. normalAttribute.needsUpdate = true;
  6440. }
  6441. }
  6442. // @deprecated since r144
  6443. merge() {
  6444. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' );
  6445. return this;
  6446. }
  6447. normalizeNormals() {
  6448. const normals = this.attributes.normal;
  6449. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6450. _vector$7.fromBufferAttribute( normals, i );
  6451. _vector$7.normalize();
  6452. normals.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  6453. }
  6454. }
  6455. toNonIndexed() {
  6456. function convertBufferAttribute( attribute, indices ) {
  6457. const array = attribute.array;
  6458. const itemSize = attribute.itemSize;
  6459. const normalized = attribute.normalized;
  6460. const array2 = new array.constructor( indices.length * itemSize );
  6461. let index = 0, index2 = 0;
  6462. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6463. if ( attribute.isInterleavedBufferAttribute ) {
  6464. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6465. } else {
  6466. index = indices[ i ] * itemSize;
  6467. }
  6468. for ( let j = 0; j < itemSize; j ++ ) {
  6469. array2[ index2 ++ ] = array[ index ++ ];
  6470. }
  6471. }
  6472. return new BufferAttribute( array2, itemSize, normalized );
  6473. }
  6474. //
  6475. if ( this.index === null ) {
  6476. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6477. return this;
  6478. }
  6479. const geometry2 = new BufferGeometry();
  6480. const indices = this.index.array;
  6481. const attributes = this.attributes;
  6482. // attributes
  6483. for ( const name in attributes ) {
  6484. const attribute = attributes[ name ];
  6485. const newAttribute = convertBufferAttribute( attribute, indices );
  6486. geometry2.setAttribute( name, newAttribute );
  6487. }
  6488. // morph attributes
  6489. const morphAttributes = this.morphAttributes;
  6490. for ( const name in morphAttributes ) {
  6491. const morphArray = [];
  6492. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6493. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6494. const attribute = morphAttribute[ i ];
  6495. const newAttribute = convertBufferAttribute( attribute, indices );
  6496. morphArray.push( newAttribute );
  6497. }
  6498. geometry2.morphAttributes[ name ] = morphArray;
  6499. }
  6500. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6501. // groups
  6502. const groups = this.groups;
  6503. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6504. const group = groups[ i ];
  6505. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6506. }
  6507. return geometry2;
  6508. }
  6509. toJSON() {
  6510. const data = {
  6511. metadata: {
  6512. version: 4.5,
  6513. type: 'BufferGeometry',
  6514. generator: 'BufferGeometry.toJSON'
  6515. }
  6516. };
  6517. // standard BufferGeometry serialization
  6518. data.uuid = this.uuid;
  6519. data.type = this.type;
  6520. if ( this.name !== '' ) data.name = this.name;
  6521. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6522. if ( this.parameters !== undefined ) {
  6523. const parameters = this.parameters;
  6524. for ( const key in parameters ) {
  6525. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6526. }
  6527. return data;
  6528. }
  6529. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6530. data.data = { attributes: {} };
  6531. const index = this.index;
  6532. if ( index !== null ) {
  6533. data.data.index = {
  6534. type: index.array.constructor.name,
  6535. array: Array.prototype.slice.call( index.array )
  6536. };
  6537. }
  6538. const attributes = this.attributes;
  6539. for ( const key in attributes ) {
  6540. const attribute = attributes[ key ];
  6541. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6542. }
  6543. const morphAttributes = {};
  6544. let hasMorphAttributes = false;
  6545. for ( const key in this.morphAttributes ) {
  6546. const attributeArray = this.morphAttributes[ key ];
  6547. const array = [];
  6548. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6549. const attribute = attributeArray[ i ];
  6550. array.push( attribute.toJSON( data.data ) );
  6551. }
  6552. if ( array.length > 0 ) {
  6553. morphAttributes[ key ] = array;
  6554. hasMorphAttributes = true;
  6555. }
  6556. }
  6557. if ( hasMorphAttributes ) {
  6558. data.data.morphAttributes = morphAttributes;
  6559. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6560. }
  6561. const groups = this.groups;
  6562. if ( groups.length > 0 ) {
  6563. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6564. }
  6565. const boundingSphere = this.boundingSphere;
  6566. if ( boundingSphere !== null ) {
  6567. data.data.boundingSphere = {
  6568. center: boundingSphere.center.toArray(),
  6569. radius: boundingSphere.radius
  6570. };
  6571. }
  6572. return data;
  6573. }
  6574. clone() {
  6575. return new this.constructor().copy( this );
  6576. }
  6577. copy( source ) {
  6578. // reset
  6579. this.index = null;
  6580. this.attributes = {};
  6581. this.morphAttributes = {};
  6582. this.groups = [];
  6583. this.boundingBox = null;
  6584. this.boundingSphere = null;
  6585. // used for storing cloned, shared data
  6586. const data = {};
  6587. // name
  6588. this.name = source.name;
  6589. // index
  6590. const index = source.index;
  6591. if ( index !== null ) {
  6592. this.setIndex( index.clone( data ) );
  6593. }
  6594. // attributes
  6595. const attributes = source.attributes;
  6596. for ( const name in attributes ) {
  6597. const attribute = attributes[ name ];
  6598. this.setAttribute( name, attribute.clone( data ) );
  6599. }
  6600. // morph attributes
  6601. const morphAttributes = source.morphAttributes;
  6602. for ( const name in morphAttributes ) {
  6603. const array = [];
  6604. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6605. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6606. array.push( morphAttribute[ i ].clone( data ) );
  6607. }
  6608. this.morphAttributes[ name ] = array;
  6609. }
  6610. this.morphTargetsRelative = source.morphTargetsRelative;
  6611. // groups
  6612. const groups = source.groups;
  6613. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6614. const group = groups[ i ];
  6615. this.addGroup( group.start, group.count, group.materialIndex );
  6616. }
  6617. // bounding box
  6618. const boundingBox = source.boundingBox;
  6619. if ( boundingBox !== null ) {
  6620. this.boundingBox = boundingBox.clone();
  6621. }
  6622. // bounding sphere
  6623. const boundingSphere = source.boundingSphere;
  6624. if ( boundingSphere !== null ) {
  6625. this.boundingSphere = boundingSphere.clone();
  6626. }
  6627. // draw range
  6628. this.drawRange.start = source.drawRange.start;
  6629. this.drawRange.count = source.drawRange.count;
  6630. // user data
  6631. this.userData = source.userData;
  6632. return this;
  6633. }
  6634. dispose() {
  6635. this.dispatchEvent( { type: 'dispose' } );
  6636. }
  6637. }
  6638. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6639. const _ray$2 = /*@__PURE__*/ new Ray();
  6640. const _sphere$4 = /*@__PURE__*/ new Sphere();
  6641. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6642. const _vA$1 = /*@__PURE__*/ new Vector3();
  6643. const _vB$1 = /*@__PURE__*/ new Vector3();
  6644. const _vC$1 = /*@__PURE__*/ new Vector3();
  6645. const _tempA = /*@__PURE__*/ new Vector3();
  6646. const _morphA = /*@__PURE__*/ new Vector3();
  6647. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6648. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6649. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6650. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6651. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6652. class Mesh extends Object3D {
  6653. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6654. super();
  6655. this.isMesh = true;
  6656. this.type = 'Mesh';
  6657. this.geometry = geometry;
  6658. this.material = material;
  6659. this.updateMorphTargets();
  6660. }
  6661. copy( source, recursive ) {
  6662. super.copy( source, recursive );
  6663. if ( source.morphTargetInfluences !== undefined ) {
  6664. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6665. }
  6666. if ( source.morphTargetDictionary !== undefined ) {
  6667. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6668. }
  6669. this.material = source.material;
  6670. this.geometry = source.geometry;
  6671. return this;
  6672. }
  6673. updateMorphTargets() {
  6674. const geometry = this.geometry;
  6675. const morphAttributes = geometry.morphAttributes;
  6676. const keys = Object.keys( morphAttributes );
  6677. if ( keys.length > 0 ) {
  6678. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6679. if ( morphAttribute !== undefined ) {
  6680. this.morphTargetInfluences = [];
  6681. this.morphTargetDictionary = {};
  6682. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6683. const name = morphAttribute[ m ].name || String( m );
  6684. this.morphTargetInfluences.push( 0 );
  6685. this.morphTargetDictionary[ name ] = m;
  6686. }
  6687. }
  6688. }
  6689. }
  6690. getVertexPosition( index, target ) {
  6691. const geometry = this.geometry;
  6692. const position = geometry.attributes.position;
  6693. const morphPosition = geometry.morphAttributes.position;
  6694. const morphTargetsRelative = geometry.morphTargetsRelative;
  6695. target.fromBufferAttribute( position, index );
  6696. const morphInfluences = this.morphTargetInfluences;
  6697. if ( morphPosition && morphInfluences ) {
  6698. _morphA.set( 0, 0, 0 );
  6699. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6700. const influence = morphInfluences[ i ];
  6701. const morphAttribute = morphPosition[ i ];
  6702. if ( influence === 0 ) continue;
  6703. _tempA.fromBufferAttribute( morphAttribute, index );
  6704. if ( morphTargetsRelative ) {
  6705. _morphA.addScaledVector( _tempA, influence );
  6706. } else {
  6707. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6708. }
  6709. }
  6710. target.add( _morphA );
  6711. }
  6712. if ( this.isSkinnedMesh ) {
  6713. this.applyBoneTransform( index, target );
  6714. }
  6715. return target;
  6716. }
  6717. raycast( raycaster, intersects ) {
  6718. const geometry = this.geometry;
  6719. const material = this.material;
  6720. const matrixWorld = this.matrixWorld;
  6721. if ( material === undefined ) return;
  6722. // Checking boundingSphere distance to ray
  6723. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6724. _sphere$4.copy( geometry.boundingSphere );
  6725. _sphere$4.applyMatrix4( matrixWorld );
  6726. _ray$2.copy( raycaster.ray ).recast( raycaster.near );
  6727. if ( _sphere$4.containsPoint( _ray$2.origin ) === false ) {
  6728. if ( _ray$2.intersectSphere( _sphere$4, _sphereHitAt ) === null ) return;
  6729. if ( _ray$2.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6730. }
  6731. //
  6732. _inverseMatrix$2.copy( matrixWorld ).invert();
  6733. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6734. // Check boundingBox before continuing
  6735. if ( geometry.boundingBox !== null ) {
  6736. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6737. }
  6738. let intersection;
  6739. const index = geometry.index;
  6740. const position = geometry.attributes.position;
  6741. const uv = geometry.attributes.uv;
  6742. const uv2 = geometry.attributes.uv2;
  6743. const groups = geometry.groups;
  6744. const drawRange = geometry.drawRange;
  6745. if ( index !== null ) {
  6746. // indexed buffer geometry
  6747. if ( Array.isArray( material ) ) {
  6748. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6749. const group = groups[ i ];
  6750. const groupMaterial = material[ group.materialIndex ];
  6751. const start = Math.max( group.start, drawRange.start );
  6752. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6753. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6754. const a = index.getX( j );
  6755. const b = index.getX( j + 1 );
  6756. const c = index.getX( j + 2 );
  6757. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6758. if ( intersection ) {
  6759. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6760. intersection.face.materialIndex = group.materialIndex;
  6761. intersects.push( intersection );
  6762. }
  6763. }
  6764. }
  6765. } else {
  6766. const start = Math.max( 0, drawRange.start );
  6767. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6768. for ( let i = start, il = end; i < il; i += 3 ) {
  6769. const a = index.getX( i );
  6770. const b = index.getX( i + 1 );
  6771. const c = index.getX( i + 2 );
  6772. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6773. if ( intersection ) {
  6774. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6775. intersects.push( intersection );
  6776. }
  6777. }
  6778. }
  6779. } else if ( position !== undefined ) {
  6780. // non-indexed buffer geometry
  6781. if ( Array.isArray( material ) ) {
  6782. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6783. const group = groups[ i ];
  6784. const groupMaterial = material[ group.materialIndex ];
  6785. const start = Math.max( group.start, drawRange.start );
  6786. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6787. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6788. const a = j;
  6789. const b = j + 1;
  6790. const c = j + 2;
  6791. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6792. if ( intersection ) {
  6793. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6794. intersection.face.materialIndex = group.materialIndex;
  6795. intersects.push( intersection );
  6796. }
  6797. }
  6798. }
  6799. } else {
  6800. const start = Math.max( 0, drawRange.start );
  6801. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6802. for ( let i = start, il = end; i < il; i += 3 ) {
  6803. const a = i;
  6804. const b = i + 1;
  6805. const c = i + 2;
  6806. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6807. if ( intersection ) {
  6808. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6809. intersects.push( intersection );
  6810. }
  6811. }
  6812. }
  6813. }
  6814. }
  6815. }
  6816. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6817. let intersect;
  6818. if ( material.side === BackSide ) {
  6819. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6820. } else {
  6821. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6822. }
  6823. if ( intersect === null ) return null;
  6824. _intersectionPointWorld.copy( point );
  6825. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6826. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6827. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6828. return {
  6829. distance: distance,
  6830. point: _intersectionPointWorld.clone(),
  6831. object: object
  6832. };
  6833. }
  6834. function checkBufferGeometryIntersection( object, material, raycaster, ray, uv, uv2, a, b, c ) {
  6835. object.getVertexPosition( a, _vA$1 );
  6836. object.getVertexPosition( b, _vB$1 );
  6837. object.getVertexPosition( c, _vC$1 );
  6838. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6839. if ( intersection ) {
  6840. if ( uv ) {
  6841. _uvA$1.fromBufferAttribute( uv, a );
  6842. _uvB$1.fromBufferAttribute( uv, b );
  6843. _uvC$1.fromBufferAttribute( uv, c );
  6844. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6845. }
  6846. if ( uv2 ) {
  6847. _uvA$1.fromBufferAttribute( uv2, a );
  6848. _uvB$1.fromBufferAttribute( uv2, b );
  6849. _uvC$1.fromBufferAttribute( uv2, c );
  6850. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6851. }
  6852. const face = {
  6853. a: a,
  6854. b: b,
  6855. c: c,
  6856. normal: new Vector3(),
  6857. materialIndex: 0
  6858. };
  6859. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6860. intersection.face = face;
  6861. }
  6862. return intersection;
  6863. }
  6864. class BoxGeometry extends BufferGeometry {
  6865. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6866. super();
  6867. this.type = 'BoxGeometry';
  6868. this.parameters = {
  6869. width: width,
  6870. height: height,
  6871. depth: depth,
  6872. widthSegments: widthSegments,
  6873. heightSegments: heightSegments,
  6874. depthSegments: depthSegments
  6875. };
  6876. const scope = this;
  6877. // segments
  6878. widthSegments = Math.floor( widthSegments );
  6879. heightSegments = Math.floor( heightSegments );
  6880. depthSegments = Math.floor( depthSegments );
  6881. // buffers
  6882. const indices = [];
  6883. const vertices = [];
  6884. const normals = [];
  6885. const uvs = [];
  6886. // helper variables
  6887. let numberOfVertices = 0;
  6888. let groupStart = 0;
  6889. // build each side of the box geometry
  6890. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6891. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6892. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6893. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6894. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6895. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6896. // build geometry
  6897. this.setIndex( indices );
  6898. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6899. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6900. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6901. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6902. const segmentWidth = width / gridX;
  6903. const segmentHeight = height / gridY;
  6904. const widthHalf = width / 2;
  6905. const heightHalf = height / 2;
  6906. const depthHalf = depth / 2;
  6907. const gridX1 = gridX + 1;
  6908. const gridY1 = gridY + 1;
  6909. let vertexCounter = 0;
  6910. let groupCount = 0;
  6911. const vector = new Vector3();
  6912. // generate vertices, normals and uvs
  6913. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6914. const y = iy * segmentHeight - heightHalf;
  6915. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6916. const x = ix * segmentWidth - widthHalf;
  6917. // set values to correct vector component
  6918. vector[ u ] = x * udir;
  6919. vector[ v ] = y * vdir;
  6920. vector[ w ] = depthHalf;
  6921. // now apply vector to vertex buffer
  6922. vertices.push( vector.x, vector.y, vector.z );
  6923. // set values to correct vector component
  6924. vector[ u ] = 0;
  6925. vector[ v ] = 0;
  6926. vector[ w ] = depth > 0 ? 1 : - 1;
  6927. // now apply vector to normal buffer
  6928. normals.push( vector.x, vector.y, vector.z );
  6929. // uvs
  6930. uvs.push( ix / gridX );
  6931. uvs.push( 1 - ( iy / gridY ) );
  6932. // counters
  6933. vertexCounter += 1;
  6934. }
  6935. }
  6936. // indices
  6937. // 1. you need three indices to draw a single face
  6938. // 2. a single segment consists of two faces
  6939. // 3. so we need to generate six (2*3) indices per segment
  6940. for ( let iy = 0; iy < gridY; iy ++ ) {
  6941. for ( let ix = 0; ix < gridX; ix ++ ) {
  6942. const a = numberOfVertices + ix + gridX1 * iy;
  6943. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6944. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6945. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6946. // faces
  6947. indices.push( a, b, d );
  6948. indices.push( b, c, d );
  6949. // increase counter
  6950. groupCount += 6;
  6951. }
  6952. }
  6953. // add a group to the geometry. this will ensure multi material support
  6954. scope.addGroup( groupStart, groupCount, materialIndex );
  6955. // calculate new start value for groups
  6956. groupStart += groupCount;
  6957. // update total number of vertices
  6958. numberOfVertices += vertexCounter;
  6959. }
  6960. }
  6961. copy( source ) {
  6962. super.copy( source );
  6963. this.parameters = Object.assign( {}, source.parameters );
  6964. return this;
  6965. }
  6966. static fromJSON( data ) {
  6967. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6968. }
  6969. }
  6970. /**
  6971. * Uniform Utilities
  6972. */
  6973. function cloneUniforms( src ) {
  6974. const dst = {};
  6975. for ( const u in src ) {
  6976. dst[ u ] = {};
  6977. for ( const p in src[ u ] ) {
  6978. const property = src[ u ][ p ];
  6979. if ( property && ( property.isColor ||
  6980. property.isMatrix3 || property.isMatrix4 ||
  6981. property.isVector2 || property.isVector3 || property.isVector4 ||
  6982. property.isTexture || property.isQuaternion ) ) {
  6983. if ( property.isRenderTargetTexture ) {
  6984. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  6985. dst[ u ][ p ] = null;
  6986. } else {
  6987. dst[ u ][ p ] = property.clone();
  6988. }
  6989. } else if ( Array.isArray( property ) ) {
  6990. dst[ u ][ p ] = property.slice();
  6991. } else {
  6992. dst[ u ][ p ] = property;
  6993. }
  6994. }
  6995. }
  6996. return dst;
  6997. }
  6998. function mergeUniforms( uniforms ) {
  6999. const merged = {};
  7000. for ( let u = 0; u < uniforms.length; u ++ ) {
  7001. const tmp = cloneUniforms( uniforms[ u ] );
  7002. for ( const p in tmp ) {
  7003. merged[ p ] = tmp[ p ];
  7004. }
  7005. }
  7006. return merged;
  7007. }
  7008. function cloneUniformsGroups( src ) {
  7009. const dst = [];
  7010. for ( let u = 0; u < src.length; u ++ ) {
  7011. dst.push( src[ u ].clone() );
  7012. }
  7013. return dst;
  7014. }
  7015. function getUnlitUniformColorSpace( renderer ) {
  7016. if ( renderer.getRenderTarget() === null ) {
  7017. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7018. return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  7019. }
  7020. return LinearSRGBColorSpace;
  7021. }
  7022. // Legacy
  7023. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7024. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7025. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7026. class ShaderMaterial extends Material {
  7027. constructor( parameters ) {
  7028. super();
  7029. this.isShaderMaterial = true;
  7030. this.type = 'ShaderMaterial';
  7031. this.defines = {};
  7032. this.uniforms = {};
  7033. this.uniformsGroups = [];
  7034. this.vertexShader = default_vertex;
  7035. this.fragmentShader = default_fragment;
  7036. this.linewidth = 1;
  7037. this.wireframe = false;
  7038. this.wireframeLinewidth = 1;
  7039. this.fog = false; // set to use scene fog
  7040. this.lights = false; // set to use scene lights
  7041. this.clipping = false; // set to use user-defined clipping planes
  7042. this.extensions = {
  7043. derivatives: false, // set to use derivatives
  7044. fragDepth: false, // set to use fragment depth values
  7045. drawBuffers: false, // set to use draw buffers
  7046. shaderTextureLOD: false // set to use shader texture LOD
  7047. };
  7048. // When rendered geometry doesn't include these attributes but the material does,
  7049. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7050. this.defaultAttributeValues = {
  7051. 'color': [ 1, 1, 1 ],
  7052. 'uv': [ 0, 0 ],
  7053. 'uv2': [ 0, 0 ]
  7054. };
  7055. this.index0AttributeName = undefined;
  7056. this.uniformsNeedUpdate = false;
  7057. this.glslVersion = null;
  7058. if ( parameters !== undefined ) {
  7059. this.setValues( parameters );
  7060. }
  7061. }
  7062. copy( source ) {
  7063. super.copy( source );
  7064. this.fragmentShader = source.fragmentShader;
  7065. this.vertexShader = source.vertexShader;
  7066. this.uniforms = cloneUniforms( source.uniforms );
  7067. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7068. this.defines = Object.assign( {}, source.defines );
  7069. this.wireframe = source.wireframe;
  7070. this.wireframeLinewidth = source.wireframeLinewidth;
  7071. this.fog = source.fog;
  7072. this.lights = source.lights;
  7073. this.clipping = source.clipping;
  7074. this.extensions = Object.assign( {}, source.extensions );
  7075. this.glslVersion = source.glslVersion;
  7076. return this;
  7077. }
  7078. toJSON( meta ) {
  7079. const data = super.toJSON( meta );
  7080. data.glslVersion = this.glslVersion;
  7081. data.uniforms = {};
  7082. for ( const name in this.uniforms ) {
  7083. const uniform = this.uniforms[ name ];
  7084. const value = uniform.value;
  7085. if ( value && value.isTexture ) {
  7086. data.uniforms[ name ] = {
  7087. type: 't',
  7088. value: value.toJSON( meta ).uuid
  7089. };
  7090. } else if ( value && value.isColor ) {
  7091. data.uniforms[ name ] = {
  7092. type: 'c',
  7093. value: value.getHex()
  7094. };
  7095. } else if ( value && value.isVector2 ) {
  7096. data.uniforms[ name ] = {
  7097. type: 'v2',
  7098. value: value.toArray()
  7099. };
  7100. } else if ( value && value.isVector3 ) {
  7101. data.uniforms[ name ] = {
  7102. type: 'v3',
  7103. value: value.toArray()
  7104. };
  7105. } else if ( value && value.isVector4 ) {
  7106. data.uniforms[ name ] = {
  7107. type: 'v4',
  7108. value: value.toArray()
  7109. };
  7110. } else if ( value && value.isMatrix3 ) {
  7111. data.uniforms[ name ] = {
  7112. type: 'm3',
  7113. value: value.toArray()
  7114. };
  7115. } else if ( value && value.isMatrix4 ) {
  7116. data.uniforms[ name ] = {
  7117. type: 'm4',
  7118. value: value.toArray()
  7119. };
  7120. } else {
  7121. data.uniforms[ name ] = {
  7122. value: value
  7123. };
  7124. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7125. }
  7126. }
  7127. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7128. data.vertexShader = this.vertexShader;
  7129. data.fragmentShader = this.fragmentShader;
  7130. const extensions = {};
  7131. for ( const key in this.extensions ) {
  7132. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7133. }
  7134. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7135. return data;
  7136. }
  7137. }
  7138. class Camera extends Object3D {
  7139. constructor() {
  7140. super();
  7141. this.isCamera = true;
  7142. this.type = 'Camera';
  7143. this.matrixWorldInverse = new Matrix4();
  7144. this.projectionMatrix = new Matrix4();
  7145. this.projectionMatrixInverse = new Matrix4();
  7146. }
  7147. copy( source, recursive ) {
  7148. super.copy( source, recursive );
  7149. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7150. this.projectionMatrix.copy( source.projectionMatrix );
  7151. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7152. return this;
  7153. }
  7154. getWorldDirection( target ) {
  7155. this.updateWorldMatrix( true, false );
  7156. const e = this.matrixWorld.elements;
  7157. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7158. }
  7159. updateMatrixWorld( force ) {
  7160. super.updateMatrixWorld( force );
  7161. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7162. }
  7163. updateWorldMatrix( updateParents, updateChildren ) {
  7164. super.updateWorldMatrix( updateParents, updateChildren );
  7165. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7166. }
  7167. clone() {
  7168. return new this.constructor().copy( this );
  7169. }
  7170. }
  7171. class PerspectiveCamera extends Camera {
  7172. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7173. super();
  7174. this.isPerspectiveCamera = true;
  7175. this.type = 'PerspectiveCamera';
  7176. this.fov = fov;
  7177. this.zoom = 1;
  7178. this.near = near;
  7179. this.far = far;
  7180. this.focus = 10;
  7181. this.aspect = aspect;
  7182. this.view = null;
  7183. this.filmGauge = 35; // width of the film (default in millimeters)
  7184. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7185. this.updateProjectionMatrix();
  7186. }
  7187. copy( source, recursive ) {
  7188. super.copy( source, recursive );
  7189. this.fov = source.fov;
  7190. this.zoom = source.zoom;
  7191. this.near = source.near;
  7192. this.far = source.far;
  7193. this.focus = source.focus;
  7194. this.aspect = source.aspect;
  7195. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7196. this.filmGauge = source.filmGauge;
  7197. this.filmOffset = source.filmOffset;
  7198. return this;
  7199. }
  7200. /**
  7201. * Sets the FOV by focal length in respect to the current .filmGauge.
  7202. *
  7203. * The default film gauge is 35, so that the focal length can be specified for
  7204. * a 35mm (full frame) camera.
  7205. *
  7206. * Values for focal length and film gauge must have the same unit.
  7207. */
  7208. setFocalLength( focalLength ) {
  7209. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7210. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7211. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7212. this.updateProjectionMatrix();
  7213. }
  7214. /**
  7215. * Calculates the focal length from the current .fov and .filmGauge.
  7216. */
  7217. getFocalLength() {
  7218. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7219. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7220. }
  7221. getEffectiveFOV() {
  7222. return RAD2DEG * 2 * Math.atan(
  7223. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7224. }
  7225. getFilmWidth() {
  7226. // film not completely covered in portrait format (aspect < 1)
  7227. return this.filmGauge * Math.min( this.aspect, 1 );
  7228. }
  7229. getFilmHeight() {
  7230. // film not completely covered in landscape format (aspect > 1)
  7231. return this.filmGauge / Math.max( this.aspect, 1 );
  7232. }
  7233. /**
  7234. * Sets an offset in a larger frustum. This is useful for multi-window or
  7235. * multi-monitor/multi-machine setups.
  7236. *
  7237. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7238. * the monitors are in grid like this
  7239. *
  7240. * +---+---+---+
  7241. * | A | B | C |
  7242. * +---+---+---+
  7243. * | D | E | F |
  7244. * +---+---+---+
  7245. *
  7246. * then for each monitor you would call it like this
  7247. *
  7248. * const w = 1920;
  7249. * const h = 1080;
  7250. * const fullWidth = w * 3;
  7251. * const fullHeight = h * 2;
  7252. *
  7253. * --A--
  7254. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7255. * --B--
  7256. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7257. * --C--
  7258. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7259. * --D--
  7260. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7261. * --E--
  7262. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7263. * --F--
  7264. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7265. *
  7266. * Note there is no reason monitors have to be the same size or in a grid.
  7267. */
  7268. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7269. this.aspect = fullWidth / fullHeight;
  7270. if ( this.view === null ) {
  7271. this.view = {
  7272. enabled: true,
  7273. fullWidth: 1,
  7274. fullHeight: 1,
  7275. offsetX: 0,
  7276. offsetY: 0,
  7277. width: 1,
  7278. height: 1
  7279. };
  7280. }
  7281. this.view.enabled = true;
  7282. this.view.fullWidth = fullWidth;
  7283. this.view.fullHeight = fullHeight;
  7284. this.view.offsetX = x;
  7285. this.view.offsetY = y;
  7286. this.view.width = width;
  7287. this.view.height = height;
  7288. this.updateProjectionMatrix();
  7289. }
  7290. clearViewOffset() {
  7291. if ( this.view !== null ) {
  7292. this.view.enabled = false;
  7293. }
  7294. this.updateProjectionMatrix();
  7295. }
  7296. updateProjectionMatrix() {
  7297. const near = this.near;
  7298. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7299. let height = 2 * top;
  7300. let width = this.aspect * height;
  7301. let left = - 0.5 * width;
  7302. const view = this.view;
  7303. if ( this.view !== null && this.view.enabled ) {
  7304. const fullWidth = view.fullWidth,
  7305. fullHeight = view.fullHeight;
  7306. left += view.offsetX * width / fullWidth;
  7307. top -= view.offsetY * height / fullHeight;
  7308. width *= view.width / fullWidth;
  7309. height *= view.height / fullHeight;
  7310. }
  7311. const skew = this.filmOffset;
  7312. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7313. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7314. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7315. }
  7316. toJSON( meta ) {
  7317. const data = super.toJSON( meta );
  7318. data.object.fov = this.fov;
  7319. data.object.zoom = this.zoom;
  7320. data.object.near = this.near;
  7321. data.object.far = this.far;
  7322. data.object.focus = this.focus;
  7323. data.object.aspect = this.aspect;
  7324. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7325. data.object.filmGauge = this.filmGauge;
  7326. data.object.filmOffset = this.filmOffset;
  7327. return data;
  7328. }
  7329. }
  7330. const fov = - 90; // negative fov is not an error
  7331. const aspect = 1;
  7332. class CubeCamera extends Object3D {
  7333. constructor( near, far, renderTarget ) {
  7334. super();
  7335. this.type = 'CubeCamera';
  7336. this.renderTarget = renderTarget;
  7337. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7338. cameraPX.layers = this.layers;
  7339. cameraPX.up.set( 0, 1, 0 );
  7340. cameraPX.lookAt( 1, 0, 0 );
  7341. this.add( cameraPX );
  7342. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7343. cameraNX.layers = this.layers;
  7344. cameraNX.up.set( 0, 1, 0 );
  7345. cameraNX.lookAt( - 1, 0, 0 );
  7346. this.add( cameraNX );
  7347. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7348. cameraPY.layers = this.layers;
  7349. cameraPY.up.set( 0, 0, - 1 );
  7350. cameraPY.lookAt( 0, 1, 0 );
  7351. this.add( cameraPY );
  7352. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7353. cameraNY.layers = this.layers;
  7354. cameraNY.up.set( 0, 0, 1 );
  7355. cameraNY.lookAt( 0, - 1, 0 );
  7356. this.add( cameraNY );
  7357. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7358. cameraPZ.layers = this.layers;
  7359. cameraPZ.up.set( 0, 1, 0 );
  7360. cameraPZ.lookAt( 0, 0, 1 );
  7361. this.add( cameraPZ );
  7362. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7363. cameraNZ.layers = this.layers;
  7364. cameraNZ.up.set( 0, 1, 0 );
  7365. cameraNZ.lookAt( 0, 0, - 1 );
  7366. this.add( cameraNZ );
  7367. }
  7368. update( renderer, scene ) {
  7369. if ( this.parent === null ) this.updateMatrixWorld();
  7370. const renderTarget = this.renderTarget;
  7371. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7372. const currentRenderTarget = renderer.getRenderTarget();
  7373. const currentToneMapping = renderer.toneMapping;
  7374. const currentXrEnabled = renderer.xr.enabled;
  7375. renderer.toneMapping = NoToneMapping;
  7376. renderer.xr.enabled = false;
  7377. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7378. renderTarget.texture.generateMipmaps = false;
  7379. renderer.setRenderTarget( renderTarget, 0 );
  7380. renderer.render( scene, cameraPX );
  7381. renderer.setRenderTarget( renderTarget, 1 );
  7382. renderer.render( scene, cameraNX );
  7383. renderer.setRenderTarget( renderTarget, 2 );
  7384. renderer.render( scene, cameraPY );
  7385. renderer.setRenderTarget( renderTarget, 3 );
  7386. renderer.render( scene, cameraNY );
  7387. renderer.setRenderTarget( renderTarget, 4 );
  7388. renderer.render( scene, cameraPZ );
  7389. renderTarget.texture.generateMipmaps = generateMipmaps;
  7390. renderer.setRenderTarget( renderTarget, 5 );
  7391. renderer.render( scene, cameraNZ );
  7392. renderer.setRenderTarget( currentRenderTarget );
  7393. renderer.toneMapping = currentToneMapping;
  7394. renderer.xr.enabled = currentXrEnabled;
  7395. renderTarget.texture.needsPMREMUpdate = true;
  7396. }
  7397. }
  7398. class CubeTexture extends Texture {
  7399. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7400. images = images !== undefined ? images : [];
  7401. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7402. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7403. this.isCubeTexture = true;
  7404. this.flipY = false;
  7405. }
  7406. get images() {
  7407. return this.image;
  7408. }
  7409. set images( value ) {
  7410. this.image = value;
  7411. }
  7412. }
  7413. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7414. constructor( size = 1, options = {} ) {
  7415. super( size, size, options );
  7416. this.isWebGLCubeRenderTarget = true;
  7417. const image = { width: size, height: size, depth: 1 };
  7418. const images = [ image, image, image, image, image, image ];
  7419. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7420. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7421. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7422. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7423. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7424. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7425. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7426. this.texture.isRenderTargetTexture = true;
  7427. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7428. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7429. }
  7430. fromEquirectangularTexture( renderer, texture ) {
  7431. this.texture.type = texture.type;
  7432. this.texture.encoding = texture.encoding;
  7433. this.texture.generateMipmaps = texture.generateMipmaps;
  7434. this.texture.minFilter = texture.minFilter;
  7435. this.texture.magFilter = texture.magFilter;
  7436. const shader = {
  7437. uniforms: {
  7438. tEquirect: { value: null },
  7439. },
  7440. vertexShader: /* glsl */`
  7441. varying vec3 vWorldDirection;
  7442. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7443. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7444. }
  7445. void main() {
  7446. vWorldDirection = transformDirection( position, modelMatrix );
  7447. #include <begin_vertex>
  7448. #include <project_vertex>
  7449. }
  7450. `,
  7451. fragmentShader: /* glsl */`
  7452. uniform sampler2D tEquirect;
  7453. varying vec3 vWorldDirection;
  7454. #include <common>
  7455. void main() {
  7456. vec3 direction = normalize( vWorldDirection );
  7457. vec2 sampleUV = equirectUv( direction );
  7458. gl_FragColor = texture2D( tEquirect, sampleUV );
  7459. }
  7460. `
  7461. };
  7462. const geometry = new BoxGeometry( 5, 5, 5 );
  7463. const material = new ShaderMaterial( {
  7464. name: 'CubemapFromEquirect',
  7465. uniforms: cloneUniforms( shader.uniforms ),
  7466. vertexShader: shader.vertexShader,
  7467. fragmentShader: shader.fragmentShader,
  7468. side: BackSide,
  7469. blending: NoBlending
  7470. } );
  7471. material.uniforms.tEquirect.value = texture;
  7472. const mesh = new Mesh( geometry, material );
  7473. const currentMinFilter = texture.minFilter;
  7474. // Avoid blurred poles
  7475. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7476. const camera = new CubeCamera( 1, 10, this );
  7477. camera.update( renderer, mesh );
  7478. texture.minFilter = currentMinFilter;
  7479. mesh.geometry.dispose();
  7480. mesh.material.dispose();
  7481. return this;
  7482. }
  7483. clear( renderer, color, depth, stencil ) {
  7484. const currentRenderTarget = renderer.getRenderTarget();
  7485. for ( let i = 0; i < 6; i ++ ) {
  7486. renderer.setRenderTarget( this, i );
  7487. renderer.clear( color, depth, stencil );
  7488. }
  7489. renderer.setRenderTarget( currentRenderTarget );
  7490. }
  7491. }
  7492. const _vector1 = /*@__PURE__*/ new Vector3();
  7493. const _vector2 = /*@__PURE__*/ new Vector3();
  7494. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7495. class Plane {
  7496. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7497. this.isPlane = true;
  7498. // normal is assumed to be normalized
  7499. this.normal = normal;
  7500. this.constant = constant;
  7501. }
  7502. set( normal, constant ) {
  7503. this.normal.copy( normal );
  7504. this.constant = constant;
  7505. return this;
  7506. }
  7507. setComponents( x, y, z, w ) {
  7508. this.normal.set( x, y, z );
  7509. this.constant = w;
  7510. return this;
  7511. }
  7512. setFromNormalAndCoplanarPoint( normal, point ) {
  7513. this.normal.copy( normal );
  7514. this.constant = - point.dot( this.normal );
  7515. return this;
  7516. }
  7517. setFromCoplanarPoints( a, b, c ) {
  7518. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7519. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7520. this.setFromNormalAndCoplanarPoint( normal, a );
  7521. return this;
  7522. }
  7523. copy( plane ) {
  7524. this.normal.copy( plane.normal );
  7525. this.constant = plane.constant;
  7526. return this;
  7527. }
  7528. normalize() {
  7529. // Note: will lead to a divide by zero if the plane is invalid.
  7530. const inverseNormalLength = 1.0 / this.normal.length();
  7531. this.normal.multiplyScalar( inverseNormalLength );
  7532. this.constant *= inverseNormalLength;
  7533. return this;
  7534. }
  7535. negate() {
  7536. this.constant *= - 1;
  7537. this.normal.negate();
  7538. return this;
  7539. }
  7540. distanceToPoint( point ) {
  7541. return this.normal.dot( point ) + this.constant;
  7542. }
  7543. distanceToSphere( sphere ) {
  7544. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7545. }
  7546. projectPoint( point, target ) {
  7547. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7548. }
  7549. intersectLine( line, target ) {
  7550. const direction = line.delta( _vector1 );
  7551. const denominator = this.normal.dot( direction );
  7552. if ( denominator === 0 ) {
  7553. // line is coplanar, return origin
  7554. if ( this.distanceToPoint( line.start ) === 0 ) {
  7555. return target.copy( line.start );
  7556. }
  7557. // Unsure if this is the correct method to handle this case.
  7558. return null;
  7559. }
  7560. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7561. if ( t < 0 || t > 1 ) {
  7562. return null;
  7563. }
  7564. return target.copy( line.start ).addScaledVector( direction, t );
  7565. }
  7566. intersectsLine( line ) {
  7567. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7568. const startSign = this.distanceToPoint( line.start );
  7569. const endSign = this.distanceToPoint( line.end );
  7570. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7571. }
  7572. intersectsBox( box ) {
  7573. return box.intersectsPlane( this );
  7574. }
  7575. intersectsSphere( sphere ) {
  7576. return sphere.intersectsPlane( this );
  7577. }
  7578. coplanarPoint( target ) {
  7579. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7580. }
  7581. applyMatrix4( matrix, optionalNormalMatrix ) {
  7582. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7583. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7584. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7585. this.constant = - referencePoint.dot( normal );
  7586. return this;
  7587. }
  7588. translate( offset ) {
  7589. this.constant -= offset.dot( this.normal );
  7590. return this;
  7591. }
  7592. equals( plane ) {
  7593. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7594. }
  7595. clone() {
  7596. return new this.constructor().copy( this );
  7597. }
  7598. }
  7599. const _sphere$3 = /*@__PURE__*/ new Sphere();
  7600. const _vector$6 = /*@__PURE__*/ new Vector3();
  7601. class Frustum {
  7602. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7603. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7604. }
  7605. set( p0, p1, p2, p3, p4, p5 ) {
  7606. const planes = this.planes;
  7607. planes[ 0 ].copy( p0 );
  7608. planes[ 1 ].copy( p1 );
  7609. planes[ 2 ].copy( p2 );
  7610. planes[ 3 ].copy( p3 );
  7611. planes[ 4 ].copy( p4 );
  7612. planes[ 5 ].copy( p5 );
  7613. return this;
  7614. }
  7615. copy( frustum ) {
  7616. const planes = this.planes;
  7617. for ( let i = 0; i < 6; i ++ ) {
  7618. planes[ i ].copy( frustum.planes[ i ] );
  7619. }
  7620. return this;
  7621. }
  7622. setFromProjectionMatrix( m ) {
  7623. const planes = this.planes;
  7624. const me = m.elements;
  7625. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7626. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7627. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7628. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7629. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7630. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7631. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7632. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7633. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7634. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7635. return this;
  7636. }
  7637. intersectsObject( object ) {
  7638. if ( object.boundingSphere !== undefined ) {
  7639. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7640. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7641. } else {
  7642. const geometry = object.geometry;
  7643. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7644. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7645. }
  7646. return this.intersectsSphere( _sphere$3 );
  7647. }
  7648. intersectsSprite( sprite ) {
  7649. _sphere$3.center.set( 0, 0, 0 );
  7650. _sphere$3.radius = 0.7071067811865476;
  7651. _sphere$3.applyMatrix4( sprite.matrixWorld );
  7652. return this.intersectsSphere( _sphere$3 );
  7653. }
  7654. intersectsSphere( sphere ) {
  7655. const planes = this.planes;
  7656. const center = sphere.center;
  7657. const negRadius = - sphere.radius;
  7658. for ( let i = 0; i < 6; i ++ ) {
  7659. const distance = planes[ i ].distanceToPoint( center );
  7660. if ( distance < negRadius ) {
  7661. return false;
  7662. }
  7663. }
  7664. return true;
  7665. }
  7666. intersectsBox( box ) {
  7667. const planes = this.planes;
  7668. for ( let i = 0; i < 6; i ++ ) {
  7669. const plane = planes[ i ];
  7670. // corner at max distance
  7671. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7672. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7673. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7674. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  7675. return false;
  7676. }
  7677. }
  7678. return true;
  7679. }
  7680. containsPoint( point ) {
  7681. const planes = this.planes;
  7682. for ( let i = 0; i < 6; i ++ ) {
  7683. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7684. return false;
  7685. }
  7686. }
  7687. return true;
  7688. }
  7689. clone() {
  7690. return new this.constructor().copy( this );
  7691. }
  7692. }
  7693. function WebGLAnimation() {
  7694. let context = null;
  7695. let isAnimating = false;
  7696. let animationLoop = null;
  7697. let requestId = null;
  7698. function onAnimationFrame( time, frame ) {
  7699. animationLoop( time, frame );
  7700. requestId = context.requestAnimationFrame( onAnimationFrame );
  7701. }
  7702. return {
  7703. start: function () {
  7704. if ( isAnimating === true ) return;
  7705. if ( animationLoop === null ) return;
  7706. requestId = context.requestAnimationFrame( onAnimationFrame );
  7707. isAnimating = true;
  7708. },
  7709. stop: function () {
  7710. context.cancelAnimationFrame( requestId );
  7711. isAnimating = false;
  7712. },
  7713. setAnimationLoop: function ( callback ) {
  7714. animationLoop = callback;
  7715. },
  7716. setContext: function ( value ) {
  7717. context = value;
  7718. }
  7719. };
  7720. }
  7721. function WebGLAttributes( gl, capabilities ) {
  7722. const isWebGL2 = capabilities.isWebGL2;
  7723. const buffers = new WeakMap();
  7724. function createBuffer( attribute, bufferType ) {
  7725. const array = attribute.array;
  7726. const usage = attribute.usage;
  7727. const buffer = gl.createBuffer();
  7728. gl.bindBuffer( bufferType, buffer );
  7729. gl.bufferData( bufferType, array, usage );
  7730. attribute.onUploadCallback();
  7731. let type;
  7732. if ( array instanceof Float32Array ) {
  7733. type = gl.FLOAT;
  7734. } else if ( array instanceof Uint16Array ) {
  7735. if ( attribute.isFloat16BufferAttribute ) {
  7736. if ( isWebGL2 ) {
  7737. type = gl.HALF_FLOAT;
  7738. } else {
  7739. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7740. }
  7741. } else {
  7742. type = gl.UNSIGNED_SHORT;
  7743. }
  7744. } else if ( array instanceof Int16Array ) {
  7745. type = gl.SHORT;
  7746. } else if ( array instanceof Uint32Array ) {
  7747. type = gl.UNSIGNED_INT;
  7748. } else if ( array instanceof Int32Array ) {
  7749. type = gl.INT;
  7750. } else if ( array instanceof Int8Array ) {
  7751. type = gl.BYTE;
  7752. } else if ( array instanceof Uint8Array ) {
  7753. type = gl.UNSIGNED_BYTE;
  7754. } else if ( array instanceof Uint8ClampedArray ) {
  7755. type = gl.UNSIGNED_BYTE;
  7756. } else {
  7757. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7758. }
  7759. return {
  7760. buffer: buffer,
  7761. type: type,
  7762. bytesPerElement: array.BYTES_PER_ELEMENT,
  7763. version: attribute.version
  7764. };
  7765. }
  7766. function updateBuffer( buffer, attribute, bufferType ) {
  7767. const array = attribute.array;
  7768. const updateRange = attribute.updateRange;
  7769. gl.bindBuffer( bufferType, buffer );
  7770. if ( updateRange.count === - 1 ) {
  7771. // Not using update ranges
  7772. gl.bufferSubData( bufferType, 0, array );
  7773. } else {
  7774. if ( isWebGL2 ) {
  7775. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7776. array, updateRange.offset, updateRange.count );
  7777. } else {
  7778. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7779. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7780. }
  7781. updateRange.count = - 1; // reset range
  7782. }
  7783. attribute.onUploadCallback();
  7784. }
  7785. //
  7786. function get( attribute ) {
  7787. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7788. return buffers.get( attribute );
  7789. }
  7790. function remove( attribute ) {
  7791. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7792. const data = buffers.get( attribute );
  7793. if ( data ) {
  7794. gl.deleteBuffer( data.buffer );
  7795. buffers.delete( attribute );
  7796. }
  7797. }
  7798. function update( attribute, bufferType ) {
  7799. if ( attribute.isGLBufferAttribute ) {
  7800. const cached = buffers.get( attribute );
  7801. if ( ! cached || cached.version < attribute.version ) {
  7802. buffers.set( attribute, {
  7803. buffer: attribute.buffer,
  7804. type: attribute.type,
  7805. bytesPerElement: attribute.elementSize,
  7806. version: attribute.version
  7807. } );
  7808. }
  7809. return;
  7810. }
  7811. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7812. const data = buffers.get( attribute );
  7813. if ( data === undefined ) {
  7814. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7815. } else if ( data.version < attribute.version ) {
  7816. updateBuffer( data.buffer, attribute, bufferType );
  7817. data.version = attribute.version;
  7818. }
  7819. }
  7820. return {
  7821. get: get,
  7822. remove: remove,
  7823. update: update
  7824. };
  7825. }
  7826. class PlaneGeometry extends BufferGeometry {
  7827. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7828. super();
  7829. this.type = 'PlaneGeometry';
  7830. this.parameters = {
  7831. width: width,
  7832. height: height,
  7833. widthSegments: widthSegments,
  7834. heightSegments: heightSegments
  7835. };
  7836. const width_half = width / 2;
  7837. const height_half = height / 2;
  7838. const gridX = Math.floor( widthSegments );
  7839. const gridY = Math.floor( heightSegments );
  7840. const gridX1 = gridX + 1;
  7841. const gridY1 = gridY + 1;
  7842. const segment_width = width / gridX;
  7843. const segment_height = height / gridY;
  7844. //
  7845. const indices = [];
  7846. const vertices = [];
  7847. const normals = [];
  7848. const uvs = [];
  7849. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7850. const y = iy * segment_height - height_half;
  7851. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7852. const x = ix * segment_width - width_half;
  7853. vertices.push( x, - y, 0 );
  7854. normals.push( 0, 0, 1 );
  7855. uvs.push( ix / gridX );
  7856. uvs.push( 1 - ( iy / gridY ) );
  7857. }
  7858. }
  7859. for ( let iy = 0; iy < gridY; iy ++ ) {
  7860. for ( let ix = 0; ix < gridX; ix ++ ) {
  7861. const a = ix + gridX1 * iy;
  7862. const b = ix + gridX1 * ( iy + 1 );
  7863. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7864. const d = ( ix + 1 ) + gridX1 * iy;
  7865. indices.push( a, b, d );
  7866. indices.push( b, c, d );
  7867. }
  7868. }
  7869. this.setIndex( indices );
  7870. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7871. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7872. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7873. }
  7874. copy( source ) {
  7875. super.copy( source );
  7876. this.parameters = Object.assign( {}, source.parameters );
  7877. return this;
  7878. }
  7879. static fromJSON( data ) {
  7880. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7881. }
  7882. }
  7883. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7884. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7885. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7886. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7887. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7888. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7889. var begin_vertex = "vec3 transformed = vec3( position );";
  7890. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7891. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\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
  7892. var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\t return vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat R21 = R12;\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif";
  7893. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  7894. 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";
  7895. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7896. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7897. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7898. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7899. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7900. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7901. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  7902. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, 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}";
  7903. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.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\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\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\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_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 ), cubeUV_m0, CUBEUV_MAX_MIP );\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";
  7904. 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";
  7905. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7906. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7907. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7908. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7909. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7910. var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
  7911. 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#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7912. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  7913. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\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";
  7914. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\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";
  7915. 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";
  7916. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7917. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7918. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7919. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7920. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}";
  7921. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7922. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7923. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7924. var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert";
  7925. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NU
  7926. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7927. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7928. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon";
  7929. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7930. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong";
  7931. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
  7932. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec
  7933. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( 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\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.vis
  7934. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7935. 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";
  7936. 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";
  7937. 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";
  7938. 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";
  7939. 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";
  7940. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  7941. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7942. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  7943. 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";
  7944. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7945. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7946. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif";
  7947. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  7948. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  7949. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  7950. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  7951. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  7952. var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7953. var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7954. var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
  7955. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  7956. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7957. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif";
  7958. 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";
  7959. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  7960. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7961. 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}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\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 depth, const in float near, const in float far ) {\n\treturn depth * ( 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 depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}";
  7962. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7963. 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;";
  7964. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7965. 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";
  7966. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7967. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7968. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#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\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\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\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 + ve
  7969. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#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\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";
  7970. var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7971. 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, vSpotLightCoord[ 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}";
  7972. 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";
  7973. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif";
  7974. 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";
  7975. 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";
  7976. 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";
  7977. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7978. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7979. 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; }";
  7980. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif";
  7981. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, vec2 fullSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\t\n\t\tvec2 lodFudge = pow( 1.95, lod ) / fullSize;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec2 fullSize = vec2( textureSize( sampler, 0 ) );\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), fullSize, floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), fullSize, ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( c
  7982. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7983. 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";
  7984. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7985. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7986. 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";
  7987. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7988. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\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";
  7989. const vertex$h = "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}";
  7990. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7991. const vertex$g = "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}";
  7992. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7993. const vertex$f = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  7994. const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7995. const vertex$e = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  7996. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7997. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  7998. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7999. const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  8000. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8001. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <morphcolor_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}";
  8002. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8003. const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  8004. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8005. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8006. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_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_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8007. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  8008. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8009. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8010. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8011. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8012. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8013. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  8014. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8015. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8016. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8017. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <morphcolor_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}";
  8018. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8019. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8020. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\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}";
  8021. const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8022. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8023. const ShaderChunk = {
  8024. alphamap_fragment: alphamap_fragment,
  8025. alphamap_pars_fragment: alphamap_pars_fragment,
  8026. alphatest_fragment: alphatest_fragment,
  8027. alphatest_pars_fragment: alphatest_pars_fragment,
  8028. aomap_fragment: aomap_fragment,
  8029. aomap_pars_fragment: aomap_pars_fragment,
  8030. begin_vertex: begin_vertex,
  8031. beginnormal_vertex: beginnormal_vertex,
  8032. bsdfs: bsdfs,
  8033. iridescence_fragment: iridescence_fragment,
  8034. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8035. clipping_planes_fragment: clipping_planes_fragment,
  8036. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8037. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8038. clipping_planes_vertex: clipping_planes_vertex,
  8039. color_fragment: color_fragment,
  8040. color_pars_fragment: color_pars_fragment,
  8041. color_pars_vertex: color_pars_vertex,
  8042. color_vertex: color_vertex,
  8043. common: common,
  8044. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8045. defaultnormal_vertex: defaultnormal_vertex,
  8046. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8047. displacementmap_vertex: displacementmap_vertex,
  8048. emissivemap_fragment: emissivemap_fragment,
  8049. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8050. encodings_fragment: encodings_fragment,
  8051. encodings_pars_fragment: encodings_pars_fragment,
  8052. envmap_fragment: envmap_fragment,
  8053. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8054. envmap_pars_fragment: envmap_pars_fragment,
  8055. envmap_pars_vertex: envmap_pars_vertex,
  8056. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8057. envmap_vertex: envmap_vertex,
  8058. fog_vertex: fog_vertex,
  8059. fog_pars_vertex: fog_pars_vertex,
  8060. fog_fragment: fog_fragment,
  8061. fog_pars_fragment: fog_pars_fragment,
  8062. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8063. lightmap_fragment: lightmap_fragment,
  8064. lightmap_pars_fragment: lightmap_pars_fragment,
  8065. lights_lambert_fragment: lights_lambert_fragment,
  8066. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8067. lights_pars_begin: lights_pars_begin,
  8068. lights_toon_fragment: lights_toon_fragment,
  8069. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8070. lights_phong_fragment: lights_phong_fragment,
  8071. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8072. lights_physical_fragment: lights_physical_fragment,
  8073. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8074. lights_fragment_begin: lights_fragment_begin,
  8075. lights_fragment_maps: lights_fragment_maps,
  8076. lights_fragment_end: lights_fragment_end,
  8077. logdepthbuf_fragment: logdepthbuf_fragment,
  8078. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8079. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8080. logdepthbuf_vertex: logdepthbuf_vertex,
  8081. map_fragment: map_fragment,
  8082. map_pars_fragment: map_pars_fragment,
  8083. map_particle_fragment: map_particle_fragment,
  8084. map_particle_pars_fragment: map_particle_pars_fragment,
  8085. metalnessmap_fragment: metalnessmap_fragment,
  8086. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8087. morphcolor_vertex: morphcolor_vertex,
  8088. morphnormal_vertex: morphnormal_vertex,
  8089. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8090. morphtarget_vertex: morphtarget_vertex,
  8091. normal_fragment_begin: normal_fragment_begin,
  8092. normal_fragment_maps: normal_fragment_maps,
  8093. normal_pars_fragment: normal_pars_fragment,
  8094. normal_pars_vertex: normal_pars_vertex,
  8095. normal_vertex: normal_vertex,
  8096. normalmap_pars_fragment: normalmap_pars_fragment,
  8097. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8098. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8099. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8100. iridescence_pars_fragment: iridescence_pars_fragment,
  8101. output_fragment: output_fragment,
  8102. packing: packing,
  8103. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8104. project_vertex: project_vertex,
  8105. dithering_fragment: dithering_fragment,
  8106. dithering_pars_fragment: dithering_pars_fragment,
  8107. roughnessmap_fragment: roughnessmap_fragment,
  8108. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8109. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8110. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8111. shadowmap_vertex: shadowmap_vertex,
  8112. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8113. skinbase_vertex: skinbase_vertex,
  8114. skinning_pars_vertex: skinning_pars_vertex,
  8115. skinning_vertex: skinning_vertex,
  8116. skinnormal_vertex: skinnormal_vertex,
  8117. specularmap_fragment: specularmap_fragment,
  8118. specularmap_pars_fragment: specularmap_pars_fragment,
  8119. tonemapping_fragment: tonemapping_fragment,
  8120. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8121. transmission_fragment: transmission_fragment,
  8122. transmission_pars_fragment: transmission_pars_fragment,
  8123. uv_pars_fragment: uv_pars_fragment,
  8124. uv_pars_vertex: uv_pars_vertex,
  8125. uv_vertex: uv_vertex,
  8126. uv2_pars_fragment: uv2_pars_fragment,
  8127. uv2_pars_vertex: uv2_pars_vertex,
  8128. uv2_vertex: uv2_vertex,
  8129. worldpos_vertex: worldpos_vertex,
  8130. background_vert: vertex$h,
  8131. background_frag: fragment$h,
  8132. backgroundCube_vert: vertex$g,
  8133. backgroundCube_frag: fragment$g,
  8134. cube_vert: vertex$f,
  8135. cube_frag: fragment$f,
  8136. depth_vert: vertex$e,
  8137. depth_frag: fragment$e,
  8138. distanceRGBA_vert: vertex$d,
  8139. distanceRGBA_frag: fragment$d,
  8140. equirect_vert: vertex$c,
  8141. equirect_frag: fragment$c,
  8142. linedashed_vert: vertex$b,
  8143. linedashed_frag: fragment$b,
  8144. meshbasic_vert: vertex$a,
  8145. meshbasic_frag: fragment$a,
  8146. meshlambert_vert: vertex$9,
  8147. meshlambert_frag: fragment$9,
  8148. meshmatcap_vert: vertex$8,
  8149. meshmatcap_frag: fragment$8,
  8150. meshnormal_vert: vertex$7,
  8151. meshnormal_frag: fragment$7,
  8152. meshphong_vert: vertex$6,
  8153. meshphong_frag: fragment$6,
  8154. meshphysical_vert: vertex$5,
  8155. meshphysical_frag: fragment$5,
  8156. meshtoon_vert: vertex$4,
  8157. meshtoon_frag: fragment$4,
  8158. points_vert: vertex$3,
  8159. points_frag: fragment$3,
  8160. shadow_vert: vertex$2,
  8161. shadow_frag: fragment$2,
  8162. sprite_vert: vertex$1,
  8163. sprite_frag: fragment$1
  8164. };
  8165. /**
  8166. * Uniforms library for shared webgl shaders
  8167. */
  8168. const UniformsLib = {
  8169. common: {
  8170. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8171. opacity: { value: 1.0 },
  8172. map: { value: null },
  8173. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8174. uv2Transform: { value: /*@__PURE__*/ new Matrix3() },
  8175. alphaMap: { value: null },
  8176. alphaTest: { value: 0 }
  8177. },
  8178. specularmap: {
  8179. specularMap: { value: null },
  8180. },
  8181. envmap: {
  8182. envMap: { value: null },
  8183. flipEnvMap: { value: - 1 },
  8184. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8185. ior: { value: 1.5 }, // physical
  8186. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8187. },
  8188. aomap: {
  8189. aoMap: { value: null },
  8190. aoMapIntensity: { value: 1 }
  8191. },
  8192. lightmap: {
  8193. lightMap: { value: null },
  8194. lightMapIntensity: { value: 1 }
  8195. },
  8196. emissivemap: {
  8197. emissiveMap: { value: null }
  8198. },
  8199. bumpmap: {
  8200. bumpMap: { value: null },
  8201. bumpScale: { value: 1 }
  8202. },
  8203. normalmap: {
  8204. normalMap: { value: null },
  8205. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8206. },
  8207. displacementmap: {
  8208. displacementMap: { value: null },
  8209. displacementScale: { value: 1 },
  8210. displacementBias: { value: 0 }
  8211. },
  8212. roughnessmap: {
  8213. roughnessMap: { value: null }
  8214. },
  8215. metalnessmap: {
  8216. metalnessMap: { value: null }
  8217. },
  8218. gradientmap: {
  8219. gradientMap: { value: null }
  8220. },
  8221. fog: {
  8222. fogDensity: { value: 0.00025 },
  8223. fogNear: { value: 1 },
  8224. fogFar: { value: 2000 },
  8225. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8226. },
  8227. lights: {
  8228. ambientLightColor: { value: [] },
  8229. lightProbe: { value: [] },
  8230. directionalLights: { value: [], properties: {
  8231. direction: {},
  8232. color: {}
  8233. } },
  8234. directionalLightShadows: { value: [], properties: {
  8235. shadowBias: {},
  8236. shadowNormalBias: {},
  8237. shadowRadius: {},
  8238. shadowMapSize: {}
  8239. } },
  8240. directionalShadowMap: { value: [] },
  8241. directionalShadowMatrix: { value: [] },
  8242. spotLights: { value: [], properties: {
  8243. color: {},
  8244. position: {},
  8245. direction: {},
  8246. distance: {},
  8247. coneCos: {},
  8248. penumbraCos: {},
  8249. decay: {}
  8250. } },
  8251. spotLightShadows: { value: [], properties: {
  8252. shadowBias: {},
  8253. shadowNormalBias: {},
  8254. shadowRadius: {},
  8255. shadowMapSize: {}
  8256. } },
  8257. spotLightMap: { value: [] },
  8258. spotShadowMap: { value: [] },
  8259. spotLightMatrix: { value: [] },
  8260. pointLights: { value: [], properties: {
  8261. color: {},
  8262. position: {},
  8263. decay: {},
  8264. distance: {}
  8265. } },
  8266. pointLightShadows: { value: [], properties: {
  8267. shadowBias: {},
  8268. shadowNormalBias: {},
  8269. shadowRadius: {},
  8270. shadowMapSize: {},
  8271. shadowCameraNear: {},
  8272. shadowCameraFar: {}
  8273. } },
  8274. pointShadowMap: { value: [] },
  8275. pointShadowMatrix: { value: [] },
  8276. hemisphereLights: { value: [], properties: {
  8277. direction: {},
  8278. skyColor: {},
  8279. groundColor: {}
  8280. } },
  8281. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8282. rectAreaLights: { value: [], properties: {
  8283. color: {},
  8284. position: {},
  8285. width: {},
  8286. height: {}
  8287. } },
  8288. ltc_1: { value: null },
  8289. ltc_2: { value: null }
  8290. },
  8291. points: {
  8292. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8293. opacity: { value: 1.0 },
  8294. size: { value: 1.0 },
  8295. scale: { value: 1.0 },
  8296. map: { value: null },
  8297. alphaMap: { value: null },
  8298. alphaTest: { value: 0 },
  8299. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8300. },
  8301. sprite: {
  8302. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8303. opacity: { value: 1.0 },
  8304. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8305. rotation: { value: 0.0 },
  8306. map: { value: null },
  8307. alphaMap: { value: null },
  8308. alphaTest: { value: 0 },
  8309. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8310. }
  8311. };
  8312. const ShaderLib = {
  8313. basic: {
  8314. uniforms: /*@__PURE__*/ mergeUniforms( [
  8315. UniformsLib.common,
  8316. UniformsLib.specularmap,
  8317. UniformsLib.envmap,
  8318. UniformsLib.aomap,
  8319. UniformsLib.lightmap,
  8320. UniformsLib.fog
  8321. ] ),
  8322. vertexShader: ShaderChunk.meshbasic_vert,
  8323. fragmentShader: ShaderChunk.meshbasic_frag
  8324. },
  8325. lambert: {
  8326. uniforms: /*@__PURE__*/ mergeUniforms( [
  8327. UniformsLib.common,
  8328. UniformsLib.specularmap,
  8329. UniformsLib.envmap,
  8330. UniformsLib.aomap,
  8331. UniformsLib.lightmap,
  8332. UniformsLib.emissivemap,
  8333. UniformsLib.bumpmap,
  8334. UniformsLib.normalmap,
  8335. UniformsLib.displacementmap,
  8336. UniformsLib.fog,
  8337. UniformsLib.lights,
  8338. {
  8339. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8340. }
  8341. ] ),
  8342. vertexShader: ShaderChunk.meshlambert_vert,
  8343. fragmentShader: ShaderChunk.meshlambert_frag
  8344. },
  8345. phong: {
  8346. uniforms: /*@__PURE__*/ mergeUniforms( [
  8347. UniformsLib.common,
  8348. UniformsLib.specularmap,
  8349. UniformsLib.envmap,
  8350. UniformsLib.aomap,
  8351. UniformsLib.lightmap,
  8352. UniformsLib.emissivemap,
  8353. UniformsLib.bumpmap,
  8354. UniformsLib.normalmap,
  8355. UniformsLib.displacementmap,
  8356. UniformsLib.fog,
  8357. UniformsLib.lights,
  8358. {
  8359. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8360. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8361. shininess: { value: 30 }
  8362. }
  8363. ] ),
  8364. vertexShader: ShaderChunk.meshphong_vert,
  8365. fragmentShader: ShaderChunk.meshphong_frag
  8366. },
  8367. standard: {
  8368. uniforms: /*@__PURE__*/ mergeUniforms( [
  8369. UniformsLib.common,
  8370. UniformsLib.envmap,
  8371. UniformsLib.aomap,
  8372. UniformsLib.lightmap,
  8373. UniformsLib.emissivemap,
  8374. UniformsLib.bumpmap,
  8375. UniformsLib.normalmap,
  8376. UniformsLib.displacementmap,
  8377. UniformsLib.roughnessmap,
  8378. UniformsLib.metalnessmap,
  8379. UniformsLib.fog,
  8380. UniformsLib.lights,
  8381. {
  8382. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8383. roughness: { value: 1.0 },
  8384. metalness: { value: 0.0 },
  8385. envMapIntensity: { value: 1 } // temporary
  8386. }
  8387. ] ),
  8388. vertexShader: ShaderChunk.meshphysical_vert,
  8389. fragmentShader: ShaderChunk.meshphysical_frag
  8390. },
  8391. toon: {
  8392. uniforms: /*@__PURE__*/ mergeUniforms( [
  8393. UniformsLib.common,
  8394. UniformsLib.aomap,
  8395. UniformsLib.lightmap,
  8396. UniformsLib.emissivemap,
  8397. UniformsLib.bumpmap,
  8398. UniformsLib.normalmap,
  8399. UniformsLib.displacementmap,
  8400. UniformsLib.gradientmap,
  8401. UniformsLib.fog,
  8402. UniformsLib.lights,
  8403. {
  8404. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8405. }
  8406. ] ),
  8407. vertexShader: ShaderChunk.meshtoon_vert,
  8408. fragmentShader: ShaderChunk.meshtoon_frag
  8409. },
  8410. matcap: {
  8411. uniforms: /*@__PURE__*/ mergeUniforms( [
  8412. UniformsLib.common,
  8413. UniformsLib.bumpmap,
  8414. UniformsLib.normalmap,
  8415. UniformsLib.displacementmap,
  8416. UniformsLib.fog,
  8417. {
  8418. matcap: { value: null }
  8419. }
  8420. ] ),
  8421. vertexShader: ShaderChunk.meshmatcap_vert,
  8422. fragmentShader: ShaderChunk.meshmatcap_frag
  8423. },
  8424. points: {
  8425. uniforms: /*@__PURE__*/ mergeUniforms( [
  8426. UniformsLib.points,
  8427. UniformsLib.fog
  8428. ] ),
  8429. vertexShader: ShaderChunk.points_vert,
  8430. fragmentShader: ShaderChunk.points_frag
  8431. },
  8432. dashed: {
  8433. uniforms: /*@__PURE__*/ mergeUniforms( [
  8434. UniformsLib.common,
  8435. UniformsLib.fog,
  8436. {
  8437. scale: { value: 1 },
  8438. dashSize: { value: 1 },
  8439. totalSize: { value: 2 }
  8440. }
  8441. ] ),
  8442. vertexShader: ShaderChunk.linedashed_vert,
  8443. fragmentShader: ShaderChunk.linedashed_frag
  8444. },
  8445. depth: {
  8446. uniforms: /*@__PURE__*/ mergeUniforms( [
  8447. UniformsLib.common,
  8448. UniformsLib.displacementmap
  8449. ] ),
  8450. vertexShader: ShaderChunk.depth_vert,
  8451. fragmentShader: ShaderChunk.depth_frag
  8452. },
  8453. normal: {
  8454. uniforms: /*@__PURE__*/ mergeUniforms( [
  8455. UniformsLib.common,
  8456. UniformsLib.bumpmap,
  8457. UniformsLib.normalmap,
  8458. UniformsLib.displacementmap,
  8459. {
  8460. opacity: { value: 1.0 }
  8461. }
  8462. ] ),
  8463. vertexShader: ShaderChunk.meshnormal_vert,
  8464. fragmentShader: ShaderChunk.meshnormal_frag
  8465. },
  8466. sprite: {
  8467. uniforms: /*@__PURE__*/ mergeUniforms( [
  8468. UniformsLib.sprite,
  8469. UniformsLib.fog
  8470. ] ),
  8471. vertexShader: ShaderChunk.sprite_vert,
  8472. fragmentShader: ShaderChunk.sprite_frag
  8473. },
  8474. background: {
  8475. uniforms: {
  8476. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8477. t2D: { value: null },
  8478. backgroundIntensity: { value: 1 }
  8479. },
  8480. vertexShader: ShaderChunk.background_vert,
  8481. fragmentShader: ShaderChunk.background_frag
  8482. },
  8483. backgroundCube: {
  8484. uniforms: {
  8485. envMap: { value: null },
  8486. flipEnvMap: { value: - 1 },
  8487. backgroundBlurriness: { value: 0 },
  8488. backgroundIntensity: { value: 1 }
  8489. },
  8490. vertexShader: ShaderChunk.backgroundCube_vert,
  8491. fragmentShader: ShaderChunk.backgroundCube_frag
  8492. },
  8493. cube: {
  8494. uniforms: {
  8495. tCube: { value: null },
  8496. tFlip: { value: - 1 },
  8497. opacity: { value: 1.0 }
  8498. },
  8499. vertexShader: ShaderChunk.cube_vert,
  8500. fragmentShader: ShaderChunk.cube_frag
  8501. },
  8502. equirect: {
  8503. uniforms: {
  8504. tEquirect: { value: null },
  8505. },
  8506. vertexShader: ShaderChunk.equirect_vert,
  8507. fragmentShader: ShaderChunk.equirect_frag
  8508. },
  8509. distanceRGBA: {
  8510. uniforms: /*@__PURE__*/ mergeUniforms( [
  8511. UniformsLib.common,
  8512. UniformsLib.displacementmap,
  8513. {
  8514. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8515. nearDistance: { value: 1 },
  8516. farDistance: { value: 1000 }
  8517. }
  8518. ] ),
  8519. vertexShader: ShaderChunk.distanceRGBA_vert,
  8520. fragmentShader: ShaderChunk.distanceRGBA_frag
  8521. },
  8522. shadow: {
  8523. uniforms: /*@__PURE__*/ mergeUniforms( [
  8524. UniformsLib.lights,
  8525. UniformsLib.fog,
  8526. {
  8527. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8528. opacity: { value: 1.0 }
  8529. },
  8530. ] ),
  8531. vertexShader: ShaderChunk.shadow_vert,
  8532. fragmentShader: ShaderChunk.shadow_frag
  8533. }
  8534. };
  8535. ShaderLib.physical = {
  8536. uniforms: /*@__PURE__*/ mergeUniforms( [
  8537. ShaderLib.standard.uniforms,
  8538. {
  8539. clearcoat: { value: 0 },
  8540. clearcoatMap: { value: null },
  8541. clearcoatRoughness: { value: 0 },
  8542. clearcoatRoughnessMap: { value: null },
  8543. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8544. clearcoatNormalMap: { value: null },
  8545. iridescence: { value: 0 },
  8546. iridescenceMap: { value: null },
  8547. iridescenceIOR: { value: 1.3 },
  8548. iridescenceThicknessMinimum: { value: 100 },
  8549. iridescenceThicknessMaximum: { value: 400 },
  8550. iridescenceThicknessMap: { value: null },
  8551. sheen: { value: 0 },
  8552. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8553. sheenColorMap: { value: null },
  8554. sheenRoughness: { value: 1 },
  8555. sheenRoughnessMap: { value: null },
  8556. transmission: { value: 0 },
  8557. transmissionMap: { value: null },
  8558. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8559. transmissionSamplerMap: { value: null },
  8560. thickness: { value: 0 },
  8561. thicknessMap: { value: null },
  8562. attenuationDistance: { value: 0 },
  8563. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8564. specularIntensity: { value: 1 },
  8565. specularIntensityMap: { value: null },
  8566. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8567. specularColorMap: { value: null },
  8568. }
  8569. ] ),
  8570. vertexShader: ShaderChunk.meshphysical_vert,
  8571. fragmentShader: ShaderChunk.meshphysical_frag
  8572. };
  8573. const _rgb = { r: 0, b: 0, g: 0 };
  8574. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8575. const clearColor = new Color( 0x000000 );
  8576. let clearAlpha = alpha === true ? 0 : 1;
  8577. let planeMesh;
  8578. let boxMesh;
  8579. let currentBackground = null;
  8580. let currentBackgroundVersion = 0;
  8581. let currentTonemapping = null;
  8582. function render( renderList, scene ) {
  8583. let forceClear = false;
  8584. let background = scene.isScene === true ? scene.background : null;
  8585. if ( background && background.isTexture ) {
  8586. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8587. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8588. }
  8589. // Ignore background in AR
  8590. // TODO: Reconsider this.
  8591. const xr = renderer.xr;
  8592. const session = xr.getSession && xr.getSession();
  8593. if ( session && session.environmentBlendMode === 'additive' ) {
  8594. background = null;
  8595. }
  8596. if ( background === null ) {
  8597. setClear( clearColor, clearAlpha );
  8598. } else if ( background && background.isColor ) {
  8599. setClear( background, 1 );
  8600. forceClear = true;
  8601. }
  8602. if ( renderer.autoClear || forceClear ) {
  8603. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8604. }
  8605. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8606. if ( boxMesh === undefined ) {
  8607. boxMesh = new Mesh(
  8608. new BoxGeometry( 1, 1, 1 ),
  8609. new ShaderMaterial( {
  8610. name: 'BackgroundCubeMaterial',
  8611. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8612. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8613. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8614. side: BackSide,
  8615. depthTest: false,
  8616. depthWrite: false,
  8617. fog: false
  8618. } )
  8619. );
  8620. boxMesh.geometry.deleteAttribute( 'normal' );
  8621. boxMesh.geometry.deleteAttribute( 'uv' );
  8622. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8623. this.matrixWorld.copyPosition( camera.matrixWorld );
  8624. };
  8625. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8626. Object.defineProperty( boxMesh.material, 'envMap', {
  8627. get: function () {
  8628. return this.uniforms.envMap.value;
  8629. }
  8630. } );
  8631. objects.update( boxMesh );
  8632. }
  8633. boxMesh.material.uniforms.envMap.value = background;
  8634. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8635. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8636. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8637. boxMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8638. if ( currentBackground !== background ||
  8639. currentBackgroundVersion !== background.version ||
  8640. currentTonemapping !== renderer.toneMapping ) {
  8641. boxMesh.material.needsUpdate = true;
  8642. currentBackground = background;
  8643. currentBackgroundVersion = background.version;
  8644. currentTonemapping = renderer.toneMapping;
  8645. }
  8646. boxMesh.layers.enableAll();
  8647. // push to the pre-sorted opaque render list
  8648. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8649. } else if ( background && background.isTexture ) {
  8650. if ( planeMesh === undefined ) {
  8651. planeMesh = new Mesh(
  8652. new PlaneGeometry( 2, 2 ),
  8653. new ShaderMaterial( {
  8654. name: 'BackgroundMaterial',
  8655. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8656. vertexShader: ShaderLib.background.vertexShader,
  8657. fragmentShader: ShaderLib.background.fragmentShader,
  8658. side: FrontSide,
  8659. depthTest: false,
  8660. depthWrite: false,
  8661. fog: false
  8662. } )
  8663. );
  8664. planeMesh.geometry.deleteAttribute( 'normal' );
  8665. // add "map" material property so the renderer can evaluate it like for built-in materials
  8666. Object.defineProperty( planeMesh.material, 'map', {
  8667. get: function () {
  8668. return this.uniforms.t2D.value;
  8669. }
  8670. } );
  8671. objects.update( planeMesh );
  8672. }
  8673. planeMesh.material.uniforms.t2D.value = background;
  8674. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8675. planeMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8676. if ( background.matrixAutoUpdate === true ) {
  8677. background.updateMatrix();
  8678. }
  8679. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8680. if ( currentBackground !== background ||
  8681. currentBackgroundVersion !== background.version ||
  8682. currentTonemapping !== renderer.toneMapping ) {
  8683. planeMesh.material.needsUpdate = true;
  8684. currentBackground = background;
  8685. currentBackgroundVersion = background.version;
  8686. currentTonemapping = renderer.toneMapping;
  8687. }
  8688. planeMesh.layers.enableAll();
  8689. // push to the pre-sorted opaque render list
  8690. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8691. }
  8692. }
  8693. function setClear( color, alpha ) {
  8694. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8695. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8696. }
  8697. return {
  8698. getClearColor: function () {
  8699. return clearColor;
  8700. },
  8701. setClearColor: function ( color, alpha = 1 ) {
  8702. clearColor.set( color );
  8703. clearAlpha = alpha;
  8704. setClear( clearColor, clearAlpha );
  8705. },
  8706. getClearAlpha: function () {
  8707. return clearAlpha;
  8708. },
  8709. setClearAlpha: function ( alpha ) {
  8710. clearAlpha = alpha;
  8711. setClear( clearColor, clearAlpha );
  8712. },
  8713. render: render
  8714. };
  8715. }
  8716. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8717. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  8718. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8719. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8720. const bindingStates = {};
  8721. const defaultState = createBindingState( null );
  8722. let currentState = defaultState;
  8723. let forceUpdate = false;
  8724. function setup( object, material, program, geometry, index ) {
  8725. let updateBuffers = false;
  8726. if ( vaoAvailable ) {
  8727. const state = getBindingState( geometry, program, material );
  8728. if ( currentState !== state ) {
  8729. currentState = state;
  8730. bindVertexArrayObject( currentState.object );
  8731. }
  8732. updateBuffers = needsUpdate( object, geometry, program, index );
  8733. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8734. } else {
  8735. const wireframe = ( material.wireframe === true );
  8736. if ( currentState.geometry !== geometry.id ||
  8737. currentState.program !== program.id ||
  8738. currentState.wireframe !== wireframe ) {
  8739. currentState.geometry = geometry.id;
  8740. currentState.program = program.id;
  8741. currentState.wireframe = wireframe;
  8742. updateBuffers = true;
  8743. }
  8744. }
  8745. if ( index !== null ) {
  8746. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  8747. }
  8748. if ( updateBuffers || forceUpdate ) {
  8749. forceUpdate = false;
  8750. setupVertexAttributes( object, material, program, geometry );
  8751. if ( index !== null ) {
  8752. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  8753. }
  8754. }
  8755. }
  8756. function createVertexArrayObject() {
  8757. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8758. return extension.createVertexArrayOES();
  8759. }
  8760. function bindVertexArrayObject( vao ) {
  8761. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8762. return extension.bindVertexArrayOES( vao );
  8763. }
  8764. function deleteVertexArrayObject( vao ) {
  8765. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8766. return extension.deleteVertexArrayOES( vao );
  8767. }
  8768. function getBindingState( geometry, program, material ) {
  8769. const wireframe = ( material.wireframe === true );
  8770. let programMap = bindingStates[ geometry.id ];
  8771. if ( programMap === undefined ) {
  8772. programMap = {};
  8773. bindingStates[ geometry.id ] = programMap;
  8774. }
  8775. let stateMap = programMap[ program.id ];
  8776. if ( stateMap === undefined ) {
  8777. stateMap = {};
  8778. programMap[ program.id ] = stateMap;
  8779. }
  8780. let state = stateMap[ wireframe ];
  8781. if ( state === undefined ) {
  8782. state = createBindingState( createVertexArrayObject() );
  8783. stateMap[ wireframe ] = state;
  8784. }
  8785. return state;
  8786. }
  8787. function createBindingState( vao ) {
  8788. const newAttributes = [];
  8789. const enabledAttributes = [];
  8790. const attributeDivisors = [];
  8791. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8792. newAttributes[ i ] = 0;
  8793. enabledAttributes[ i ] = 0;
  8794. attributeDivisors[ i ] = 0;
  8795. }
  8796. return {
  8797. // for backward compatibility on non-VAO support browser
  8798. geometry: null,
  8799. program: null,
  8800. wireframe: false,
  8801. newAttributes: newAttributes,
  8802. enabledAttributes: enabledAttributes,
  8803. attributeDivisors: attributeDivisors,
  8804. object: vao,
  8805. attributes: {},
  8806. index: null
  8807. };
  8808. }
  8809. function needsUpdate( object, geometry, program, index ) {
  8810. const cachedAttributes = currentState.attributes;
  8811. const geometryAttributes = geometry.attributes;
  8812. let attributesNum = 0;
  8813. const programAttributes = program.getAttributes();
  8814. for ( const name in programAttributes ) {
  8815. const programAttribute = programAttributes[ name ];
  8816. if ( programAttribute.location >= 0 ) {
  8817. const cachedAttribute = cachedAttributes[ name ];
  8818. let geometryAttribute = geometryAttributes[ name ];
  8819. if ( geometryAttribute === undefined ) {
  8820. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8821. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8822. }
  8823. if ( cachedAttribute === undefined ) return true;
  8824. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8825. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8826. attributesNum ++;
  8827. }
  8828. }
  8829. if ( currentState.attributesNum !== attributesNum ) return true;
  8830. if ( currentState.index !== index ) return true;
  8831. return false;
  8832. }
  8833. function saveCache( object, geometry, program, index ) {
  8834. const cache = {};
  8835. const attributes = geometry.attributes;
  8836. let attributesNum = 0;
  8837. const programAttributes = program.getAttributes();
  8838. for ( const name in programAttributes ) {
  8839. const programAttribute = programAttributes[ name ];
  8840. if ( programAttribute.location >= 0 ) {
  8841. let attribute = attributes[ name ];
  8842. if ( attribute === undefined ) {
  8843. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8844. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8845. }
  8846. const data = {};
  8847. data.attribute = attribute;
  8848. if ( attribute && attribute.data ) {
  8849. data.data = attribute.data;
  8850. }
  8851. cache[ name ] = data;
  8852. attributesNum ++;
  8853. }
  8854. }
  8855. currentState.attributes = cache;
  8856. currentState.attributesNum = attributesNum;
  8857. currentState.index = index;
  8858. }
  8859. function initAttributes() {
  8860. const newAttributes = currentState.newAttributes;
  8861. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8862. newAttributes[ i ] = 0;
  8863. }
  8864. }
  8865. function enableAttribute( attribute ) {
  8866. enableAttributeAndDivisor( attribute, 0 );
  8867. }
  8868. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8869. const newAttributes = currentState.newAttributes;
  8870. const enabledAttributes = currentState.enabledAttributes;
  8871. const attributeDivisors = currentState.attributeDivisors;
  8872. newAttributes[ attribute ] = 1;
  8873. if ( enabledAttributes[ attribute ] === 0 ) {
  8874. gl.enableVertexAttribArray( attribute );
  8875. enabledAttributes[ attribute ] = 1;
  8876. }
  8877. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8878. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8879. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8880. attributeDivisors[ attribute ] = meshPerAttribute;
  8881. }
  8882. }
  8883. function disableUnusedAttributes() {
  8884. const newAttributes = currentState.newAttributes;
  8885. const enabledAttributes = currentState.enabledAttributes;
  8886. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8887. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8888. gl.disableVertexAttribArray( i );
  8889. enabledAttributes[ i ] = 0;
  8890. }
  8891. }
  8892. }
  8893. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8894. if ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT ) ) {
  8895. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8896. } else {
  8897. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8898. }
  8899. }
  8900. function setupVertexAttributes( object, material, program, geometry ) {
  8901. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8902. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8903. }
  8904. initAttributes();
  8905. const geometryAttributes = geometry.attributes;
  8906. const programAttributes = program.getAttributes();
  8907. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8908. for ( const name in programAttributes ) {
  8909. const programAttribute = programAttributes[ name ];
  8910. if ( programAttribute.location >= 0 ) {
  8911. let geometryAttribute = geometryAttributes[ name ];
  8912. if ( geometryAttribute === undefined ) {
  8913. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8914. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8915. }
  8916. if ( geometryAttribute !== undefined ) {
  8917. const normalized = geometryAttribute.normalized;
  8918. const size = geometryAttribute.itemSize;
  8919. const attribute = attributes.get( geometryAttribute );
  8920. // TODO Attribute may not be available on context restore
  8921. if ( attribute === undefined ) continue;
  8922. const buffer = attribute.buffer;
  8923. const type = attribute.type;
  8924. const bytesPerElement = attribute.bytesPerElement;
  8925. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8926. const data = geometryAttribute.data;
  8927. const stride = data.stride;
  8928. const offset = geometryAttribute.offset;
  8929. if ( data.isInstancedInterleavedBuffer ) {
  8930. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8931. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8932. }
  8933. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8934. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8935. }
  8936. } else {
  8937. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8938. enableAttribute( programAttribute.location + i );
  8939. }
  8940. }
  8941. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  8942. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8943. vertexAttribPointer(
  8944. programAttribute.location + i,
  8945. size / programAttribute.locationSize,
  8946. type,
  8947. normalized,
  8948. stride * bytesPerElement,
  8949. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8950. );
  8951. }
  8952. } else {
  8953. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8954. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8955. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8956. }
  8957. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8958. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8959. }
  8960. } else {
  8961. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8962. enableAttribute( programAttribute.location + i );
  8963. }
  8964. }
  8965. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  8966. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8967. vertexAttribPointer(
  8968. programAttribute.location + i,
  8969. size / programAttribute.locationSize,
  8970. type,
  8971. normalized,
  8972. size * bytesPerElement,
  8973. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8974. );
  8975. }
  8976. }
  8977. } else if ( materialDefaultAttributeValues !== undefined ) {
  8978. const value = materialDefaultAttributeValues[ name ];
  8979. if ( value !== undefined ) {
  8980. switch ( value.length ) {
  8981. case 2:
  8982. gl.vertexAttrib2fv( programAttribute.location, value );
  8983. break;
  8984. case 3:
  8985. gl.vertexAttrib3fv( programAttribute.location, value );
  8986. break;
  8987. case 4:
  8988. gl.vertexAttrib4fv( programAttribute.location, value );
  8989. break;
  8990. default:
  8991. gl.vertexAttrib1fv( programAttribute.location, value );
  8992. }
  8993. }
  8994. }
  8995. }
  8996. }
  8997. disableUnusedAttributes();
  8998. }
  8999. function dispose() {
  9000. reset();
  9001. for ( const geometryId in bindingStates ) {
  9002. const programMap = bindingStates[ geometryId ];
  9003. for ( const programId in programMap ) {
  9004. const stateMap = programMap[ programId ];
  9005. for ( const wireframe in stateMap ) {
  9006. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9007. delete stateMap[ wireframe ];
  9008. }
  9009. delete programMap[ programId ];
  9010. }
  9011. delete bindingStates[ geometryId ];
  9012. }
  9013. }
  9014. function releaseStatesOfGeometry( geometry ) {
  9015. if ( bindingStates[ geometry.id ] === undefined ) return;
  9016. const programMap = bindingStates[ geometry.id ];
  9017. for ( const programId in programMap ) {
  9018. const stateMap = programMap[ programId ];
  9019. for ( const wireframe in stateMap ) {
  9020. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9021. delete stateMap[ wireframe ];
  9022. }
  9023. delete programMap[ programId ];
  9024. }
  9025. delete bindingStates[ geometry.id ];
  9026. }
  9027. function releaseStatesOfProgram( program ) {
  9028. for ( const geometryId in bindingStates ) {
  9029. const programMap = bindingStates[ geometryId ];
  9030. if ( programMap[ program.id ] === undefined ) continue;
  9031. const stateMap = programMap[ program.id ];
  9032. for ( const wireframe in stateMap ) {
  9033. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9034. delete stateMap[ wireframe ];
  9035. }
  9036. delete programMap[ program.id ];
  9037. }
  9038. }
  9039. function reset() {
  9040. resetDefaultState();
  9041. forceUpdate = true;
  9042. if ( currentState === defaultState ) return;
  9043. currentState = defaultState;
  9044. bindVertexArrayObject( currentState.object );
  9045. }
  9046. // for backward-compatibility
  9047. function resetDefaultState() {
  9048. defaultState.geometry = null;
  9049. defaultState.program = null;
  9050. defaultState.wireframe = false;
  9051. }
  9052. return {
  9053. setup: setup,
  9054. reset: reset,
  9055. resetDefaultState: resetDefaultState,
  9056. dispose: dispose,
  9057. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9058. releaseStatesOfProgram: releaseStatesOfProgram,
  9059. initAttributes: initAttributes,
  9060. enableAttribute: enableAttribute,
  9061. disableUnusedAttributes: disableUnusedAttributes
  9062. };
  9063. }
  9064. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9065. const isWebGL2 = capabilities.isWebGL2;
  9066. let mode;
  9067. function setMode( value ) {
  9068. mode = value;
  9069. }
  9070. function render( start, count ) {
  9071. gl.drawArrays( mode, start, count );
  9072. info.update( count, mode, 1 );
  9073. }
  9074. function renderInstances( start, count, primcount ) {
  9075. if ( primcount === 0 ) return;
  9076. let extension, methodName;
  9077. if ( isWebGL2 ) {
  9078. extension = gl;
  9079. methodName = 'drawArraysInstanced';
  9080. } else {
  9081. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9082. methodName = 'drawArraysInstancedANGLE';
  9083. if ( extension === null ) {
  9084. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9085. return;
  9086. }
  9087. }
  9088. extension[ methodName ]( mode, start, count, primcount );
  9089. info.update( count, mode, primcount );
  9090. }
  9091. //
  9092. this.setMode = setMode;
  9093. this.render = render;
  9094. this.renderInstances = renderInstances;
  9095. }
  9096. function WebGLCapabilities( gl, extensions, parameters ) {
  9097. let maxAnisotropy;
  9098. function getMaxAnisotropy() {
  9099. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9100. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9101. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9102. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9103. } else {
  9104. maxAnisotropy = 0;
  9105. }
  9106. return maxAnisotropy;
  9107. }
  9108. function getMaxPrecision( precision ) {
  9109. if ( precision === 'highp' ) {
  9110. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9111. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9112. return 'highp';
  9113. }
  9114. precision = 'mediump';
  9115. }
  9116. if ( precision === 'mediump' ) {
  9117. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9118. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9119. return 'mediump';
  9120. }
  9121. }
  9122. return 'lowp';
  9123. }
  9124. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  9125. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9126. const maxPrecision = getMaxPrecision( precision );
  9127. if ( maxPrecision !== precision ) {
  9128. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9129. precision = maxPrecision;
  9130. }
  9131. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  9132. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9133. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9134. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9135. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9136. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9137. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9138. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9139. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9140. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9141. const vertexTextures = maxVertexTextures > 0;
  9142. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  9143. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9144. const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
  9145. return {
  9146. isWebGL2: isWebGL2,
  9147. drawBuffers: drawBuffers,
  9148. getMaxAnisotropy: getMaxAnisotropy,
  9149. getMaxPrecision: getMaxPrecision,
  9150. precision: precision,
  9151. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9152. maxTextures: maxTextures,
  9153. maxVertexTextures: maxVertexTextures,
  9154. maxTextureSize: maxTextureSize,
  9155. maxCubemapSize: maxCubemapSize,
  9156. maxAttributes: maxAttributes,
  9157. maxVertexUniforms: maxVertexUniforms,
  9158. maxVaryings: maxVaryings,
  9159. maxFragmentUniforms: maxFragmentUniforms,
  9160. vertexTextures: vertexTextures,
  9161. floatFragmentTextures: floatFragmentTextures,
  9162. floatVertexTextures: floatVertexTextures,
  9163. maxSamples: maxSamples
  9164. };
  9165. }
  9166. function WebGLClipping( properties ) {
  9167. const scope = this;
  9168. let globalState = null,
  9169. numGlobalPlanes = 0,
  9170. localClippingEnabled = false,
  9171. renderingShadows = false;
  9172. const plane = new Plane(),
  9173. viewNormalMatrix = new Matrix3(),
  9174. uniform = { value: null, needsUpdate: false };
  9175. this.uniform = uniform;
  9176. this.numPlanes = 0;
  9177. this.numIntersection = 0;
  9178. this.init = function ( planes, enableLocalClipping ) {
  9179. const enabled =
  9180. planes.length !== 0 ||
  9181. enableLocalClipping ||
  9182. // enable state of previous frame - the clipping code has to
  9183. // run another frame in order to reset the state:
  9184. numGlobalPlanes !== 0 ||
  9185. localClippingEnabled;
  9186. localClippingEnabled = enableLocalClipping;
  9187. numGlobalPlanes = planes.length;
  9188. return enabled;
  9189. };
  9190. this.beginShadows = function () {
  9191. renderingShadows = true;
  9192. projectPlanes( null );
  9193. };
  9194. this.endShadows = function () {
  9195. renderingShadows = false;
  9196. };
  9197. this.setGlobalState = function ( planes, camera ) {
  9198. globalState = projectPlanes( planes, camera, 0 );
  9199. };
  9200. this.setState = function ( material, camera, useCache ) {
  9201. const planes = material.clippingPlanes,
  9202. clipIntersection = material.clipIntersection,
  9203. clipShadows = material.clipShadows;
  9204. const materialProperties = properties.get( material );
  9205. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9206. // there's no local clipping
  9207. if ( renderingShadows ) {
  9208. // there's no global clipping
  9209. projectPlanes( null );
  9210. } else {
  9211. resetGlobalState();
  9212. }
  9213. } else {
  9214. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9215. lGlobal = nGlobal * 4;
  9216. let dstArray = materialProperties.clippingState || null;
  9217. uniform.value = dstArray; // ensure unique state
  9218. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9219. for ( let i = 0; i !== lGlobal; ++ i ) {
  9220. dstArray[ i ] = globalState[ i ];
  9221. }
  9222. materialProperties.clippingState = dstArray;
  9223. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9224. this.numPlanes += nGlobal;
  9225. }
  9226. };
  9227. function resetGlobalState() {
  9228. if ( uniform.value !== globalState ) {
  9229. uniform.value = globalState;
  9230. uniform.needsUpdate = numGlobalPlanes > 0;
  9231. }
  9232. scope.numPlanes = numGlobalPlanes;
  9233. scope.numIntersection = 0;
  9234. }
  9235. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9236. const nPlanes = planes !== null ? planes.length : 0;
  9237. let dstArray = null;
  9238. if ( nPlanes !== 0 ) {
  9239. dstArray = uniform.value;
  9240. if ( skipTransform !== true || dstArray === null ) {
  9241. const flatSize = dstOffset + nPlanes * 4,
  9242. viewMatrix = camera.matrixWorldInverse;
  9243. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9244. if ( dstArray === null || dstArray.length < flatSize ) {
  9245. dstArray = new Float32Array( flatSize );
  9246. }
  9247. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9248. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9249. plane.normal.toArray( dstArray, i4 );
  9250. dstArray[ i4 + 3 ] = plane.constant;
  9251. }
  9252. }
  9253. uniform.value = dstArray;
  9254. uniform.needsUpdate = true;
  9255. }
  9256. scope.numPlanes = nPlanes;
  9257. scope.numIntersection = 0;
  9258. return dstArray;
  9259. }
  9260. }
  9261. function WebGLCubeMaps( renderer ) {
  9262. let cubemaps = new WeakMap();
  9263. function mapTextureMapping( texture, mapping ) {
  9264. if ( mapping === EquirectangularReflectionMapping ) {
  9265. texture.mapping = CubeReflectionMapping;
  9266. } else if ( mapping === EquirectangularRefractionMapping ) {
  9267. texture.mapping = CubeRefractionMapping;
  9268. }
  9269. return texture;
  9270. }
  9271. function get( texture ) {
  9272. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9273. const mapping = texture.mapping;
  9274. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9275. if ( cubemaps.has( texture ) ) {
  9276. const cubemap = cubemaps.get( texture ).texture;
  9277. return mapTextureMapping( cubemap, texture.mapping );
  9278. } else {
  9279. const image = texture.image;
  9280. if ( image && image.height > 0 ) {
  9281. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9282. renderTarget.fromEquirectangularTexture( renderer, texture );
  9283. cubemaps.set( texture, renderTarget );
  9284. texture.addEventListener( 'dispose', onTextureDispose );
  9285. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9286. } else {
  9287. // image not yet ready. try the conversion next frame
  9288. return null;
  9289. }
  9290. }
  9291. }
  9292. }
  9293. return texture;
  9294. }
  9295. function onTextureDispose( event ) {
  9296. const texture = event.target;
  9297. texture.removeEventListener( 'dispose', onTextureDispose );
  9298. const cubemap = cubemaps.get( texture );
  9299. if ( cubemap !== undefined ) {
  9300. cubemaps.delete( texture );
  9301. cubemap.dispose();
  9302. }
  9303. }
  9304. function dispose() {
  9305. cubemaps = new WeakMap();
  9306. }
  9307. return {
  9308. get: get,
  9309. dispose: dispose
  9310. };
  9311. }
  9312. class OrthographicCamera extends Camera {
  9313. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9314. super();
  9315. this.isOrthographicCamera = true;
  9316. this.type = 'OrthographicCamera';
  9317. this.zoom = 1;
  9318. this.view = null;
  9319. this.left = left;
  9320. this.right = right;
  9321. this.top = top;
  9322. this.bottom = bottom;
  9323. this.near = near;
  9324. this.far = far;
  9325. this.updateProjectionMatrix();
  9326. }
  9327. copy( source, recursive ) {
  9328. super.copy( source, recursive );
  9329. this.left = source.left;
  9330. this.right = source.right;
  9331. this.top = source.top;
  9332. this.bottom = source.bottom;
  9333. this.near = source.near;
  9334. this.far = source.far;
  9335. this.zoom = source.zoom;
  9336. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9337. return this;
  9338. }
  9339. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9340. if ( this.view === null ) {
  9341. this.view = {
  9342. enabled: true,
  9343. fullWidth: 1,
  9344. fullHeight: 1,
  9345. offsetX: 0,
  9346. offsetY: 0,
  9347. width: 1,
  9348. height: 1
  9349. };
  9350. }
  9351. this.view.enabled = true;
  9352. this.view.fullWidth = fullWidth;
  9353. this.view.fullHeight = fullHeight;
  9354. this.view.offsetX = x;
  9355. this.view.offsetY = y;
  9356. this.view.width = width;
  9357. this.view.height = height;
  9358. this.updateProjectionMatrix();
  9359. }
  9360. clearViewOffset() {
  9361. if ( this.view !== null ) {
  9362. this.view.enabled = false;
  9363. }
  9364. this.updateProjectionMatrix();
  9365. }
  9366. updateProjectionMatrix() {
  9367. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9368. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9369. const cx = ( this.right + this.left ) / 2;
  9370. const cy = ( this.top + this.bottom ) / 2;
  9371. let left = cx - dx;
  9372. let right = cx + dx;
  9373. let top = cy + dy;
  9374. let bottom = cy - dy;
  9375. if ( this.view !== null && this.view.enabled ) {
  9376. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9377. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9378. left += scaleW * this.view.offsetX;
  9379. right = left + scaleW * this.view.width;
  9380. top -= scaleH * this.view.offsetY;
  9381. bottom = top - scaleH * this.view.height;
  9382. }
  9383. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9384. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9385. }
  9386. toJSON( meta ) {
  9387. const data = super.toJSON( meta );
  9388. data.object.zoom = this.zoom;
  9389. data.object.left = this.left;
  9390. data.object.right = this.right;
  9391. data.object.top = this.top;
  9392. data.object.bottom = this.bottom;
  9393. data.object.near = this.near;
  9394. data.object.far = this.far;
  9395. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9396. return data;
  9397. }
  9398. }
  9399. const LOD_MIN = 4;
  9400. // The standard deviations (radians) associated with the extra mips. These are
  9401. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9402. // geometric shadowing function. These sigma values squared must match the
  9403. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9404. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9405. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9406. // samples and exit early, but not recompile the shader.
  9407. const MAX_SAMPLES = 20;
  9408. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9409. const _clearColor = /*@__PURE__*/ new Color();
  9410. let _oldTarget = null;
  9411. // Golden Ratio
  9412. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9413. const INV_PHI = 1 / PHI;
  9414. // Vertices of a dodecahedron (except the opposites, which represent the
  9415. // same axis), used as axis directions evenly spread on a sphere.
  9416. const _axisDirections = [
  9417. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9418. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9419. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9420. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9421. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9422. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9423. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9424. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9425. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9426. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9427. /**
  9428. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9429. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9430. * blur to be quickly accessed based on material roughness. It is packed into a
  9431. * special CubeUV format that allows us to perform custom interpolation so that
  9432. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9433. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9434. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9435. * higher roughness levels. In this way we maintain resolution to smoothly
  9436. * interpolate diffuse lighting while limiting sampling computation.
  9437. *
  9438. * Paper: Fast, Accurate Image-Based Lighting
  9439. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9440. */
  9441. class PMREMGenerator {
  9442. constructor( renderer ) {
  9443. this._renderer = renderer;
  9444. this._pingPongRenderTarget = null;
  9445. this._lodMax = 0;
  9446. this._cubeSize = 0;
  9447. this._lodPlanes = [];
  9448. this._sizeLods = [];
  9449. this._sigmas = [];
  9450. this._blurMaterial = null;
  9451. this._cubemapMaterial = null;
  9452. this._equirectMaterial = null;
  9453. this._compileMaterial( this._blurMaterial );
  9454. }
  9455. /**
  9456. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9457. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9458. * in radians to be applied to the scene before PMREM generation. Optional near
  9459. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9460. * is placed at the origin).
  9461. */
  9462. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9463. _oldTarget = this._renderer.getRenderTarget();
  9464. this._setSize( 256 );
  9465. const cubeUVRenderTarget = this._allocateTargets();
  9466. cubeUVRenderTarget.depthBuffer = true;
  9467. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9468. if ( sigma > 0 ) {
  9469. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9470. }
  9471. this._applyPMREM( cubeUVRenderTarget );
  9472. this._cleanup( cubeUVRenderTarget );
  9473. return cubeUVRenderTarget;
  9474. }
  9475. /**
  9476. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9477. * or HDR. The ideal input image size is 1k (1024 x 512),
  9478. * as this matches best with the 256 x 256 cubemap output.
  9479. */
  9480. fromEquirectangular( equirectangular, renderTarget = null ) {
  9481. return this._fromTexture( equirectangular, renderTarget );
  9482. }
  9483. /**
  9484. * Generates a PMREM from an cubemap texture, which can be either LDR
  9485. * or HDR. The ideal input cube size is 256 x 256,
  9486. * as this matches best with the 256 x 256 cubemap output.
  9487. */
  9488. fromCubemap( cubemap, renderTarget = null ) {
  9489. return this._fromTexture( cubemap, renderTarget );
  9490. }
  9491. /**
  9492. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9493. * your texture's network fetch for increased concurrency.
  9494. */
  9495. compileCubemapShader() {
  9496. if ( this._cubemapMaterial === null ) {
  9497. this._cubemapMaterial = _getCubemapMaterial();
  9498. this._compileMaterial( this._cubemapMaterial );
  9499. }
  9500. }
  9501. /**
  9502. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9503. * your texture's network fetch for increased concurrency.
  9504. */
  9505. compileEquirectangularShader() {
  9506. if ( this._equirectMaterial === null ) {
  9507. this._equirectMaterial = _getEquirectMaterial();
  9508. this._compileMaterial( this._equirectMaterial );
  9509. }
  9510. }
  9511. /**
  9512. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9513. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9514. * one of them will cause any others to also become unusable.
  9515. */
  9516. dispose() {
  9517. this._dispose();
  9518. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9519. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9520. }
  9521. // private interface
  9522. _setSize( cubeSize ) {
  9523. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9524. this._cubeSize = Math.pow( 2, this._lodMax );
  9525. }
  9526. _dispose() {
  9527. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9528. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9529. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9530. this._lodPlanes[ i ].dispose();
  9531. }
  9532. }
  9533. _cleanup( outputTarget ) {
  9534. this._renderer.setRenderTarget( _oldTarget );
  9535. outputTarget.scissorTest = false;
  9536. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9537. }
  9538. _fromTexture( texture, renderTarget ) {
  9539. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9540. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9541. } else { // Equirectangular
  9542. this._setSize( texture.image.width / 4 );
  9543. }
  9544. _oldTarget = this._renderer.getRenderTarget();
  9545. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9546. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9547. this._applyPMREM( cubeUVRenderTarget );
  9548. this._cleanup( cubeUVRenderTarget );
  9549. return cubeUVRenderTarget;
  9550. }
  9551. _allocateTargets() {
  9552. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9553. const height = 4 * this._cubeSize;
  9554. const params = {
  9555. magFilter: LinearFilter,
  9556. minFilter: LinearFilter,
  9557. generateMipmaps: false,
  9558. type: HalfFloatType,
  9559. format: RGBAFormat,
  9560. encoding: LinearEncoding,
  9561. depthBuffer: false
  9562. };
  9563. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9564. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9565. if ( this._pingPongRenderTarget !== null ) {
  9566. this._dispose();
  9567. }
  9568. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9569. const { _lodMax } = this;
  9570. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9571. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9572. }
  9573. return cubeUVRenderTarget;
  9574. }
  9575. _compileMaterial( material ) {
  9576. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9577. this._renderer.compile( tmpMesh, _flatCamera );
  9578. }
  9579. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9580. const fov = 90;
  9581. const aspect = 1;
  9582. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9583. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9584. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9585. const renderer = this._renderer;
  9586. const originalAutoClear = renderer.autoClear;
  9587. const toneMapping = renderer.toneMapping;
  9588. renderer.getClearColor( _clearColor );
  9589. renderer.toneMapping = NoToneMapping;
  9590. renderer.autoClear = false;
  9591. const backgroundMaterial = new MeshBasicMaterial( {
  9592. name: 'PMREM.Background',
  9593. side: BackSide,
  9594. depthWrite: false,
  9595. depthTest: false,
  9596. } );
  9597. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9598. let useSolidColor = false;
  9599. const background = scene.background;
  9600. if ( background ) {
  9601. if ( background.isColor ) {
  9602. backgroundMaterial.color.copy( background );
  9603. scene.background = null;
  9604. useSolidColor = true;
  9605. }
  9606. } else {
  9607. backgroundMaterial.color.copy( _clearColor );
  9608. useSolidColor = true;
  9609. }
  9610. for ( let i = 0; i < 6; i ++ ) {
  9611. const col = i % 3;
  9612. if ( col === 0 ) {
  9613. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9614. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9615. } else if ( col === 1 ) {
  9616. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9617. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9618. } else {
  9619. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9620. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9621. }
  9622. const size = this._cubeSize;
  9623. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9624. renderer.setRenderTarget( cubeUVRenderTarget );
  9625. if ( useSolidColor ) {
  9626. renderer.render( backgroundBox, cubeCamera );
  9627. }
  9628. renderer.render( scene, cubeCamera );
  9629. }
  9630. backgroundBox.geometry.dispose();
  9631. backgroundBox.material.dispose();
  9632. renderer.toneMapping = toneMapping;
  9633. renderer.autoClear = originalAutoClear;
  9634. scene.background = background;
  9635. }
  9636. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9637. const renderer = this._renderer;
  9638. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9639. if ( isCubeTexture ) {
  9640. if ( this._cubemapMaterial === null ) {
  9641. this._cubemapMaterial = _getCubemapMaterial();
  9642. }
  9643. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9644. } else {
  9645. if ( this._equirectMaterial === null ) {
  9646. this._equirectMaterial = _getEquirectMaterial();
  9647. }
  9648. }
  9649. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9650. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9651. const uniforms = material.uniforms;
  9652. uniforms[ 'envMap' ].value = texture;
  9653. const size = this._cubeSize;
  9654. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9655. renderer.setRenderTarget( cubeUVRenderTarget );
  9656. renderer.render( mesh, _flatCamera );
  9657. }
  9658. _applyPMREM( cubeUVRenderTarget ) {
  9659. const renderer = this._renderer;
  9660. const autoClear = renderer.autoClear;
  9661. renderer.autoClear = false;
  9662. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9663. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9664. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9665. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9666. }
  9667. renderer.autoClear = autoClear;
  9668. }
  9669. /**
  9670. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9671. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9672. * the blur latitudinally (around the poles), and then longitudinally (towards
  9673. * the poles) to approximate the orthogonally-separable blur. It is least
  9674. * accurate at the poles, but still does a decent job.
  9675. */
  9676. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9677. const pingPongRenderTarget = this._pingPongRenderTarget;
  9678. this._halfBlur(
  9679. cubeUVRenderTarget,
  9680. pingPongRenderTarget,
  9681. lodIn,
  9682. lodOut,
  9683. sigma,
  9684. 'latitudinal',
  9685. poleAxis );
  9686. this._halfBlur(
  9687. pingPongRenderTarget,
  9688. cubeUVRenderTarget,
  9689. lodOut,
  9690. lodOut,
  9691. sigma,
  9692. 'longitudinal',
  9693. poleAxis );
  9694. }
  9695. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9696. const renderer = this._renderer;
  9697. const blurMaterial = this._blurMaterial;
  9698. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9699. console.error(
  9700. 'blur direction must be either latitudinal or longitudinal!' );
  9701. }
  9702. // Number of standard deviations at which to cut off the discrete approximation.
  9703. const STANDARD_DEVIATIONS = 3;
  9704. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9705. const blurUniforms = blurMaterial.uniforms;
  9706. const pixels = this._sizeLods[ lodIn ] - 1;
  9707. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9708. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9709. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9710. if ( samples > MAX_SAMPLES ) {
  9711. console.warn( `sigmaRadians, ${
  9712. sigmaRadians}, is too large and will clip, as it requested ${
  9713. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9714. }
  9715. const weights = [];
  9716. let sum = 0;
  9717. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9718. const x = i / sigmaPixels;
  9719. const weight = Math.exp( - x * x / 2 );
  9720. weights.push( weight );
  9721. if ( i === 0 ) {
  9722. sum += weight;
  9723. } else if ( i < samples ) {
  9724. sum += 2 * weight;
  9725. }
  9726. }
  9727. for ( let i = 0; i < weights.length; i ++ ) {
  9728. weights[ i ] = weights[ i ] / sum;
  9729. }
  9730. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9731. blurUniforms[ 'samples' ].value = samples;
  9732. blurUniforms[ 'weights' ].value = weights;
  9733. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9734. if ( poleAxis ) {
  9735. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9736. }
  9737. const { _lodMax } = this;
  9738. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9739. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9740. const outputSize = this._sizeLods[ lodOut ];
  9741. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9742. const y = 4 * ( this._cubeSize - outputSize );
  9743. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9744. renderer.setRenderTarget( targetOut );
  9745. renderer.render( blurMesh, _flatCamera );
  9746. }
  9747. }
  9748. function _createPlanes( lodMax ) {
  9749. const lodPlanes = [];
  9750. const sizeLods = [];
  9751. const sigmas = [];
  9752. let lod = lodMax;
  9753. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9754. for ( let i = 0; i < totalLods; i ++ ) {
  9755. const sizeLod = Math.pow( 2, lod );
  9756. sizeLods.push( sizeLod );
  9757. let sigma = 1.0 / sizeLod;
  9758. if ( i > lodMax - LOD_MIN ) {
  9759. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9760. } else if ( i === 0 ) {
  9761. sigma = 0;
  9762. }
  9763. sigmas.push( sigma );
  9764. const texelSize = 1.0 / ( sizeLod - 2 );
  9765. const min = - texelSize;
  9766. const max = 1 + texelSize;
  9767. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9768. const cubeFaces = 6;
  9769. const vertices = 6;
  9770. const positionSize = 3;
  9771. const uvSize = 2;
  9772. const faceIndexSize = 1;
  9773. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9774. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9775. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9776. for ( let face = 0; face < cubeFaces; face ++ ) {
  9777. const x = ( face % 3 ) * 2 / 3 - 1;
  9778. const y = face > 2 ? 0 : - 1;
  9779. const coordinates = [
  9780. x, y, 0,
  9781. x + 2 / 3, y, 0,
  9782. x + 2 / 3, y + 1, 0,
  9783. x, y, 0,
  9784. x + 2 / 3, y + 1, 0,
  9785. x, y + 1, 0
  9786. ];
  9787. position.set( coordinates, positionSize * vertices * face );
  9788. uv.set( uv1, uvSize * vertices * face );
  9789. const fill = [ face, face, face, face, face, face ];
  9790. faceIndex.set( fill, faceIndexSize * vertices * face );
  9791. }
  9792. const planes = new BufferGeometry();
  9793. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9794. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9795. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9796. lodPlanes.push( planes );
  9797. if ( lod > LOD_MIN ) {
  9798. lod --;
  9799. }
  9800. }
  9801. return { lodPlanes, sizeLods, sigmas };
  9802. }
  9803. function _createRenderTarget( width, height, params ) {
  9804. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9805. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9806. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9807. cubeUVRenderTarget.scissorTest = true;
  9808. return cubeUVRenderTarget;
  9809. }
  9810. function _setViewport( target, x, y, width, height ) {
  9811. target.viewport.set( x, y, width, height );
  9812. target.scissor.set( x, y, width, height );
  9813. }
  9814. function _getBlurShader( lodMax, width, height ) {
  9815. const weights = new Float32Array( MAX_SAMPLES );
  9816. const poleAxis = new Vector3( 0, 1, 0 );
  9817. const shaderMaterial = new ShaderMaterial( {
  9818. name: 'SphericalGaussianBlur',
  9819. defines: {
  9820. 'n': MAX_SAMPLES,
  9821. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9822. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9823. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9824. },
  9825. uniforms: {
  9826. 'envMap': { value: null },
  9827. 'samples': { value: 1 },
  9828. 'weights': { value: weights },
  9829. 'latitudinal': { value: false },
  9830. 'dTheta': { value: 0 },
  9831. 'mipInt': { value: 0 },
  9832. 'poleAxis': { value: poleAxis }
  9833. },
  9834. vertexShader: _getCommonVertexShader(),
  9835. fragmentShader: /* glsl */`
  9836. precision mediump float;
  9837. precision mediump int;
  9838. varying vec3 vOutputDirection;
  9839. uniform sampler2D envMap;
  9840. uniform int samples;
  9841. uniform float weights[ n ];
  9842. uniform bool latitudinal;
  9843. uniform float dTheta;
  9844. uniform float mipInt;
  9845. uniform vec3 poleAxis;
  9846. #define ENVMAP_TYPE_CUBE_UV
  9847. #include <cube_uv_reflection_fragment>
  9848. vec3 getSample( float theta, vec3 axis ) {
  9849. float cosTheta = cos( theta );
  9850. // Rodrigues' axis-angle rotation
  9851. vec3 sampleDirection = vOutputDirection * cosTheta
  9852. + cross( axis, vOutputDirection ) * sin( theta )
  9853. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9854. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9855. }
  9856. void main() {
  9857. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9858. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9859. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9860. }
  9861. axis = normalize( axis );
  9862. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9863. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9864. for ( int i = 1; i < n; i++ ) {
  9865. if ( i >= samples ) {
  9866. break;
  9867. }
  9868. float theta = dTheta * float( i );
  9869. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9870. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9871. }
  9872. }
  9873. `,
  9874. blending: NoBlending,
  9875. depthTest: false,
  9876. depthWrite: false
  9877. } );
  9878. return shaderMaterial;
  9879. }
  9880. function _getEquirectMaterial() {
  9881. return new ShaderMaterial( {
  9882. name: 'EquirectangularToCubeUV',
  9883. uniforms: {
  9884. 'envMap': { value: null }
  9885. },
  9886. vertexShader: _getCommonVertexShader(),
  9887. fragmentShader: /* glsl */`
  9888. precision mediump float;
  9889. precision mediump int;
  9890. varying vec3 vOutputDirection;
  9891. uniform sampler2D envMap;
  9892. #include <common>
  9893. void main() {
  9894. vec3 outputDirection = normalize( vOutputDirection );
  9895. vec2 uv = equirectUv( outputDirection );
  9896. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9897. }
  9898. `,
  9899. blending: NoBlending,
  9900. depthTest: false,
  9901. depthWrite: false
  9902. } );
  9903. }
  9904. function _getCubemapMaterial() {
  9905. return new ShaderMaterial( {
  9906. name: 'CubemapToCubeUV',
  9907. uniforms: {
  9908. 'envMap': { value: null },
  9909. 'flipEnvMap': { value: - 1 }
  9910. },
  9911. vertexShader: _getCommonVertexShader(),
  9912. fragmentShader: /* glsl */`
  9913. precision mediump float;
  9914. precision mediump int;
  9915. uniform float flipEnvMap;
  9916. varying vec3 vOutputDirection;
  9917. uniform samplerCube envMap;
  9918. void main() {
  9919. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9920. }
  9921. `,
  9922. blending: NoBlending,
  9923. depthTest: false,
  9924. depthWrite: false
  9925. } );
  9926. }
  9927. function _getCommonVertexShader() {
  9928. return /* glsl */`
  9929. precision mediump float;
  9930. precision mediump int;
  9931. attribute float faceIndex;
  9932. varying vec3 vOutputDirection;
  9933. // RH coordinate system; PMREM face-indexing convention
  9934. vec3 getDirection( vec2 uv, float face ) {
  9935. uv = 2.0 * uv - 1.0;
  9936. vec3 direction = vec3( uv, 1.0 );
  9937. if ( face == 0.0 ) {
  9938. direction = direction.zyx; // ( 1, v, u ) pos x
  9939. } else if ( face == 1.0 ) {
  9940. direction = direction.xzy;
  9941. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9942. } else if ( face == 2.0 ) {
  9943. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9944. } else if ( face == 3.0 ) {
  9945. direction = direction.zyx;
  9946. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9947. } else if ( face == 4.0 ) {
  9948. direction = direction.xzy;
  9949. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9950. } else if ( face == 5.0 ) {
  9951. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9952. }
  9953. return direction;
  9954. }
  9955. void main() {
  9956. vOutputDirection = getDirection( uv, faceIndex );
  9957. gl_Position = vec4( position, 1.0 );
  9958. }
  9959. `;
  9960. }
  9961. function WebGLCubeUVMaps( renderer ) {
  9962. let cubeUVmaps = new WeakMap();
  9963. let pmremGenerator = null;
  9964. function get( texture ) {
  9965. if ( texture && texture.isTexture ) {
  9966. const mapping = texture.mapping;
  9967. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9968. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9969. // equirect/cube map to cubeUV conversion
  9970. if ( isEquirectMap || isCubeMap ) {
  9971. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  9972. texture.needsPMREMUpdate = false;
  9973. let renderTarget = cubeUVmaps.get( texture );
  9974. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9975. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  9976. cubeUVmaps.set( texture, renderTarget );
  9977. return renderTarget.texture;
  9978. } else {
  9979. if ( cubeUVmaps.has( texture ) ) {
  9980. return cubeUVmaps.get( texture ).texture;
  9981. } else {
  9982. const image = texture.image;
  9983. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9984. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9985. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9986. cubeUVmaps.set( texture, renderTarget );
  9987. texture.addEventListener( 'dispose', onTextureDispose );
  9988. return renderTarget.texture;
  9989. } else {
  9990. // image not yet ready. try the conversion next frame
  9991. return null;
  9992. }
  9993. }
  9994. }
  9995. }
  9996. }
  9997. return texture;
  9998. }
  9999. function isCubeTextureComplete( image ) {
  10000. let count = 0;
  10001. const length = 6;
  10002. for ( let i = 0; i < length; i ++ ) {
  10003. if ( image[ i ] !== undefined ) count ++;
  10004. }
  10005. return count === length;
  10006. }
  10007. function onTextureDispose( event ) {
  10008. const texture = event.target;
  10009. texture.removeEventListener( 'dispose', onTextureDispose );
  10010. const cubemapUV = cubeUVmaps.get( texture );
  10011. if ( cubemapUV !== undefined ) {
  10012. cubeUVmaps.delete( texture );
  10013. cubemapUV.dispose();
  10014. }
  10015. }
  10016. function dispose() {
  10017. cubeUVmaps = new WeakMap();
  10018. if ( pmremGenerator !== null ) {
  10019. pmremGenerator.dispose();
  10020. pmremGenerator = null;
  10021. }
  10022. }
  10023. return {
  10024. get: get,
  10025. dispose: dispose
  10026. };
  10027. }
  10028. function WebGLExtensions( gl ) {
  10029. const extensions = {};
  10030. function getExtension( name ) {
  10031. if ( extensions[ name ] !== undefined ) {
  10032. return extensions[ name ];
  10033. }
  10034. let extension;
  10035. switch ( name ) {
  10036. case 'WEBGL_depth_texture':
  10037. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10038. break;
  10039. case 'EXT_texture_filter_anisotropic':
  10040. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10041. break;
  10042. case 'WEBGL_compressed_texture_s3tc':
  10043. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10044. break;
  10045. case 'WEBGL_compressed_texture_pvrtc':
  10046. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10047. break;
  10048. default:
  10049. extension = gl.getExtension( name );
  10050. }
  10051. extensions[ name ] = extension;
  10052. return extension;
  10053. }
  10054. return {
  10055. has: function ( name ) {
  10056. return getExtension( name ) !== null;
  10057. },
  10058. init: function ( capabilities ) {
  10059. if ( capabilities.isWebGL2 ) {
  10060. getExtension( 'EXT_color_buffer_float' );
  10061. } else {
  10062. getExtension( 'WEBGL_depth_texture' );
  10063. getExtension( 'OES_texture_float' );
  10064. getExtension( 'OES_texture_half_float' );
  10065. getExtension( 'OES_texture_half_float_linear' );
  10066. getExtension( 'OES_standard_derivatives' );
  10067. getExtension( 'OES_element_index_uint' );
  10068. getExtension( 'OES_vertex_array_object' );
  10069. getExtension( 'ANGLE_instanced_arrays' );
  10070. }
  10071. getExtension( 'OES_texture_float_linear' );
  10072. getExtension( 'EXT_color_buffer_half_float' );
  10073. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10074. },
  10075. get: function ( name ) {
  10076. const extension = getExtension( name );
  10077. if ( extension === null ) {
  10078. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10079. }
  10080. return extension;
  10081. }
  10082. };
  10083. }
  10084. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10085. const geometries = {};
  10086. const wireframeAttributes = new WeakMap();
  10087. function onGeometryDispose( event ) {
  10088. const geometry = event.target;
  10089. if ( geometry.index !== null ) {
  10090. attributes.remove( geometry.index );
  10091. }
  10092. for ( const name in geometry.attributes ) {
  10093. attributes.remove( geometry.attributes[ name ] );
  10094. }
  10095. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10096. delete geometries[ geometry.id ];
  10097. const attribute = wireframeAttributes.get( geometry );
  10098. if ( attribute ) {
  10099. attributes.remove( attribute );
  10100. wireframeAttributes.delete( geometry );
  10101. }
  10102. bindingStates.releaseStatesOfGeometry( geometry );
  10103. if ( geometry.isInstancedBufferGeometry === true ) {
  10104. delete geometry._maxInstanceCount;
  10105. }
  10106. //
  10107. info.memory.geometries --;
  10108. }
  10109. function get( object, geometry ) {
  10110. if ( geometries[ geometry.id ] === true ) return geometry;
  10111. geometry.addEventListener( 'dispose', onGeometryDispose );
  10112. geometries[ geometry.id ] = true;
  10113. info.memory.geometries ++;
  10114. return geometry;
  10115. }
  10116. function update( geometry ) {
  10117. const geometryAttributes = geometry.attributes;
  10118. // Updating index buffer in VAO now. See WebGLBindingStates.
  10119. for ( const name in geometryAttributes ) {
  10120. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10121. }
  10122. // morph targets
  10123. const morphAttributes = geometry.morphAttributes;
  10124. for ( const name in morphAttributes ) {
  10125. const array = morphAttributes[ name ];
  10126. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10127. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10128. }
  10129. }
  10130. }
  10131. function updateWireframeAttribute( geometry ) {
  10132. const indices = [];
  10133. const geometryIndex = geometry.index;
  10134. const geometryPosition = geometry.attributes.position;
  10135. let version = 0;
  10136. if ( geometryIndex !== null ) {
  10137. const array = geometryIndex.array;
  10138. version = geometryIndex.version;
  10139. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10140. const a = array[ i + 0 ];
  10141. const b = array[ i + 1 ];
  10142. const c = array[ i + 2 ];
  10143. indices.push( a, b, b, c, c, a );
  10144. }
  10145. } else {
  10146. const array = geometryPosition.array;
  10147. version = geometryPosition.version;
  10148. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10149. const a = i + 0;
  10150. const b = i + 1;
  10151. const c = i + 2;
  10152. indices.push( a, b, b, c, c, a );
  10153. }
  10154. }
  10155. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10156. attribute.version = version;
  10157. // Updating index buffer in VAO now. See WebGLBindingStates
  10158. //
  10159. const previousAttribute = wireframeAttributes.get( geometry );
  10160. if ( previousAttribute ) attributes.remove( previousAttribute );
  10161. //
  10162. wireframeAttributes.set( geometry, attribute );
  10163. }
  10164. function getWireframeAttribute( geometry ) {
  10165. const currentAttribute = wireframeAttributes.get( geometry );
  10166. if ( currentAttribute ) {
  10167. const geometryIndex = geometry.index;
  10168. if ( geometryIndex !== null ) {
  10169. // if the attribute is obsolete, create a new one
  10170. if ( currentAttribute.version < geometryIndex.version ) {
  10171. updateWireframeAttribute( geometry );
  10172. }
  10173. }
  10174. } else {
  10175. updateWireframeAttribute( geometry );
  10176. }
  10177. return wireframeAttributes.get( geometry );
  10178. }
  10179. return {
  10180. get: get,
  10181. update: update,
  10182. getWireframeAttribute: getWireframeAttribute
  10183. };
  10184. }
  10185. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10186. const isWebGL2 = capabilities.isWebGL2;
  10187. let mode;
  10188. function setMode( value ) {
  10189. mode = value;
  10190. }
  10191. let type, bytesPerElement;
  10192. function setIndex( value ) {
  10193. type = value.type;
  10194. bytesPerElement = value.bytesPerElement;
  10195. }
  10196. function render( start, count ) {
  10197. gl.drawElements( mode, count, type, start * bytesPerElement );
  10198. info.update( count, mode, 1 );
  10199. }
  10200. function renderInstances( start, count, primcount ) {
  10201. if ( primcount === 0 ) return;
  10202. let extension, methodName;
  10203. if ( isWebGL2 ) {
  10204. extension = gl;
  10205. methodName = 'drawElementsInstanced';
  10206. } else {
  10207. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10208. methodName = 'drawElementsInstancedANGLE';
  10209. if ( extension === null ) {
  10210. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10211. return;
  10212. }
  10213. }
  10214. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10215. info.update( count, mode, primcount );
  10216. }
  10217. //
  10218. this.setMode = setMode;
  10219. this.setIndex = setIndex;
  10220. this.render = render;
  10221. this.renderInstances = renderInstances;
  10222. }
  10223. function WebGLInfo( gl ) {
  10224. const memory = {
  10225. geometries: 0,
  10226. textures: 0
  10227. };
  10228. const render = {
  10229. frame: 0,
  10230. calls: 0,
  10231. triangles: 0,
  10232. points: 0,
  10233. lines: 0
  10234. };
  10235. function update( count, mode, instanceCount ) {
  10236. render.calls ++;
  10237. switch ( mode ) {
  10238. case gl.TRIANGLES:
  10239. render.triangles += instanceCount * ( count / 3 );
  10240. break;
  10241. case gl.LINES:
  10242. render.lines += instanceCount * ( count / 2 );
  10243. break;
  10244. case gl.LINE_STRIP:
  10245. render.lines += instanceCount * ( count - 1 );
  10246. break;
  10247. case gl.LINE_LOOP:
  10248. render.lines += instanceCount * count;
  10249. break;
  10250. case gl.POINTS:
  10251. render.points += instanceCount * count;
  10252. break;
  10253. default:
  10254. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10255. break;
  10256. }
  10257. }
  10258. function reset() {
  10259. render.frame ++;
  10260. render.calls = 0;
  10261. render.triangles = 0;
  10262. render.points = 0;
  10263. render.lines = 0;
  10264. }
  10265. return {
  10266. memory: memory,
  10267. render: render,
  10268. programs: null,
  10269. autoReset: true,
  10270. reset: reset,
  10271. update: update
  10272. };
  10273. }
  10274. function numericalSort( a, b ) {
  10275. return a[ 0 ] - b[ 0 ];
  10276. }
  10277. function absNumericalSort( a, b ) {
  10278. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10279. }
  10280. function WebGLMorphtargets( gl, capabilities, textures ) {
  10281. const influencesList = {};
  10282. const morphInfluences = new Float32Array( 8 );
  10283. const morphTextures = new WeakMap();
  10284. const morph = new Vector4();
  10285. const workInfluences = [];
  10286. for ( let i = 0; i < 8; i ++ ) {
  10287. workInfluences[ i ] = [ i, 0 ];
  10288. }
  10289. function update( object, geometry, program ) {
  10290. const objectInfluences = object.morphTargetInfluences;
  10291. if ( capabilities.isWebGL2 === true ) {
  10292. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10293. // into an array of data textures. Each layer represents a single morph target.
  10294. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10295. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10296. let entry = morphTextures.get( geometry );
  10297. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10298. if ( entry !== undefined ) entry.texture.dispose();
  10299. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10300. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10301. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10302. const morphTargets = geometry.morphAttributes.position || [];
  10303. const morphNormals = geometry.morphAttributes.normal || [];
  10304. const morphColors = geometry.morphAttributes.color || [];
  10305. let vertexDataCount = 0;
  10306. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10307. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10308. if ( hasMorphColors === true ) vertexDataCount = 3;
  10309. let width = geometry.attributes.position.count * vertexDataCount;
  10310. let height = 1;
  10311. if ( width > capabilities.maxTextureSize ) {
  10312. height = Math.ceil( width / capabilities.maxTextureSize );
  10313. width = capabilities.maxTextureSize;
  10314. }
  10315. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10316. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10317. texture.type = FloatType;
  10318. texture.needsUpdate = true;
  10319. // fill buffer
  10320. const vertexDataStride = vertexDataCount * 4;
  10321. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10322. const morphTarget = morphTargets[ i ];
  10323. const morphNormal = morphNormals[ i ];
  10324. const morphColor = morphColors[ i ];
  10325. const offset = width * height * 4 * i;
  10326. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10327. const stride = j * vertexDataStride;
  10328. if ( hasMorphPosition === true ) {
  10329. morph.fromBufferAttribute( morphTarget, j );
  10330. buffer[ offset + stride + 0 ] = morph.x;
  10331. buffer[ offset + stride + 1 ] = morph.y;
  10332. buffer[ offset + stride + 2 ] = morph.z;
  10333. buffer[ offset + stride + 3 ] = 0;
  10334. }
  10335. if ( hasMorphNormals === true ) {
  10336. morph.fromBufferAttribute( morphNormal, j );
  10337. buffer[ offset + stride + 4 ] = morph.x;
  10338. buffer[ offset + stride + 5 ] = morph.y;
  10339. buffer[ offset + stride + 6 ] = morph.z;
  10340. buffer[ offset + stride + 7 ] = 0;
  10341. }
  10342. if ( hasMorphColors === true ) {
  10343. morph.fromBufferAttribute( morphColor, j );
  10344. buffer[ offset + stride + 8 ] = morph.x;
  10345. buffer[ offset + stride + 9 ] = morph.y;
  10346. buffer[ offset + stride + 10 ] = morph.z;
  10347. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10348. }
  10349. }
  10350. }
  10351. entry = {
  10352. count: morphTargetsCount,
  10353. texture: texture,
  10354. size: new Vector2( width, height )
  10355. };
  10356. morphTextures.set( geometry, entry );
  10357. function disposeTexture() {
  10358. texture.dispose();
  10359. morphTextures.delete( geometry );
  10360. geometry.removeEventListener( 'dispose', disposeTexture );
  10361. }
  10362. geometry.addEventListener( 'dispose', disposeTexture );
  10363. }
  10364. //
  10365. let morphInfluencesSum = 0;
  10366. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10367. morphInfluencesSum += objectInfluences[ i ];
  10368. }
  10369. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10370. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10371. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10372. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10373. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10374. } else {
  10375. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10376. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10377. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10378. let influences = influencesList[ geometry.id ];
  10379. if ( influences === undefined || influences.length !== length ) {
  10380. // initialise list
  10381. influences = [];
  10382. for ( let i = 0; i < length; i ++ ) {
  10383. influences[ i ] = [ i, 0 ];
  10384. }
  10385. influencesList[ geometry.id ] = influences;
  10386. }
  10387. // Collect influences
  10388. for ( let i = 0; i < length; i ++ ) {
  10389. const influence = influences[ i ];
  10390. influence[ 0 ] = i;
  10391. influence[ 1 ] = objectInfluences[ i ];
  10392. }
  10393. influences.sort( absNumericalSort );
  10394. for ( let i = 0; i < 8; i ++ ) {
  10395. if ( i < length && influences[ i ][ 1 ] ) {
  10396. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10397. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10398. } else {
  10399. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10400. workInfluences[ i ][ 1 ] = 0;
  10401. }
  10402. }
  10403. workInfluences.sort( numericalSort );
  10404. const morphTargets = geometry.morphAttributes.position;
  10405. const morphNormals = geometry.morphAttributes.normal;
  10406. let morphInfluencesSum = 0;
  10407. for ( let i = 0; i < 8; i ++ ) {
  10408. const influence = workInfluences[ i ];
  10409. const index = influence[ 0 ];
  10410. const value = influence[ 1 ];
  10411. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10412. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10413. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10414. }
  10415. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10416. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10417. }
  10418. morphInfluences[ i ] = value;
  10419. morphInfluencesSum += value;
  10420. } else {
  10421. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10422. geometry.deleteAttribute( 'morphTarget' + i );
  10423. }
  10424. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10425. geometry.deleteAttribute( 'morphNormal' + i );
  10426. }
  10427. morphInfluences[ i ] = 0;
  10428. }
  10429. }
  10430. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10431. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10432. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10433. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10434. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10435. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10436. }
  10437. }
  10438. return {
  10439. update: update
  10440. };
  10441. }
  10442. function WebGLObjects( gl, geometries, attributes, info ) {
  10443. let updateMap = new WeakMap();
  10444. function update( object ) {
  10445. const frame = info.render.frame;
  10446. const geometry = object.geometry;
  10447. const buffergeometry = geometries.get( object, geometry );
  10448. // Update once per frame
  10449. if ( updateMap.get( buffergeometry ) !== frame ) {
  10450. geometries.update( buffergeometry );
  10451. updateMap.set( buffergeometry, frame );
  10452. }
  10453. if ( object.isInstancedMesh ) {
  10454. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10455. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10456. }
  10457. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10458. if ( object.instanceColor !== null ) {
  10459. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10460. }
  10461. }
  10462. return buffergeometry;
  10463. }
  10464. function dispose() {
  10465. updateMap = new WeakMap();
  10466. }
  10467. function onInstancedMeshDispose( event ) {
  10468. const instancedMesh = event.target;
  10469. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10470. attributes.remove( instancedMesh.instanceMatrix );
  10471. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10472. }
  10473. return {
  10474. update: update,
  10475. dispose: dispose
  10476. };
  10477. }
  10478. /**
  10479. * Uniforms of a program.
  10480. * Those form a tree structure with a special top-level container for the root,
  10481. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10482. *
  10483. *
  10484. * Properties of inner nodes including the top-level container:
  10485. *
  10486. * .seq - array of nested uniforms
  10487. * .map - nested uniforms by name
  10488. *
  10489. *
  10490. * Methods of all nodes except the top-level container:
  10491. *
  10492. * .setValue( gl, value, [textures] )
  10493. *
  10494. * uploads a uniform value(s)
  10495. * the 'textures' parameter is needed for sampler uniforms
  10496. *
  10497. *
  10498. * Static methods of the top-level container (textures factorizations):
  10499. *
  10500. * .upload( gl, seq, values, textures )
  10501. *
  10502. * sets uniforms in 'seq' to 'values[id].value'
  10503. *
  10504. * .seqWithValue( seq, values ) : filteredSeq
  10505. *
  10506. * filters 'seq' entries with corresponding entry in values
  10507. *
  10508. *
  10509. * Methods of the top-level container (textures factorizations):
  10510. *
  10511. * .setValue( gl, name, value, textures )
  10512. *
  10513. * sets uniform with name 'name' to 'value'
  10514. *
  10515. * .setOptional( gl, obj, prop )
  10516. *
  10517. * like .set for an optional property of the object
  10518. *
  10519. */
  10520. const emptyTexture = /*@__PURE__*/ new Texture();
  10521. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10522. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10523. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10524. // --- Utilities ---
  10525. // Array Caches (provide typed arrays for temporary by size)
  10526. const arrayCacheF32 = [];
  10527. const arrayCacheI32 = [];
  10528. // Float32Array caches used for uploading Matrix uniforms
  10529. const mat4array = new Float32Array( 16 );
  10530. const mat3array = new Float32Array( 9 );
  10531. const mat2array = new Float32Array( 4 );
  10532. // Flattening for arrays of vectors and matrices
  10533. function flatten( array, nBlocks, blockSize ) {
  10534. const firstElem = array[ 0 ];
  10535. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10536. // unoptimized: ! isNaN( firstElem )
  10537. // see http://jacksondunstan.com/articles/983
  10538. const n = nBlocks * blockSize;
  10539. let r = arrayCacheF32[ n ];
  10540. if ( r === undefined ) {
  10541. r = new Float32Array( n );
  10542. arrayCacheF32[ n ] = r;
  10543. }
  10544. if ( nBlocks !== 0 ) {
  10545. firstElem.toArray( r, 0 );
  10546. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10547. offset += blockSize;
  10548. array[ i ].toArray( r, offset );
  10549. }
  10550. }
  10551. return r;
  10552. }
  10553. function arraysEqual( a, b ) {
  10554. if ( a.length !== b.length ) return false;
  10555. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10556. if ( a[ i ] !== b[ i ] ) return false;
  10557. }
  10558. return true;
  10559. }
  10560. function copyArray( a, b ) {
  10561. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10562. a[ i ] = b[ i ];
  10563. }
  10564. }
  10565. // Texture unit allocation
  10566. function allocTexUnits( textures, n ) {
  10567. let r = arrayCacheI32[ n ];
  10568. if ( r === undefined ) {
  10569. r = new Int32Array( n );
  10570. arrayCacheI32[ n ] = r;
  10571. }
  10572. for ( let i = 0; i !== n; ++ i ) {
  10573. r[ i ] = textures.allocateTextureUnit();
  10574. }
  10575. return r;
  10576. }
  10577. // --- Setters ---
  10578. // Note: Defining these methods externally, because they come in a bunch
  10579. // and this way their names minify.
  10580. // Single scalar
  10581. function setValueV1f( gl, v ) {
  10582. const cache = this.cache;
  10583. if ( cache[ 0 ] === v ) return;
  10584. gl.uniform1f( this.addr, v );
  10585. cache[ 0 ] = v;
  10586. }
  10587. // Single float vector (from flat array or THREE.VectorN)
  10588. function setValueV2f( gl, v ) {
  10589. const cache = this.cache;
  10590. if ( v.x !== undefined ) {
  10591. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10592. gl.uniform2f( this.addr, v.x, v.y );
  10593. cache[ 0 ] = v.x;
  10594. cache[ 1 ] = v.y;
  10595. }
  10596. } else {
  10597. if ( arraysEqual( cache, v ) ) return;
  10598. gl.uniform2fv( this.addr, v );
  10599. copyArray( cache, v );
  10600. }
  10601. }
  10602. function setValueV3f( gl, v ) {
  10603. const cache = this.cache;
  10604. if ( v.x !== undefined ) {
  10605. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10606. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10607. cache[ 0 ] = v.x;
  10608. cache[ 1 ] = v.y;
  10609. cache[ 2 ] = v.z;
  10610. }
  10611. } else if ( v.r !== undefined ) {
  10612. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10613. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10614. cache[ 0 ] = v.r;
  10615. cache[ 1 ] = v.g;
  10616. cache[ 2 ] = v.b;
  10617. }
  10618. } else {
  10619. if ( arraysEqual( cache, v ) ) return;
  10620. gl.uniform3fv( this.addr, v );
  10621. copyArray( cache, v );
  10622. }
  10623. }
  10624. function setValueV4f( gl, v ) {
  10625. const cache = this.cache;
  10626. if ( v.x !== undefined ) {
  10627. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10628. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10629. cache[ 0 ] = v.x;
  10630. cache[ 1 ] = v.y;
  10631. cache[ 2 ] = v.z;
  10632. cache[ 3 ] = v.w;
  10633. }
  10634. } else {
  10635. if ( arraysEqual( cache, v ) ) return;
  10636. gl.uniform4fv( this.addr, v );
  10637. copyArray( cache, v );
  10638. }
  10639. }
  10640. // Single matrix (from flat array or THREE.MatrixN)
  10641. function setValueM2( gl, v ) {
  10642. const cache = this.cache;
  10643. const elements = v.elements;
  10644. if ( elements === undefined ) {
  10645. if ( arraysEqual( cache, v ) ) return;
  10646. gl.uniformMatrix2fv( this.addr, false, v );
  10647. copyArray( cache, v );
  10648. } else {
  10649. if ( arraysEqual( cache, elements ) ) return;
  10650. mat2array.set( elements );
  10651. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10652. copyArray( cache, elements );
  10653. }
  10654. }
  10655. function setValueM3( gl, v ) {
  10656. const cache = this.cache;
  10657. const elements = v.elements;
  10658. if ( elements === undefined ) {
  10659. if ( arraysEqual( cache, v ) ) return;
  10660. gl.uniformMatrix3fv( this.addr, false, v );
  10661. copyArray( cache, v );
  10662. } else {
  10663. if ( arraysEqual( cache, elements ) ) return;
  10664. mat3array.set( elements );
  10665. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10666. copyArray( cache, elements );
  10667. }
  10668. }
  10669. function setValueM4( gl, v ) {
  10670. const cache = this.cache;
  10671. const elements = v.elements;
  10672. if ( elements === undefined ) {
  10673. if ( arraysEqual( cache, v ) ) return;
  10674. gl.uniformMatrix4fv( this.addr, false, v );
  10675. copyArray( cache, v );
  10676. } else {
  10677. if ( arraysEqual( cache, elements ) ) return;
  10678. mat4array.set( elements );
  10679. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10680. copyArray( cache, elements );
  10681. }
  10682. }
  10683. // Single integer / boolean
  10684. function setValueV1i( gl, v ) {
  10685. const cache = this.cache;
  10686. if ( cache[ 0 ] === v ) return;
  10687. gl.uniform1i( this.addr, v );
  10688. cache[ 0 ] = v;
  10689. }
  10690. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10691. function setValueV2i( gl, v ) {
  10692. const cache = this.cache;
  10693. if ( v.x !== undefined ) {
  10694. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10695. gl.uniform2i( this.addr, v.x, v.y );
  10696. cache[ 0 ] = v.x;
  10697. cache[ 1 ] = v.y;
  10698. }
  10699. } else {
  10700. if ( arraysEqual( cache, v ) ) return;
  10701. gl.uniform2iv( this.addr, v );
  10702. copyArray( cache, v );
  10703. }
  10704. }
  10705. function setValueV3i( gl, v ) {
  10706. const cache = this.cache;
  10707. if ( v.x !== undefined ) {
  10708. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10709. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10710. cache[ 0 ] = v.x;
  10711. cache[ 1 ] = v.y;
  10712. cache[ 2 ] = v.z;
  10713. }
  10714. } else {
  10715. if ( arraysEqual( cache, v ) ) return;
  10716. gl.uniform3iv( this.addr, v );
  10717. copyArray( cache, v );
  10718. }
  10719. }
  10720. function setValueV4i( gl, v ) {
  10721. const cache = this.cache;
  10722. if ( v.x !== undefined ) {
  10723. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10724. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  10725. cache[ 0 ] = v.x;
  10726. cache[ 1 ] = v.y;
  10727. cache[ 2 ] = v.z;
  10728. cache[ 3 ] = v.w;
  10729. }
  10730. } else {
  10731. if ( arraysEqual( cache, v ) ) return;
  10732. gl.uniform4iv( this.addr, v );
  10733. copyArray( cache, v );
  10734. }
  10735. }
  10736. // Single unsigned integer
  10737. function setValueV1ui( gl, v ) {
  10738. const cache = this.cache;
  10739. if ( cache[ 0 ] === v ) return;
  10740. gl.uniform1ui( this.addr, v );
  10741. cache[ 0 ] = v;
  10742. }
  10743. // Single unsigned integer vector (from flat array or THREE.VectorN)
  10744. function setValueV2ui( gl, v ) {
  10745. const cache = this.cache;
  10746. if ( v.x !== undefined ) {
  10747. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10748. gl.uniform2ui( this.addr, v.x, v.y );
  10749. cache[ 0 ] = v.x;
  10750. cache[ 1 ] = v.y;
  10751. }
  10752. } else {
  10753. if ( arraysEqual( cache, v ) ) return;
  10754. gl.uniform2uiv( this.addr, v );
  10755. copyArray( cache, v );
  10756. }
  10757. }
  10758. function setValueV3ui( gl, v ) {
  10759. const cache = this.cache;
  10760. if ( v.x !== undefined ) {
  10761. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10762. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  10763. cache[ 0 ] = v.x;
  10764. cache[ 1 ] = v.y;
  10765. cache[ 2 ] = v.z;
  10766. }
  10767. } else {
  10768. if ( arraysEqual( cache, v ) ) return;
  10769. gl.uniform3uiv( this.addr, v );
  10770. copyArray( cache, v );
  10771. }
  10772. }
  10773. function setValueV4ui( gl, v ) {
  10774. const cache = this.cache;
  10775. if ( v.x !== undefined ) {
  10776. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10777. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  10778. cache[ 0 ] = v.x;
  10779. cache[ 1 ] = v.y;
  10780. cache[ 2 ] = v.z;
  10781. cache[ 3 ] = v.w;
  10782. }
  10783. } else {
  10784. if ( arraysEqual( cache, v ) ) return;
  10785. gl.uniform4uiv( this.addr, v );
  10786. copyArray( cache, v );
  10787. }
  10788. }
  10789. // Single texture (2D / Cube)
  10790. function setValueT1( gl, v, textures ) {
  10791. const cache = this.cache;
  10792. const unit = textures.allocateTextureUnit();
  10793. if ( cache[ 0 ] !== unit ) {
  10794. gl.uniform1i( this.addr, unit );
  10795. cache[ 0 ] = unit;
  10796. }
  10797. textures.setTexture2D( v || emptyTexture, unit );
  10798. }
  10799. function setValueT3D1( gl, v, textures ) {
  10800. const cache = this.cache;
  10801. const unit = textures.allocateTextureUnit();
  10802. if ( cache[ 0 ] !== unit ) {
  10803. gl.uniform1i( this.addr, unit );
  10804. cache[ 0 ] = unit;
  10805. }
  10806. textures.setTexture3D( v || empty3dTexture, unit );
  10807. }
  10808. function setValueT6( gl, v, textures ) {
  10809. const cache = this.cache;
  10810. const unit = textures.allocateTextureUnit();
  10811. if ( cache[ 0 ] !== unit ) {
  10812. gl.uniform1i( this.addr, unit );
  10813. cache[ 0 ] = unit;
  10814. }
  10815. textures.setTextureCube( v || emptyCubeTexture, unit );
  10816. }
  10817. function setValueT2DArray1( gl, v, textures ) {
  10818. const cache = this.cache;
  10819. const unit = textures.allocateTextureUnit();
  10820. if ( cache[ 0 ] !== unit ) {
  10821. gl.uniform1i( this.addr, unit );
  10822. cache[ 0 ] = unit;
  10823. }
  10824. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10825. }
  10826. // Helper to pick the right setter for the singular case
  10827. function getSingularSetter( type ) {
  10828. switch ( type ) {
  10829. case 0x1406: return setValueV1f; // FLOAT
  10830. case 0x8b50: return setValueV2f; // _VEC2
  10831. case 0x8b51: return setValueV3f; // _VEC3
  10832. case 0x8b52: return setValueV4f; // _VEC4
  10833. case 0x8b5a: return setValueM2; // _MAT2
  10834. case 0x8b5b: return setValueM3; // _MAT3
  10835. case 0x8b5c: return setValueM4; // _MAT4
  10836. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10837. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10838. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10839. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10840. case 0x1405: return setValueV1ui; // UINT
  10841. case 0x8dc6: return setValueV2ui; // _VEC2
  10842. case 0x8dc7: return setValueV3ui; // _VEC3
  10843. case 0x8dc8: return setValueV4ui; // _VEC4
  10844. case 0x8b5e: // SAMPLER_2D
  10845. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10846. case 0x8dca: // INT_SAMPLER_2D
  10847. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10848. case 0x8b62: // SAMPLER_2D_SHADOW
  10849. return setValueT1;
  10850. case 0x8b5f: // SAMPLER_3D
  10851. case 0x8dcb: // INT_SAMPLER_3D
  10852. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10853. return setValueT3D1;
  10854. case 0x8b60: // SAMPLER_CUBE
  10855. case 0x8dcc: // INT_SAMPLER_CUBE
  10856. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10857. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10858. return setValueT6;
  10859. case 0x8dc1: // SAMPLER_2D_ARRAY
  10860. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10861. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10862. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10863. return setValueT2DArray1;
  10864. }
  10865. }
  10866. // Array of scalars
  10867. function setValueV1fArray( gl, v ) {
  10868. gl.uniform1fv( this.addr, v );
  10869. }
  10870. // Array of vectors (from flat array or array of THREE.VectorN)
  10871. function setValueV2fArray( gl, v ) {
  10872. const data = flatten( v, this.size, 2 );
  10873. gl.uniform2fv( this.addr, data );
  10874. }
  10875. function setValueV3fArray( gl, v ) {
  10876. const data = flatten( v, this.size, 3 );
  10877. gl.uniform3fv( this.addr, data );
  10878. }
  10879. function setValueV4fArray( gl, v ) {
  10880. const data = flatten( v, this.size, 4 );
  10881. gl.uniform4fv( this.addr, data );
  10882. }
  10883. // Array of matrices (from flat array or array of THREE.MatrixN)
  10884. function setValueM2Array( gl, v ) {
  10885. const data = flatten( v, this.size, 4 );
  10886. gl.uniformMatrix2fv( this.addr, false, data );
  10887. }
  10888. function setValueM3Array( gl, v ) {
  10889. const data = flatten( v, this.size, 9 );
  10890. gl.uniformMatrix3fv( this.addr, false, data );
  10891. }
  10892. function setValueM4Array( gl, v ) {
  10893. const data = flatten( v, this.size, 16 );
  10894. gl.uniformMatrix4fv( this.addr, false, data );
  10895. }
  10896. // Array of integer / boolean
  10897. function setValueV1iArray( gl, v ) {
  10898. gl.uniform1iv( this.addr, v );
  10899. }
  10900. // Array of integer / boolean vectors (from flat array)
  10901. function setValueV2iArray( gl, v ) {
  10902. gl.uniform2iv( this.addr, v );
  10903. }
  10904. function setValueV3iArray( gl, v ) {
  10905. gl.uniform3iv( this.addr, v );
  10906. }
  10907. function setValueV4iArray( gl, v ) {
  10908. gl.uniform4iv( this.addr, v );
  10909. }
  10910. // Array of unsigned integer
  10911. function setValueV1uiArray( gl, v ) {
  10912. gl.uniform1uiv( this.addr, v );
  10913. }
  10914. // Array of unsigned integer vectors (from flat array)
  10915. function setValueV2uiArray( gl, v ) {
  10916. gl.uniform2uiv( this.addr, v );
  10917. }
  10918. function setValueV3uiArray( gl, v ) {
  10919. gl.uniform3uiv( this.addr, v );
  10920. }
  10921. function setValueV4uiArray( gl, v ) {
  10922. gl.uniform4uiv( this.addr, v );
  10923. }
  10924. // Array of textures (2D / 3D / Cube / 2DArray)
  10925. function setValueT1Array( gl, v, textures ) {
  10926. const cache = this.cache;
  10927. const n = v.length;
  10928. const units = allocTexUnits( textures, n );
  10929. if ( ! arraysEqual( cache, units ) ) {
  10930. gl.uniform1iv( this.addr, units );
  10931. copyArray( cache, units );
  10932. }
  10933. for ( let i = 0; i !== n; ++ i ) {
  10934. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10935. }
  10936. }
  10937. function setValueT3DArray( gl, v, textures ) {
  10938. const cache = this.cache;
  10939. const n = v.length;
  10940. const units = allocTexUnits( textures, n );
  10941. if ( ! arraysEqual( cache, units ) ) {
  10942. gl.uniform1iv( this.addr, units );
  10943. copyArray( cache, units );
  10944. }
  10945. for ( let i = 0; i !== n; ++ i ) {
  10946. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  10947. }
  10948. }
  10949. function setValueT6Array( gl, v, textures ) {
  10950. const cache = this.cache;
  10951. const n = v.length;
  10952. const units = allocTexUnits( textures, n );
  10953. if ( ! arraysEqual( cache, units ) ) {
  10954. gl.uniform1iv( this.addr, units );
  10955. copyArray( cache, units );
  10956. }
  10957. for ( let i = 0; i !== n; ++ i ) {
  10958. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10959. }
  10960. }
  10961. function setValueT2DArrayArray( gl, v, textures ) {
  10962. const cache = this.cache;
  10963. const n = v.length;
  10964. const units = allocTexUnits( textures, n );
  10965. if ( ! arraysEqual( cache, units ) ) {
  10966. gl.uniform1iv( this.addr, units );
  10967. copyArray( cache, units );
  10968. }
  10969. for ( let i = 0; i !== n; ++ i ) {
  10970. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  10971. }
  10972. }
  10973. // Helper to pick the right setter for a pure (bottom-level) array
  10974. function getPureArraySetter( type ) {
  10975. switch ( type ) {
  10976. case 0x1406: return setValueV1fArray; // FLOAT
  10977. case 0x8b50: return setValueV2fArray; // _VEC2
  10978. case 0x8b51: return setValueV3fArray; // _VEC3
  10979. case 0x8b52: return setValueV4fArray; // _VEC4
  10980. case 0x8b5a: return setValueM2Array; // _MAT2
  10981. case 0x8b5b: return setValueM3Array; // _MAT3
  10982. case 0x8b5c: return setValueM4Array; // _MAT4
  10983. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10984. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10985. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10986. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10987. case 0x1405: return setValueV1uiArray; // UINT
  10988. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10989. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10990. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10991. case 0x8b5e: // SAMPLER_2D
  10992. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10993. case 0x8dca: // INT_SAMPLER_2D
  10994. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10995. case 0x8b62: // SAMPLER_2D_SHADOW
  10996. return setValueT1Array;
  10997. case 0x8b5f: // SAMPLER_3D
  10998. case 0x8dcb: // INT_SAMPLER_3D
  10999. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11000. return setValueT3DArray;
  11001. case 0x8b60: // SAMPLER_CUBE
  11002. case 0x8dcc: // INT_SAMPLER_CUBE
  11003. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11004. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11005. return setValueT6Array;
  11006. case 0x8dc1: // SAMPLER_2D_ARRAY
  11007. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11008. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11009. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11010. return setValueT2DArrayArray;
  11011. }
  11012. }
  11013. // --- Uniform Classes ---
  11014. class SingleUniform {
  11015. constructor( id, activeInfo, addr ) {
  11016. this.id = id;
  11017. this.addr = addr;
  11018. this.cache = [];
  11019. this.setValue = getSingularSetter( activeInfo.type );
  11020. // this.path = activeInfo.name; // DEBUG
  11021. }
  11022. }
  11023. class PureArrayUniform {
  11024. constructor( id, activeInfo, addr ) {
  11025. this.id = id;
  11026. this.addr = addr;
  11027. this.cache = [];
  11028. this.size = activeInfo.size;
  11029. this.setValue = getPureArraySetter( activeInfo.type );
  11030. // this.path = activeInfo.name; // DEBUG
  11031. }
  11032. }
  11033. class StructuredUniform {
  11034. constructor( id ) {
  11035. this.id = id;
  11036. this.seq = [];
  11037. this.map = {};
  11038. }
  11039. setValue( gl, value, textures ) {
  11040. const seq = this.seq;
  11041. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11042. const u = seq[ i ];
  11043. u.setValue( gl, value[ u.id ], textures );
  11044. }
  11045. }
  11046. }
  11047. // --- Top-level ---
  11048. // Parser - builds up the property tree from the path strings
  11049. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11050. // extracts
  11051. // - the identifier (member name or array index)
  11052. // - followed by an optional right bracket (found when array index)
  11053. // - followed by an optional left bracket or dot (type of subscript)
  11054. //
  11055. // Note: These portions can be read in a non-overlapping fashion and
  11056. // allow straightforward parsing of the hierarchy that WebGL encodes
  11057. // in the uniform names.
  11058. function addUniform( container, uniformObject ) {
  11059. container.seq.push( uniformObject );
  11060. container.map[ uniformObject.id ] = uniformObject;
  11061. }
  11062. function parseUniform( activeInfo, addr, container ) {
  11063. const path = activeInfo.name,
  11064. pathLength = path.length;
  11065. // reset RegExp object, because of the early exit of a previous run
  11066. RePathPart.lastIndex = 0;
  11067. while ( true ) {
  11068. const match = RePathPart.exec( path ),
  11069. matchEnd = RePathPart.lastIndex;
  11070. let id = match[ 1 ];
  11071. const idIsIndex = match[ 2 ] === ']',
  11072. subscript = match[ 3 ];
  11073. if ( idIsIndex ) id = id | 0; // convert to integer
  11074. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11075. // bare name or "pure" bottom-level array "[0]" suffix
  11076. addUniform( container, subscript === undefined ?
  11077. new SingleUniform( id, activeInfo, addr ) :
  11078. new PureArrayUniform( id, activeInfo, addr ) );
  11079. break;
  11080. } else {
  11081. // step into inner node / create it in case it doesn't exist
  11082. const map = container.map;
  11083. let next = map[ id ];
  11084. if ( next === undefined ) {
  11085. next = new StructuredUniform( id );
  11086. addUniform( container, next );
  11087. }
  11088. container = next;
  11089. }
  11090. }
  11091. }
  11092. // Root Container
  11093. class WebGLUniforms {
  11094. constructor( gl, program ) {
  11095. this.seq = [];
  11096. this.map = {};
  11097. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  11098. for ( let i = 0; i < n; ++ i ) {
  11099. const info = gl.getActiveUniform( program, i ),
  11100. addr = gl.getUniformLocation( program, info.name );
  11101. parseUniform( info, addr, this );
  11102. }
  11103. }
  11104. setValue( gl, name, value, textures ) {
  11105. const u = this.map[ name ];
  11106. if ( u !== undefined ) u.setValue( gl, value, textures );
  11107. }
  11108. setOptional( gl, object, name ) {
  11109. const v = object[ name ];
  11110. if ( v !== undefined ) this.setValue( gl, name, v );
  11111. }
  11112. static upload( gl, seq, values, textures ) {
  11113. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11114. const u = seq[ i ],
  11115. v = values[ u.id ];
  11116. if ( v.needsUpdate !== false ) {
  11117. // note: always updating when .needsUpdate is undefined
  11118. u.setValue( gl, v.value, textures );
  11119. }
  11120. }
  11121. }
  11122. static seqWithValue( seq, values ) {
  11123. const r = [];
  11124. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11125. const u = seq[ i ];
  11126. if ( u.id in values ) r.push( u );
  11127. }
  11128. return r;
  11129. }
  11130. }
  11131. function WebGLShader( gl, type, string ) {
  11132. const shader = gl.createShader( type );
  11133. gl.shaderSource( shader, string );
  11134. gl.compileShader( shader );
  11135. return shader;
  11136. }
  11137. let programIdCount = 0;
  11138. function handleSource( string, errorLine ) {
  11139. const lines = string.split( '\n' );
  11140. const lines2 = [];
  11141. const from = Math.max( errorLine - 6, 0 );
  11142. const to = Math.min( errorLine + 6, lines.length );
  11143. for ( let i = from; i < to; i ++ ) {
  11144. const line = i + 1;
  11145. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11146. }
  11147. return lines2.join( '\n' );
  11148. }
  11149. function getEncodingComponents( encoding ) {
  11150. switch ( encoding ) {
  11151. case LinearEncoding:
  11152. return [ 'Linear', '( value )' ];
  11153. case sRGBEncoding:
  11154. return [ 'sRGB', '( value )' ];
  11155. default:
  11156. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  11157. return [ 'Linear', '( value )' ];
  11158. }
  11159. }
  11160. function getShaderErrors( gl, shader, type ) {
  11161. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  11162. const errors = gl.getShaderInfoLog( shader ).trim();
  11163. if ( status && errors === '' ) return '';
  11164. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11165. if ( errorMatches ) {
  11166. // --enable-privileged-webgl-extension
  11167. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11168. const errorLine = parseInt( errorMatches[ 1 ] );
  11169. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11170. } else {
  11171. return errors;
  11172. }
  11173. }
  11174. function getTexelEncodingFunction( functionName, encoding ) {
  11175. const components = getEncodingComponents( encoding );
  11176. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  11177. }
  11178. function getToneMappingFunction( functionName, toneMapping ) {
  11179. let toneMappingName;
  11180. switch ( toneMapping ) {
  11181. case LinearToneMapping:
  11182. toneMappingName = 'Linear';
  11183. break;
  11184. case ReinhardToneMapping:
  11185. toneMappingName = 'Reinhard';
  11186. break;
  11187. case CineonToneMapping:
  11188. toneMappingName = 'OptimizedCineon';
  11189. break;
  11190. case ACESFilmicToneMapping:
  11191. toneMappingName = 'ACESFilmic';
  11192. break;
  11193. case CustomToneMapping:
  11194. toneMappingName = 'Custom';
  11195. break;
  11196. default:
  11197. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11198. toneMappingName = 'Linear';
  11199. }
  11200. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11201. }
  11202. function generateExtensions( parameters ) {
  11203. const chunks = [
  11204. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11205. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11206. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11207. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11208. ];
  11209. return chunks.filter( filterEmptyLine ).join( '\n' );
  11210. }
  11211. function generateDefines( defines ) {
  11212. const chunks = [];
  11213. for ( const name in defines ) {
  11214. const value = defines[ name ];
  11215. if ( value === false ) continue;
  11216. chunks.push( '#define ' + name + ' ' + value );
  11217. }
  11218. return chunks.join( '\n' );
  11219. }
  11220. function fetchAttributeLocations( gl, program ) {
  11221. const attributes = {};
  11222. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  11223. for ( let i = 0; i < n; i ++ ) {
  11224. const info = gl.getActiveAttrib( program, i );
  11225. const name = info.name;
  11226. let locationSize = 1;
  11227. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11228. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11229. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11230. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11231. attributes[ name ] = {
  11232. type: info.type,
  11233. location: gl.getAttribLocation( program, name ),
  11234. locationSize: locationSize
  11235. };
  11236. }
  11237. return attributes;
  11238. }
  11239. function filterEmptyLine( string ) {
  11240. return string !== '';
  11241. }
  11242. function replaceLightNums( string, parameters ) {
  11243. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11244. return string
  11245. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11246. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11247. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11248. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11249. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11250. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11251. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11252. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11253. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11254. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11255. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11256. }
  11257. function replaceClippingPlaneNums( string, parameters ) {
  11258. return string
  11259. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11260. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11261. }
  11262. // Resolve Includes
  11263. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11264. function resolveIncludes( string ) {
  11265. return string.replace( includePattern, includeReplacer );
  11266. }
  11267. function includeReplacer( match, include ) {
  11268. const string = ShaderChunk[ include ];
  11269. if ( string === undefined ) {
  11270. throw new Error( 'Can not resolve #include <' + include + '>' );
  11271. }
  11272. return resolveIncludes( string );
  11273. }
  11274. // Unroll Loops
  11275. const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  11276. function unrollLoops( string ) {
  11277. return string.replace( unrollLoopPattern, loopReplacer );
  11278. }
  11279. function loopReplacer( match, start, end, snippet ) {
  11280. let string = '';
  11281. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11282. string += snippet
  11283. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11284. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11285. }
  11286. return string;
  11287. }
  11288. //
  11289. function generatePrecision( parameters ) {
  11290. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11291. if ( parameters.precision === 'highp' ) {
  11292. precisionstring += '\n#define HIGH_PRECISION';
  11293. } else if ( parameters.precision === 'mediump' ) {
  11294. precisionstring += '\n#define MEDIUM_PRECISION';
  11295. } else if ( parameters.precision === 'lowp' ) {
  11296. precisionstring += '\n#define LOW_PRECISION';
  11297. }
  11298. return precisionstring;
  11299. }
  11300. function generateShadowMapTypeDefine( parameters ) {
  11301. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11302. if ( parameters.shadowMapType === PCFShadowMap ) {
  11303. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11304. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11305. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11306. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11307. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11308. }
  11309. return shadowMapTypeDefine;
  11310. }
  11311. function generateEnvMapTypeDefine( parameters ) {
  11312. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11313. if ( parameters.envMap ) {
  11314. switch ( parameters.envMapMode ) {
  11315. case CubeReflectionMapping:
  11316. case CubeRefractionMapping:
  11317. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11318. break;
  11319. case CubeUVReflectionMapping:
  11320. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11321. break;
  11322. }
  11323. }
  11324. return envMapTypeDefine;
  11325. }
  11326. function generateEnvMapModeDefine( parameters ) {
  11327. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11328. if ( parameters.envMap ) {
  11329. switch ( parameters.envMapMode ) {
  11330. case CubeRefractionMapping:
  11331. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11332. break;
  11333. }
  11334. }
  11335. return envMapModeDefine;
  11336. }
  11337. function generateEnvMapBlendingDefine( parameters ) {
  11338. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11339. if ( parameters.envMap ) {
  11340. switch ( parameters.combine ) {
  11341. case MultiplyOperation:
  11342. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11343. break;
  11344. case MixOperation:
  11345. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11346. break;
  11347. case AddOperation:
  11348. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11349. break;
  11350. }
  11351. }
  11352. return envMapBlendingDefine;
  11353. }
  11354. function generateCubeUVSize( parameters ) {
  11355. const imageHeight = parameters.envMapCubeUVHeight;
  11356. if ( imageHeight === null ) return null;
  11357. const maxMip = Math.log2( imageHeight ) - 2;
  11358. const texelHeight = 1.0 / imageHeight;
  11359. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11360. return { texelWidth, texelHeight, maxMip };
  11361. }
  11362. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11363. // TODO Send this event to Three.js DevTools
  11364. // console.log( 'WebGLProgram', cacheKey );
  11365. const gl = renderer.getContext();
  11366. const defines = parameters.defines;
  11367. let vertexShader = parameters.vertexShader;
  11368. let fragmentShader = parameters.fragmentShader;
  11369. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11370. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11371. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11372. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11373. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11374. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11375. const customDefines = generateDefines( defines );
  11376. const program = gl.createProgram();
  11377. let prefixVertex, prefixFragment;
  11378. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11379. if ( parameters.isRawShaderMaterial ) {
  11380. prefixVertex = [
  11381. customDefines
  11382. ].filter( filterEmptyLine ).join( '\n' );
  11383. if ( prefixVertex.length > 0 ) {
  11384. prefixVertex += '\n';
  11385. }
  11386. prefixFragment = [
  11387. customExtensions,
  11388. customDefines
  11389. ].filter( filterEmptyLine ).join( '\n' );
  11390. if ( prefixFragment.length > 0 ) {
  11391. prefixFragment += '\n';
  11392. }
  11393. } else {
  11394. prefixVertex = [
  11395. generatePrecision( parameters ),
  11396. '#define SHADER_NAME ' + parameters.shaderName,
  11397. customDefines,
  11398. parameters.instancing ? '#define USE_INSTANCING' : '',
  11399. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11400. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11401. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11402. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11403. parameters.map ? '#define USE_MAP' : '',
  11404. parameters.envMap ? '#define USE_ENVMAP' : '',
  11405. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11406. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11407. parameters.aoMap ? '#define USE_AOMAP' : '',
  11408. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11409. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11410. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11411. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11412. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11413. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11414. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11415. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11416. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11417. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11418. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11419. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11420. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11421. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11422. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11423. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11424. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11425. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11426. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11427. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11428. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11429. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11430. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11431. parameters.vertexColors ? '#define USE_COLOR' : '',
  11432. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11433. parameters.vertexUvs ? '#define USE_UV' : '',
  11434. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11435. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11436. parameters.skinning ? '#define USE_SKINNING' : '',
  11437. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11438. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11439. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11440. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11441. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11442. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11443. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11444. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11445. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11446. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11447. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11448. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11449. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11450. 'uniform mat4 modelMatrix;',
  11451. 'uniform mat4 modelViewMatrix;',
  11452. 'uniform mat4 projectionMatrix;',
  11453. 'uniform mat4 viewMatrix;',
  11454. 'uniform mat3 normalMatrix;',
  11455. 'uniform vec3 cameraPosition;',
  11456. 'uniform bool isOrthographic;',
  11457. '#ifdef USE_INSTANCING',
  11458. ' attribute mat4 instanceMatrix;',
  11459. '#endif',
  11460. '#ifdef USE_INSTANCING_COLOR',
  11461. ' attribute vec3 instanceColor;',
  11462. '#endif',
  11463. 'attribute vec3 position;',
  11464. 'attribute vec3 normal;',
  11465. 'attribute vec2 uv;',
  11466. '#ifdef USE_TANGENT',
  11467. ' attribute vec4 tangent;',
  11468. '#endif',
  11469. '#if defined( USE_COLOR_ALPHA )',
  11470. ' attribute vec4 color;',
  11471. '#elif defined( USE_COLOR )',
  11472. ' attribute vec3 color;',
  11473. '#endif',
  11474. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11475. ' attribute vec3 morphTarget0;',
  11476. ' attribute vec3 morphTarget1;',
  11477. ' attribute vec3 morphTarget2;',
  11478. ' attribute vec3 morphTarget3;',
  11479. ' #ifdef USE_MORPHNORMALS',
  11480. ' attribute vec3 morphNormal0;',
  11481. ' attribute vec3 morphNormal1;',
  11482. ' attribute vec3 morphNormal2;',
  11483. ' attribute vec3 morphNormal3;',
  11484. ' #else',
  11485. ' attribute vec3 morphTarget4;',
  11486. ' attribute vec3 morphTarget5;',
  11487. ' attribute vec3 morphTarget6;',
  11488. ' attribute vec3 morphTarget7;',
  11489. ' #endif',
  11490. '#endif',
  11491. '#ifdef USE_SKINNING',
  11492. ' attribute vec4 skinIndex;',
  11493. ' attribute vec4 skinWeight;',
  11494. '#endif',
  11495. '\n'
  11496. ].filter( filterEmptyLine ).join( '\n' );
  11497. prefixFragment = [
  11498. customExtensions,
  11499. generatePrecision( parameters ),
  11500. '#define SHADER_NAME ' + parameters.shaderName,
  11501. customDefines,
  11502. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11503. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11504. parameters.map ? '#define USE_MAP' : '',
  11505. parameters.matcap ? '#define USE_MATCAP' : '',
  11506. parameters.envMap ? '#define USE_ENVMAP' : '',
  11507. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11508. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11509. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11510. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11511. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11512. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11513. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11514. parameters.aoMap ? '#define USE_AOMAP' : '',
  11515. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11516. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11517. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11518. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11519. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11520. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11521. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11522. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11523. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11524. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11525. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11526. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11527. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11528. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11529. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11530. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11531. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11532. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11533. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11534. parameters.sheen ? '#define USE_SHEEN' : '',
  11535. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11536. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11537. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11538. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11539. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11540. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11541. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11542. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11543. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11544. parameters.vertexUvs ? '#define USE_UV' : '',
  11545. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11546. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11547. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11548. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11549. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11550. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11551. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11552. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11553. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11554. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11555. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11556. 'uniform mat4 viewMatrix;',
  11557. 'uniform vec3 cameraPosition;',
  11558. 'uniform bool isOrthographic;',
  11559. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11560. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11561. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11562. parameters.dithering ? '#define DITHERING' : '',
  11563. parameters.opaque ? '#define OPAQUE' : '',
  11564. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11565. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11566. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11567. '\n'
  11568. ].filter( filterEmptyLine ).join( '\n' );
  11569. }
  11570. vertexShader = resolveIncludes( vertexShader );
  11571. vertexShader = replaceLightNums( vertexShader, parameters );
  11572. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11573. fragmentShader = resolveIncludes( fragmentShader );
  11574. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11575. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11576. vertexShader = unrollLoops( vertexShader );
  11577. fragmentShader = unrollLoops( fragmentShader );
  11578. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11579. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11580. versionString = '#version 300 es\n';
  11581. prefixVertex = [
  11582. 'precision mediump sampler2DArray;',
  11583. '#define attribute in',
  11584. '#define varying out',
  11585. '#define texture2D texture'
  11586. ].join( '\n' ) + '\n' + prefixVertex;
  11587. prefixFragment = [
  11588. '#define varying in',
  11589. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11590. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11591. '#define gl_FragDepthEXT gl_FragDepth',
  11592. '#define texture2D texture',
  11593. '#define textureCube texture',
  11594. '#define texture2DProj textureProj',
  11595. '#define texture2DLodEXT textureLod',
  11596. '#define texture2DProjLodEXT textureProjLod',
  11597. '#define textureCubeLodEXT textureLod',
  11598. '#define texture2DGradEXT textureGrad',
  11599. '#define texture2DProjGradEXT textureProjGrad',
  11600. '#define textureCubeGradEXT textureGrad'
  11601. ].join( '\n' ) + '\n' + prefixFragment;
  11602. }
  11603. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11604. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11605. // console.log( '*VERTEX*', vertexGlsl );
  11606. // console.log( '*FRAGMENT*', fragmentGlsl );
  11607. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  11608. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  11609. gl.attachShader( program, glVertexShader );
  11610. gl.attachShader( program, glFragmentShader );
  11611. // Force a particular attribute to index 0.
  11612. if ( parameters.index0AttributeName !== undefined ) {
  11613. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11614. } else if ( parameters.morphTargets === true ) {
  11615. // programs with morphTargets displace position out of attribute 0
  11616. gl.bindAttribLocation( program, 0, 'position' );
  11617. }
  11618. gl.linkProgram( program );
  11619. // check for link errors
  11620. if ( renderer.debug.checkShaderErrors ) {
  11621. const programLog = gl.getProgramInfoLog( program ).trim();
  11622. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11623. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11624. let runnable = true;
  11625. let haveDiagnostics = true;
  11626. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  11627. runnable = false;
  11628. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11629. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11630. console.error(
  11631. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11632. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  11633. 'Program Info Log: ' + programLog + '\n' +
  11634. vertexErrors + '\n' +
  11635. fragmentErrors
  11636. );
  11637. } else if ( programLog !== '' ) {
  11638. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11639. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11640. haveDiagnostics = false;
  11641. }
  11642. if ( haveDiagnostics ) {
  11643. this.diagnostics = {
  11644. runnable: runnable,
  11645. programLog: programLog,
  11646. vertexShader: {
  11647. log: vertexLog,
  11648. prefix: prefixVertex
  11649. },
  11650. fragmentShader: {
  11651. log: fragmentLog,
  11652. prefix: prefixFragment
  11653. }
  11654. };
  11655. }
  11656. }
  11657. // Clean up
  11658. // Crashes in iOS9 and iOS10. #18402
  11659. // gl.detachShader( program, glVertexShader );
  11660. // gl.detachShader( program, glFragmentShader );
  11661. gl.deleteShader( glVertexShader );
  11662. gl.deleteShader( glFragmentShader );
  11663. // set up caching for uniform locations
  11664. let cachedUniforms;
  11665. this.getUniforms = function () {
  11666. if ( cachedUniforms === undefined ) {
  11667. cachedUniforms = new WebGLUniforms( gl, program );
  11668. }
  11669. return cachedUniforms;
  11670. };
  11671. // set up caching for attribute locations
  11672. let cachedAttributes;
  11673. this.getAttributes = function () {
  11674. if ( cachedAttributes === undefined ) {
  11675. cachedAttributes = fetchAttributeLocations( gl, program );
  11676. }
  11677. return cachedAttributes;
  11678. };
  11679. // free resource
  11680. this.destroy = function () {
  11681. bindingStates.releaseStatesOfProgram( this );
  11682. gl.deleteProgram( program );
  11683. this.program = undefined;
  11684. };
  11685. //
  11686. this.name = parameters.shaderName;
  11687. this.id = programIdCount ++;
  11688. this.cacheKey = cacheKey;
  11689. this.usedTimes = 1;
  11690. this.program = program;
  11691. this.vertexShader = glVertexShader;
  11692. this.fragmentShader = glFragmentShader;
  11693. return this;
  11694. }
  11695. let _id = 0;
  11696. class WebGLShaderCache {
  11697. constructor() {
  11698. this.shaderCache = new Map();
  11699. this.materialCache = new Map();
  11700. }
  11701. update( material ) {
  11702. const vertexShader = material.vertexShader;
  11703. const fragmentShader = material.fragmentShader;
  11704. const vertexShaderStage = this._getShaderStage( vertexShader );
  11705. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11706. const materialShaders = this._getShaderCacheForMaterial( material );
  11707. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11708. materialShaders.add( vertexShaderStage );
  11709. vertexShaderStage.usedTimes ++;
  11710. }
  11711. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11712. materialShaders.add( fragmentShaderStage );
  11713. fragmentShaderStage.usedTimes ++;
  11714. }
  11715. return this;
  11716. }
  11717. remove( material ) {
  11718. const materialShaders = this.materialCache.get( material );
  11719. for ( const shaderStage of materialShaders ) {
  11720. shaderStage.usedTimes --;
  11721. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11722. }
  11723. this.materialCache.delete( material );
  11724. return this;
  11725. }
  11726. getVertexShaderID( material ) {
  11727. return this._getShaderStage( material.vertexShader ).id;
  11728. }
  11729. getFragmentShaderID( material ) {
  11730. return this._getShaderStage( material.fragmentShader ).id;
  11731. }
  11732. dispose() {
  11733. this.shaderCache.clear();
  11734. this.materialCache.clear();
  11735. }
  11736. _getShaderCacheForMaterial( material ) {
  11737. const cache = this.materialCache;
  11738. let set = cache.get( material );
  11739. if ( set === undefined ) {
  11740. set = new Set();
  11741. cache.set( material, set );
  11742. }
  11743. return set;
  11744. }
  11745. _getShaderStage( code ) {
  11746. const cache = this.shaderCache;
  11747. let stage = cache.get( code );
  11748. if ( stage === undefined ) {
  11749. stage = new WebGLShaderStage( code );
  11750. cache.set( code, stage );
  11751. }
  11752. return stage;
  11753. }
  11754. }
  11755. class WebGLShaderStage {
  11756. constructor( code ) {
  11757. this.id = _id ++;
  11758. this.code = code;
  11759. this.usedTimes = 0;
  11760. }
  11761. }
  11762. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11763. const _programLayers = new Layers();
  11764. const _customShaders = new WebGLShaderCache();
  11765. const programs = [];
  11766. const isWebGL2 = capabilities.isWebGL2;
  11767. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11768. const vertexTextures = capabilities.vertexTextures;
  11769. let precision = capabilities.precision;
  11770. const shaderIDs = {
  11771. MeshDepthMaterial: 'depth',
  11772. MeshDistanceMaterial: 'distanceRGBA',
  11773. MeshNormalMaterial: 'normal',
  11774. MeshBasicMaterial: 'basic',
  11775. MeshLambertMaterial: 'lambert',
  11776. MeshPhongMaterial: 'phong',
  11777. MeshToonMaterial: 'toon',
  11778. MeshStandardMaterial: 'physical',
  11779. MeshPhysicalMaterial: 'physical',
  11780. MeshMatcapMaterial: 'matcap',
  11781. LineBasicMaterial: 'basic',
  11782. LineDashedMaterial: 'dashed',
  11783. PointsMaterial: 'points',
  11784. ShadowMaterial: 'shadow',
  11785. SpriteMaterial: 'sprite'
  11786. };
  11787. function getParameters( material, lights, shadows, scene, object ) {
  11788. const fog = scene.fog;
  11789. const geometry = object.geometry;
  11790. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11791. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11792. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11793. const shaderID = shaderIDs[ material.type ];
  11794. // heuristics to create shader parameters according to lights in the scene
  11795. // (not to blow over maxLights budget)
  11796. if ( material.precision !== null ) {
  11797. precision = capabilities.getMaxPrecision( material.precision );
  11798. if ( precision !== material.precision ) {
  11799. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11800. }
  11801. }
  11802. //
  11803. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11804. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11805. let morphTextureStride = 0;
  11806. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11807. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11808. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11809. //
  11810. let vertexShader, fragmentShader;
  11811. let customVertexShaderID, customFragmentShaderID;
  11812. if ( shaderID ) {
  11813. const shader = ShaderLib[ shaderID ];
  11814. vertexShader = shader.vertexShader;
  11815. fragmentShader = shader.fragmentShader;
  11816. } else {
  11817. vertexShader = material.vertexShader;
  11818. fragmentShader = material.fragmentShader;
  11819. _customShaders.update( material );
  11820. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11821. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11822. }
  11823. const currentRenderTarget = renderer.getRenderTarget();
  11824. const useAlphaTest = material.alphaTest > 0;
  11825. const useClearcoat = material.clearcoat > 0;
  11826. const useIridescence = material.iridescence > 0;
  11827. const parameters = {
  11828. isWebGL2: isWebGL2,
  11829. shaderID: shaderID,
  11830. shaderName: material.type,
  11831. vertexShader: vertexShader,
  11832. fragmentShader: fragmentShader,
  11833. defines: material.defines,
  11834. customVertexShaderID: customVertexShaderID,
  11835. customFragmentShaderID: customFragmentShaderID,
  11836. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11837. glslVersion: material.glslVersion,
  11838. precision: precision,
  11839. instancing: object.isInstancedMesh === true,
  11840. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11841. supportsVertexTextures: vertexTextures,
  11842. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11843. map: !! material.map,
  11844. matcap: !! material.matcap,
  11845. envMap: !! envMap,
  11846. envMapMode: envMap && envMap.mapping,
  11847. envMapCubeUVHeight: envMapCubeUVHeight,
  11848. lightMap: !! material.lightMap,
  11849. aoMap: !! material.aoMap,
  11850. emissiveMap: !! material.emissiveMap,
  11851. bumpMap: !! material.bumpMap,
  11852. normalMap: !! material.normalMap,
  11853. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11854. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11855. decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11856. clearcoat: useClearcoat,
  11857. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11858. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11859. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11860. iridescence: useIridescence,
  11861. iridescenceMap: useIridescence && !! material.iridescenceMap,
  11862. iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap,
  11863. displacementMap: !! material.displacementMap,
  11864. roughnessMap: !! material.roughnessMap,
  11865. metalnessMap: !! material.metalnessMap,
  11866. specularMap: !! material.specularMap,
  11867. specularIntensityMap: !! material.specularIntensityMap,
  11868. specularColorMap: !! material.specularColorMap,
  11869. opaque: material.transparent === false && material.blending === NormalBlending,
  11870. alphaMap: !! material.alphaMap,
  11871. alphaTest: useAlphaTest,
  11872. gradientMap: !! material.gradientMap,
  11873. sheen: material.sheen > 0,
  11874. sheenColorMap: !! material.sheenColorMap,
  11875. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11876. transmission: material.transmission > 0,
  11877. transmissionMap: !! material.transmissionMap,
  11878. thicknessMap: !! material.thicknessMap,
  11879. combine: material.combine,
  11880. vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ),
  11881. vertexColors: material.vertexColors,
  11882. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11883. vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap,
  11884. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap,
  11885. fog: !! fog,
  11886. useFog: material.fog === true,
  11887. fogExp2: ( fog && fog.isFogExp2 ),
  11888. flatShading: !! material.flatShading,
  11889. sizeAttenuation: material.sizeAttenuation,
  11890. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11891. skinning: object.isSkinnedMesh === true,
  11892. morphTargets: geometry.morphAttributes.position !== undefined,
  11893. morphNormals: geometry.morphAttributes.normal !== undefined,
  11894. morphColors: geometry.morphAttributes.color !== undefined,
  11895. morphTargetsCount: morphTargetsCount,
  11896. morphTextureStride: morphTextureStride,
  11897. numDirLights: lights.directional.length,
  11898. numPointLights: lights.point.length,
  11899. numSpotLights: lights.spot.length,
  11900. numSpotLightMaps: lights.spotLightMap.length,
  11901. numRectAreaLights: lights.rectArea.length,
  11902. numHemiLights: lights.hemi.length,
  11903. numDirLightShadows: lights.directionalShadowMap.length,
  11904. numPointLightShadows: lights.pointShadowMap.length,
  11905. numSpotLightShadows: lights.spotShadowMap.length,
  11906. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  11907. numClippingPlanes: clipping.numPlanes,
  11908. numClipIntersection: clipping.numIntersection,
  11909. dithering: material.dithering,
  11910. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11911. shadowMapType: renderer.shadowMap.type,
  11912. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11913. useLegacyLights: renderer.useLegacyLights,
  11914. premultipliedAlpha: material.premultipliedAlpha,
  11915. doubleSided: material.side === DoubleSide,
  11916. flipSided: material.side === BackSide,
  11917. useDepthPacking: !! material.depthPacking,
  11918. depthPacking: material.depthPacking || 0,
  11919. index0AttributeName: material.index0AttributeName,
  11920. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11921. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11922. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11923. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11924. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11925. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11926. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11927. customProgramCacheKey: material.customProgramCacheKey()
  11928. };
  11929. return parameters;
  11930. }
  11931. function getProgramCacheKey( parameters ) {
  11932. const array = [];
  11933. if ( parameters.shaderID ) {
  11934. array.push( parameters.shaderID );
  11935. } else {
  11936. array.push( parameters.customVertexShaderID );
  11937. array.push( parameters.customFragmentShaderID );
  11938. }
  11939. if ( parameters.defines !== undefined ) {
  11940. for ( const name in parameters.defines ) {
  11941. array.push( name );
  11942. array.push( parameters.defines[ name ] );
  11943. }
  11944. }
  11945. if ( parameters.isRawShaderMaterial === false ) {
  11946. getProgramCacheKeyParameters( array, parameters );
  11947. getProgramCacheKeyBooleans( array, parameters );
  11948. array.push( renderer.outputEncoding );
  11949. }
  11950. array.push( parameters.customProgramCacheKey );
  11951. return array.join();
  11952. }
  11953. function getProgramCacheKeyParameters( array, parameters ) {
  11954. array.push( parameters.precision );
  11955. array.push( parameters.outputEncoding );
  11956. array.push( parameters.envMapMode );
  11957. array.push( parameters.envMapCubeUVHeight );
  11958. array.push( parameters.combine );
  11959. array.push( parameters.vertexUvs );
  11960. array.push( parameters.fogExp2 );
  11961. array.push( parameters.sizeAttenuation );
  11962. array.push( parameters.morphTargetsCount );
  11963. array.push( parameters.morphAttributeCount );
  11964. array.push( parameters.numDirLights );
  11965. array.push( parameters.numPointLights );
  11966. array.push( parameters.numSpotLights );
  11967. array.push( parameters.numSpotLightMaps );
  11968. array.push( parameters.numHemiLights );
  11969. array.push( parameters.numRectAreaLights );
  11970. array.push( parameters.numDirLightShadows );
  11971. array.push( parameters.numPointLightShadows );
  11972. array.push( parameters.numSpotLightShadows );
  11973. array.push( parameters.numSpotLightShadowsWithMaps );
  11974. array.push( parameters.shadowMapType );
  11975. array.push( parameters.toneMapping );
  11976. array.push( parameters.numClippingPlanes );
  11977. array.push( parameters.numClipIntersection );
  11978. array.push( parameters.depthPacking );
  11979. }
  11980. function getProgramCacheKeyBooleans( array, parameters ) {
  11981. _programLayers.disableAll();
  11982. if ( parameters.isWebGL2 )
  11983. _programLayers.enable( 0 );
  11984. if ( parameters.supportsVertexTextures )
  11985. _programLayers.enable( 1 );
  11986. if ( parameters.instancing )
  11987. _programLayers.enable( 2 );
  11988. if ( parameters.instancingColor )
  11989. _programLayers.enable( 3 );
  11990. if ( parameters.map )
  11991. _programLayers.enable( 4 );
  11992. if ( parameters.matcap )
  11993. _programLayers.enable( 5 );
  11994. if ( parameters.envMap )
  11995. _programLayers.enable( 6 );
  11996. if ( parameters.lightMap )
  11997. _programLayers.enable( 7 );
  11998. if ( parameters.aoMap )
  11999. _programLayers.enable( 8 );
  12000. if ( parameters.emissiveMap )
  12001. _programLayers.enable( 9 );
  12002. if ( parameters.bumpMap )
  12003. _programLayers.enable( 10 );
  12004. if ( parameters.normalMap )
  12005. _programLayers.enable( 11 );
  12006. if ( parameters.objectSpaceNormalMap )
  12007. _programLayers.enable( 12 );
  12008. if ( parameters.tangentSpaceNormalMap )
  12009. _programLayers.enable( 13 );
  12010. if ( parameters.clearcoat )
  12011. _programLayers.enable( 14 );
  12012. if ( parameters.clearcoatMap )
  12013. _programLayers.enable( 15 );
  12014. if ( parameters.clearcoatRoughnessMap )
  12015. _programLayers.enable( 16 );
  12016. if ( parameters.clearcoatNormalMap )
  12017. _programLayers.enable( 17 );
  12018. if ( parameters.iridescence )
  12019. _programLayers.enable( 18 );
  12020. if ( parameters.iridescenceMap )
  12021. _programLayers.enable( 19 );
  12022. if ( parameters.iridescenceThicknessMap )
  12023. _programLayers.enable( 20 );
  12024. if ( parameters.displacementMap )
  12025. _programLayers.enable( 21 );
  12026. if ( parameters.specularMap )
  12027. _programLayers.enable( 22 );
  12028. if ( parameters.roughnessMap )
  12029. _programLayers.enable( 23 );
  12030. if ( parameters.metalnessMap )
  12031. _programLayers.enable( 24 );
  12032. if ( parameters.gradientMap )
  12033. _programLayers.enable( 25 );
  12034. if ( parameters.alphaMap )
  12035. _programLayers.enable( 26 );
  12036. if ( parameters.alphaTest )
  12037. _programLayers.enable( 27 );
  12038. if ( parameters.vertexColors )
  12039. _programLayers.enable( 28 );
  12040. if ( parameters.vertexAlphas )
  12041. _programLayers.enable( 29 );
  12042. if ( parameters.vertexUvs )
  12043. _programLayers.enable( 30 );
  12044. if ( parameters.vertexTangents )
  12045. _programLayers.enable( 31 );
  12046. if ( parameters.uvsVertexOnly )
  12047. _programLayers.enable( 32 );
  12048. array.push( _programLayers.mask );
  12049. _programLayers.disableAll();
  12050. if ( parameters.fog )
  12051. _programLayers.enable( 0 );
  12052. if ( parameters.useFog )
  12053. _programLayers.enable( 1 );
  12054. if ( parameters.flatShading )
  12055. _programLayers.enable( 2 );
  12056. if ( parameters.logarithmicDepthBuffer )
  12057. _programLayers.enable( 3 );
  12058. if ( parameters.skinning )
  12059. _programLayers.enable( 4 );
  12060. if ( parameters.morphTargets )
  12061. _programLayers.enable( 5 );
  12062. if ( parameters.morphNormals )
  12063. _programLayers.enable( 6 );
  12064. if ( parameters.morphColors )
  12065. _programLayers.enable( 7 );
  12066. if ( parameters.premultipliedAlpha )
  12067. _programLayers.enable( 8 );
  12068. if ( parameters.shadowMapEnabled )
  12069. _programLayers.enable( 9 );
  12070. if ( parameters.useLegacyLights )
  12071. _programLayers.enable( 10 );
  12072. if ( parameters.doubleSided )
  12073. _programLayers.enable( 11 );
  12074. if ( parameters.flipSided )
  12075. _programLayers.enable( 12 );
  12076. if ( parameters.useDepthPacking )
  12077. _programLayers.enable( 13 );
  12078. if ( parameters.dithering )
  12079. _programLayers.enable( 14 );
  12080. if ( parameters.specularIntensityMap )
  12081. _programLayers.enable( 15 );
  12082. if ( parameters.specularColorMap )
  12083. _programLayers.enable( 16 );
  12084. if ( parameters.transmission )
  12085. _programLayers.enable( 17 );
  12086. if ( parameters.transmissionMap )
  12087. _programLayers.enable( 18 );
  12088. if ( parameters.thicknessMap )
  12089. _programLayers.enable( 19 );
  12090. if ( parameters.sheen )
  12091. _programLayers.enable( 20 );
  12092. if ( parameters.sheenColorMap )
  12093. _programLayers.enable( 21 );
  12094. if ( parameters.sheenRoughnessMap )
  12095. _programLayers.enable( 22 );
  12096. if ( parameters.decodeVideoTexture )
  12097. _programLayers.enable( 23 );
  12098. if ( parameters.opaque )
  12099. _programLayers.enable( 24 );
  12100. array.push( _programLayers.mask );
  12101. }
  12102. function getUniforms( material ) {
  12103. const shaderID = shaderIDs[ material.type ];
  12104. let uniforms;
  12105. if ( shaderID ) {
  12106. const shader = ShaderLib[ shaderID ];
  12107. uniforms = UniformsUtils.clone( shader.uniforms );
  12108. } else {
  12109. uniforms = material.uniforms;
  12110. }
  12111. return uniforms;
  12112. }
  12113. function acquireProgram( parameters, cacheKey ) {
  12114. let program;
  12115. // Check if code has been already compiled
  12116. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12117. const preexistingProgram = programs[ p ];
  12118. if ( preexistingProgram.cacheKey === cacheKey ) {
  12119. program = preexistingProgram;
  12120. ++ program.usedTimes;
  12121. break;
  12122. }
  12123. }
  12124. if ( program === undefined ) {
  12125. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12126. programs.push( program );
  12127. }
  12128. return program;
  12129. }
  12130. function releaseProgram( program ) {
  12131. if ( -- program.usedTimes === 0 ) {
  12132. // Remove from unordered set
  12133. const i = programs.indexOf( program );
  12134. programs[ i ] = programs[ programs.length - 1 ];
  12135. programs.pop();
  12136. // Free WebGL resources
  12137. program.destroy();
  12138. }
  12139. }
  12140. function releaseShaderCache( material ) {
  12141. _customShaders.remove( material );
  12142. }
  12143. function dispose() {
  12144. _customShaders.dispose();
  12145. }
  12146. return {
  12147. getParameters: getParameters,
  12148. getProgramCacheKey: getProgramCacheKey,
  12149. getUniforms: getUniforms,
  12150. acquireProgram: acquireProgram,
  12151. releaseProgram: releaseProgram,
  12152. releaseShaderCache: releaseShaderCache,
  12153. // Exposed for resource monitoring & error feedback via renderer.info:
  12154. programs: programs,
  12155. dispose: dispose
  12156. };
  12157. }
  12158. function WebGLProperties() {
  12159. let properties = new WeakMap();
  12160. function get( object ) {
  12161. let map = properties.get( object );
  12162. if ( map === undefined ) {
  12163. map = {};
  12164. properties.set( object, map );
  12165. }
  12166. return map;
  12167. }
  12168. function remove( object ) {
  12169. properties.delete( object );
  12170. }
  12171. function update( object, key, value ) {
  12172. properties.get( object )[ key ] = value;
  12173. }
  12174. function dispose() {
  12175. properties = new WeakMap();
  12176. }
  12177. return {
  12178. get: get,
  12179. remove: remove,
  12180. update: update,
  12181. dispose: dispose
  12182. };
  12183. }
  12184. function painterSortStable( a, b ) {
  12185. if ( a.groupOrder !== b.groupOrder ) {
  12186. return a.groupOrder - b.groupOrder;
  12187. } else if ( a.renderOrder !== b.renderOrder ) {
  12188. return a.renderOrder - b.renderOrder;
  12189. } else if ( a.material.id !== b.material.id ) {
  12190. return a.material.id - b.material.id;
  12191. } else if ( a.z !== b.z ) {
  12192. return a.z - b.z;
  12193. } else {
  12194. return a.id - b.id;
  12195. }
  12196. }
  12197. function reversePainterSortStable( a, b ) {
  12198. if ( a.groupOrder !== b.groupOrder ) {
  12199. return a.groupOrder - b.groupOrder;
  12200. } else if ( a.renderOrder !== b.renderOrder ) {
  12201. return a.renderOrder - b.renderOrder;
  12202. } else if ( a.z !== b.z ) {
  12203. return b.z - a.z;
  12204. } else {
  12205. return a.id - b.id;
  12206. }
  12207. }
  12208. function WebGLRenderList() {
  12209. const renderItems = [];
  12210. let renderItemsIndex = 0;
  12211. const opaque = [];
  12212. const transmissive = [];
  12213. const transparent = [];
  12214. function init() {
  12215. renderItemsIndex = 0;
  12216. opaque.length = 0;
  12217. transmissive.length = 0;
  12218. transparent.length = 0;
  12219. }
  12220. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12221. let renderItem = renderItems[ renderItemsIndex ];
  12222. if ( renderItem === undefined ) {
  12223. renderItem = {
  12224. id: object.id,
  12225. object: object,
  12226. geometry: geometry,
  12227. material: material,
  12228. groupOrder: groupOrder,
  12229. renderOrder: object.renderOrder,
  12230. z: z,
  12231. group: group
  12232. };
  12233. renderItems[ renderItemsIndex ] = renderItem;
  12234. } else {
  12235. renderItem.id = object.id;
  12236. renderItem.object = object;
  12237. renderItem.geometry = geometry;
  12238. renderItem.material = material;
  12239. renderItem.groupOrder = groupOrder;
  12240. renderItem.renderOrder = object.renderOrder;
  12241. renderItem.z = z;
  12242. renderItem.group = group;
  12243. }
  12244. renderItemsIndex ++;
  12245. return renderItem;
  12246. }
  12247. function push( object, geometry, material, groupOrder, z, group ) {
  12248. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12249. if ( material.transmission > 0.0 ) {
  12250. transmissive.push( renderItem );
  12251. } else if ( material.transparent === true ) {
  12252. transparent.push( renderItem );
  12253. } else {
  12254. opaque.push( renderItem );
  12255. }
  12256. }
  12257. function unshift( object, geometry, material, groupOrder, z, group ) {
  12258. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12259. if ( material.transmission > 0.0 ) {
  12260. transmissive.unshift( renderItem );
  12261. } else if ( material.transparent === true ) {
  12262. transparent.unshift( renderItem );
  12263. } else {
  12264. opaque.unshift( renderItem );
  12265. }
  12266. }
  12267. function sort( customOpaqueSort, customTransparentSort ) {
  12268. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12269. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12270. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12271. }
  12272. function finish() {
  12273. // Clear references from inactive renderItems in the list
  12274. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12275. const renderItem = renderItems[ i ];
  12276. if ( renderItem.id === null ) break;
  12277. renderItem.id = null;
  12278. renderItem.object = null;
  12279. renderItem.geometry = null;
  12280. renderItem.material = null;
  12281. renderItem.group = null;
  12282. }
  12283. }
  12284. return {
  12285. opaque: opaque,
  12286. transmissive: transmissive,
  12287. transparent: transparent,
  12288. init: init,
  12289. push: push,
  12290. unshift: unshift,
  12291. finish: finish,
  12292. sort: sort
  12293. };
  12294. }
  12295. function WebGLRenderLists() {
  12296. let lists = new WeakMap();
  12297. function get( scene, renderCallDepth ) {
  12298. const listArray = lists.get( scene );
  12299. let list;
  12300. if ( listArray === undefined ) {
  12301. list = new WebGLRenderList();
  12302. lists.set( scene, [ list ] );
  12303. } else {
  12304. if ( renderCallDepth >= listArray.length ) {
  12305. list = new WebGLRenderList();
  12306. listArray.push( list );
  12307. } else {
  12308. list = listArray[ renderCallDepth ];
  12309. }
  12310. }
  12311. return list;
  12312. }
  12313. function dispose() {
  12314. lists = new WeakMap();
  12315. }
  12316. return {
  12317. get: get,
  12318. dispose: dispose
  12319. };
  12320. }
  12321. function UniformsCache() {
  12322. const lights = {};
  12323. return {
  12324. get: function ( light ) {
  12325. if ( lights[ light.id ] !== undefined ) {
  12326. return lights[ light.id ];
  12327. }
  12328. let uniforms;
  12329. switch ( light.type ) {
  12330. case 'DirectionalLight':
  12331. uniforms = {
  12332. direction: new Vector3(),
  12333. color: new Color()
  12334. };
  12335. break;
  12336. case 'SpotLight':
  12337. uniforms = {
  12338. position: new Vector3(),
  12339. direction: new Vector3(),
  12340. color: new Color(),
  12341. distance: 0,
  12342. coneCos: 0,
  12343. penumbraCos: 0,
  12344. decay: 0
  12345. };
  12346. break;
  12347. case 'PointLight':
  12348. uniforms = {
  12349. position: new Vector3(),
  12350. color: new Color(),
  12351. distance: 0,
  12352. decay: 0
  12353. };
  12354. break;
  12355. case 'HemisphereLight':
  12356. uniforms = {
  12357. direction: new Vector3(),
  12358. skyColor: new Color(),
  12359. groundColor: new Color()
  12360. };
  12361. break;
  12362. case 'RectAreaLight':
  12363. uniforms = {
  12364. color: new Color(),
  12365. position: new Vector3(),
  12366. halfWidth: new Vector3(),
  12367. halfHeight: new Vector3()
  12368. };
  12369. break;
  12370. }
  12371. lights[ light.id ] = uniforms;
  12372. return uniforms;
  12373. }
  12374. };
  12375. }
  12376. function ShadowUniformsCache() {
  12377. const lights = {};
  12378. return {
  12379. get: function ( light ) {
  12380. if ( lights[ light.id ] !== undefined ) {
  12381. return lights[ light.id ];
  12382. }
  12383. let uniforms;
  12384. switch ( light.type ) {
  12385. case 'DirectionalLight':
  12386. uniforms = {
  12387. shadowBias: 0,
  12388. shadowNormalBias: 0,
  12389. shadowRadius: 1,
  12390. shadowMapSize: new Vector2()
  12391. };
  12392. break;
  12393. case 'SpotLight':
  12394. uniforms = {
  12395. shadowBias: 0,
  12396. shadowNormalBias: 0,
  12397. shadowRadius: 1,
  12398. shadowMapSize: new Vector2()
  12399. };
  12400. break;
  12401. case 'PointLight':
  12402. uniforms = {
  12403. shadowBias: 0,
  12404. shadowNormalBias: 0,
  12405. shadowRadius: 1,
  12406. shadowMapSize: new Vector2(),
  12407. shadowCameraNear: 1,
  12408. shadowCameraFar: 1000
  12409. };
  12410. break;
  12411. // TODO (abelnation): set RectAreaLight shadow uniforms
  12412. }
  12413. lights[ light.id ] = uniforms;
  12414. return uniforms;
  12415. }
  12416. };
  12417. }
  12418. let nextVersion = 0;
  12419. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12420. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12421. }
  12422. function WebGLLights( extensions, capabilities ) {
  12423. const cache = new UniformsCache();
  12424. const shadowCache = ShadowUniformsCache();
  12425. const state = {
  12426. version: 0,
  12427. hash: {
  12428. directionalLength: - 1,
  12429. pointLength: - 1,
  12430. spotLength: - 1,
  12431. rectAreaLength: - 1,
  12432. hemiLength: - 1,
  12433. numDirectionalShadows: - 1,
  12434. numPointShadows: - 1,
  12435. numSpotShadows: - 1,
  12436. numSpotMaps: - 1
  12437. },
  12438. ambient: [ 0, 0, 0 ],
  12439. probe: [],
  12440. directional: [],
  12441. directionalShadow: [],
  12442. directionalShadowMap: [],
  12443. directionalShadowMatrix: [],
  12444. spot: [],
  12445. spotLightMap: [],
  12446. spotShadow: [],
  12447. spotShadowMap: [],
  12448. spotLightMatrix: [],
  12449. rectArea: [],
  12450. rectAreaLTC1: null,
  12451. rectAreaLTC2: null,
  12452. point: [],
  12453. pointShadow: [],
  12454. pointShadowMap: [],
  12455. pointShadowMatrix: [],
  12456. hemi: [],
  12457. numSpotLightShadowsWithMaps: 0
  12458. };
  12459. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12460. const vector3 = new Vector3();
  12461. const matrix4 = new Matrix4();
  12462. const matrix42 = new Matrix4();
  12463. function setup( lights, useLegacyLights ) {
  12464. let r = 0, g = 0, b = 0;
  12465. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12466. let directionalLength = 0;
  12467. let pointLength = 0;
  12468. let spotLength = 0;
  12469. let rectAreaLength = 0;
  12470. let hemiLength = 0;
  12471. let numDirectionalShadows = 0;
  12472. let numPointShadows = 0;
  12473. let numSpotShadows = 0;
  12474. let numSpotMaps = 0;
  12475. let numSpotShadowsWithMaps = 0;
  12476. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12477. lights.sort( shadowCastingAndTexturingLightsFirst );
  12478. // artist-friendly light intensity scaling factor
  12479. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  12480. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12481. const light = lights[ i ];
  12482. const color = light.color;
  12483. const intensity = light.intensity;
  12484. const distance = light.distance;
  12485. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12486. if ( light.isAmbientLight ) {
  12487. r += color.r * intensity * scaleFactor;
  12488. g += color.g * intensity * scaleFactor;
  12489. b += color.b * intensity * scaleFactor;
  12490. } else if ( light.isLightProbe ) {
  12491. for ( let j = 0; j < 9; j ++ ) {
  12492. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12493. }
  12494. } else if ( light.isDirectionalLight ) {
  12495. const uniforms = cache.get( light );
  12496. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12497. if ( light.castShadow ) {
  12498. const shadow = light.shadow;
  12499. const shadowUniforms = shadowCache.get( light );
  12500. shadowUniforms.shadowBias = shadow.bias;
  12501. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12502. shadowUniforms.shadowRadius = shadow.radius;
  12503. shadowUniforms.shadowMapSize = shadow.mapSize;
  12504. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12505. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12506. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12507. numDirectionalShadows ++;
  12508. }
  12509. state.directional[ directionalLength ] = uniforms;
  12510. directionalLength ++;
  12511. } else if ( light.isSpotLight ) {
  12512. const uniforms = cache.get( light );
  12513. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12514. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12515. uniforms.distance = distance;
  12516. uniforms.coneCos = Math.cos( light.angle );
  12517. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12518. uniforms.decay = light.decay;
  12519. state.spot[ spotLength ] = uniforms;
  12520. const shadow = light.shadow;
  12521. if ( light.map ) {
  12522. state.spotLightMap[ numSpotMaps ] = light.map;
  12523. numSpotMaps ++;
  12524. // make sure the lightMatrix is up to date
  12525. // TODO : do it if required only
  12526. shadow.updateMatrices( light );
  12527. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12528. }
  12529. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12530. if ( light.castShadow ) {
  12531. const shadowUniforms = shadowCache.get( light );
  12532. shadowUniforms.shadowBias = shadow.bias;
  12533. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12534. shadowUniforms.shadowRadius = shadow.radius;
  12535. shadowUniforms.shadowMapSize = shadow.mapSize;
  12536. state.spotShadow[ spotLength ] = shadowUniforms;
  12537. state.spotShadowMap[ spotLength ] = shadowMap;
  12538. numSpotShadows ++;
  12539. }
  12540. spotLength ++;
  12541. } else if ( light.isRectAreaLight ) {
  12542. const uniforms = cache.get( light );
  12543. uniforms.color.copy( color ).multiplyScalar( intensity );
  12544. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12545. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12546. state.rectArea[ rectAreaLength ] = uniforms;
  12547. rectAreaLength ++;
  12548. } else if ( light.isPointLight ) {
  12549. const uniforms = cache.get( light );
  12550. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12551. uniforms.distance = light.distance;
  12552. uniforms.decay = light.decay;
  12553. if ( light.castShadow ) {
  12554. const shadow = light.shadow;
  12555. const shadowUniforms = shadowCache.get( light );
  12556. shadowUniforms.shadowBias = shadow.bias;
  12557. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12558. shadowUniforms.shadowRadius = shadow.radius;
  12559. shadowUniforms.shadowMapSize = shadow.mapSize;
  12560. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12561. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12562. state.pointShadow[ pointLength ] = shadowUniforms;
  12563. state.pointShadowMap[ pointLength ] = shadowMap;
  12564. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12565. numPointShadows ++;
  12566. }
  12567. state.point[ pointLength ] = uniforms;
  12568. pointLength ++;
  12569. } else if ( light.isHemisphereLight ) {
  12570. const uniforms = cache.get( light );
  12571. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12572. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12573. state.hemi[ hemiLength ] = uniforms;
  12574. hemiLength ++;
  12575. }
  12576. }
  12577. if ( rectAreaLength > 0 ) {
  12578. if ( capabilities.isWebGL2 ) {
  12579. // WebGL 2
  12580. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12581. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12582. } else {
  12583. // WebGL 1
  12584. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12585. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12586. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12587. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12588. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12589. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12590. } else {
  12591. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12592. }
  12593. }
  12594. }
  12595. state.ambient[ 0 ] = r;
  12596. state.ambient[ 1 ] = g;
  12597. state.ambient[ 2 ] = b;
  12598. const hash = state.hash;
  12599. if ( hash.directionalLength !== directionalLength ||
  12600. hash.pointLength !== pointLength ||
  12601. hash.spotLength !== spotLength ||
  12602. hash.rectAreaLength !== rectAreaLength ||
  12603. hash.hemiLength !== hemiLength ||
  12604. hash.numDirectionalShadows !== numDirectionalShadows ||
  12605. hash.numPointShadows !== numPointShadows ||
  12606. hash.numSpotShadows !== numSpotShadows ||
  12607. hash.numSpotMaps !== numSpotMaps ) {
  12608. state.directional.length = directionalLength;
  12609. state.spot.length = spotLength;
  12610. state.rectArea.length = rectAreaLength;
  12611. state.point.length = pointLength;
  12612. state.hemi.length = hemiLength;
  12613. state.directionalShadow.length = numDirectionalShadows;
  12614. state.directionalShadowMap.length = numDirectionalShadows;
  12615. state.pointShadow.length = numPointShadows;
  12616. state.pointShadowMap.length = numPointShadows;
  12617. state.spotShadow.length = numSpotShadows;
  12618. state.spotShadowMap.length = numSpotShadows;
  12619. state.directionalShadowMatrix.length = numDirectionalShadows;
  12620. state.pointShadowMatrix.length = numPointShadows;
  12621. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12622. state.spotLightMap.length = numSpotMaps;
  12623. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12624. hash.directionalLength = directionalLength;
  12625. hash.pointLength = pointLength;
  12626. hash.spotLength = spotLength;
  12627. hash.rectAreaLength = rectAreaLength;
  12628. hash.hemiLength = hemiLength;
  12629. hash.numDirectionalShadows = numDirectionalShadows;
  12630. hash.numPointShadows = numPointShadows;
  12631. hash.numSpotShadows = numSpotShadows;
  12632. hash.numSpotMaps = numSpotMaps;
  12633. state.version = nextVersion ++;
  12634. }
  12635. }
  12636. function setupView( lights, camera ) {
  12637. let directionalLength = 0;
  12638. let pointLength = 0;
  12639. let spotLength = 0;
  12640. let rectAreaLength = 0;
  12641. let hemiLength = 0;
  12642. const viewMatrix = camera.matrixWorldInverse;
  12643. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12644. const light = lights[ i ];
  12645. if ( light.isDirectionalLight ) {
  12646. const uniforms = state.directional[ directionalLength ];
  12647. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12648. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12649. uniforms.direction.sub( vector3 );
  12650. uniforms.direction.transformDirection( viewMatrix );
  12651. directionalLength ++;
  12652. } else if ( light.isSpotLight ) {
  12653. const uniforms = state.spot[ spotLength ];
  12654. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12655. uniforms.position.applyMatrix4( viewMatrix );
  12656. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12657. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12658. uniforms.direction.sub( vector3 );
  12659. uniforms.direction.transformDirection( viewMatrix );
  12660. spotLength ++;
  12661. } else if ( light.isRectAreaLight ) {
  12662. const uniforms = state.rectArea[ rectAreaLength ];
  12663. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12664. uniforms.position.applyMatrix4( viewMatrix );
  12665. // extract local rotation of light to derive width/height half vectors
  12666. matrix42.identity();
  12667. matrix4.copy( light.matrixWorld );
  12668. matrix4.premultiply( viewMatrix );
  12669. matrix42.extractRotation( matrix4 );
  12670. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12671. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12672. uniforms.halfWidth.applyMatrix4( matrix42 );
  12673. uniforms.halfHeight.applyMatrix4( matrix42 );
  12674. rectAreaLength ++;
  12675. } else if ( light.isPointLight ) {
  12676. const uniforms = state.point[ pointLength ];
  12677. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12678. uniforms.position.applyMatrix4( viewMatrix );
  12679. pointLength ++;
  12680. } else if ( light.isHemisphereLight ) {
  12681. const uniforms = state.hemi[ hemiLength ];
  12682. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12683. uniforms.direction.transformDirection( viewMatrix );
  12684. hemiLength ++;
  12685. }
  12686. }
  12687. }
  12688. return {
  12689. setup: setup,
  12690. setupView: setupView,
  12691. state: state
  12692. };
  12693. }
  12694. function WebGLRenderState( extensions, capabilities ) {
  12695. const lights = new WebGLLights( extensions, capabilities );
  12696. const lightsArray = [];
  12697. const shadowsArray = [];
  12698. function init() {
  12699. lightsArray.length = 0;
  12700. shadowsArray.length = 0;
  12701. }
  12702. function pushLight( light ) {
  12703. lightsArray.push( light );
  12704. }
  12705. function pushShadow( shadowLight ) {
  12706. shadowsArray.push( shadowLight );
  12707. }
  12708. function setupLights( useLegacyLights ) {
  12709. lights.setup( lightsArray, useLegacyLights );
  12710. }
  12711. function setupLightsView( camera ) {
  12712. lights.setupView( lightsArray, camera );
  12713. }
  12714. const state = {
  12715. lightsArray: lightsArray,
  12716. shadowsArray: shadowsArray,
  12717. lights: lights
  12718. };
  12719. return {
  12720. init: init,
  12721. state: state,
  12722. setupLights: setupLights,
  12723. setupLightsView: setupLightsView,
  12724. pushLight: pushLight,
  12725. pushShadow: pushShadow
  12726. };
  12727. }
  12728. function WebGLRenderStates( extensions, capabilities ) {
  12729. let renderStates = new WeakMap();
  12730. function get( scene, renderCallDepth = 0 ) {
  12731. const renderStateArray = renderStates.get( scene );
  12732. let renderState;
  12733. if ( renderStateArray === undefined ) {
  12734. renderState = new WebGLRenderState( extensions, capabilities );
  12735. renderStates.set( scene, [ renderState ] );
  12736. } else {
  12737. if ( renderCallDepth >= renderStateArray.length ) {
  12738. renderState = new WebGLRenderState( extensions, capabilities );
  12739. renderStateArray.push( renderState );
  12740. } else {
  12741. renderState = renderStateArray[ renderCallDepth ];
  12742. }
  12743. }
  12744. return renderState;
  12745. }
  12746. function dispose() {
  12747. renderStates = new WeakMap();
  12748. }
  12749. return {
  12750. get: get,
  12751. dispose: dispose
  12752. };
  12753. }
  12754. class MeshDepthMaterial extends Material {
  12755. constructor( parameters ) {
  12756. super();
  12757. this.isMeshDepthMaterial = true;
  12758. this.type = 'MeshDepthMaterial';
  12759. this.depthPacking = BasicDepthPacking;
  12760. this.map = null;
  12761. this.alphaMap = null;
  12762. this.displacementMap = null;
  12763. this.displacementScale = 1;
  12764. this.displacementBias = 0;
  12765. this.wireframe = false;
  12766. this.wireframeLinewidth = 1;
  12767. this.setValues( parameters );
  12768. }
  12769. copy( source ) {
  12770. super.copy( source );
  12771. this.depthPacking = source.depthPacking;
  12772. this.map = source.map;
  12773. this.alphaMap = source.alphaMap;
  12774. this.displacementMap = source.displacementMap;
  12775. this.displacementScale = source.displacementScale;
  12776. this.displacementBias = source.displacementBias;
  12777. this.wireframe = source.wireframe;
  12778. this.wireframeLinewidth = source.wireframeLinewidth;
  12779. return this;
  12780. }
  12781. }
  12782. class MeshDistanceMaterial extends Material {
  12783. constructor( parameters ) {
  12784. super();
  12785. this.isMeshDistanceMaterial = true;
  12786. this.type = 'MeshDistanceMaterial';
  12787. this.referencePosition = new Vector3();
  12788. this.nearDistance = 1;
  12789. this.farDistance = 1000;
  12790. this.map = null;
  12791. this.alphaMap = null;
  12792. this.displacementMap = null;
  12793. this.displacementScale = 1;
  12794. this.displacementBias = 0;
  12795. this.setValues( parameters );
  12796. }
  12797. copy( source ) {
  12798. super.copy( source );
  12799. this.referencePosition.copy( source.referencePosition );
  12800. this.nearDistance = source.nearDistance;
  12801. this.farDistance = source.farDistance;
  12802. this.map = source.map;
  12803. this.alphaMap = source.alphaMap;
  12804. this.displacementMap = source.displacementMap;
  12805. this.displacementScale = source.displacementScale;
  12806. this.displacementBias = source.displacementBias;
  12807. return this;
  12808. }
  12809. }
  12810. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12811. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12812. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12813. let _frustum = new Frustum();
  12814. const _shadowMapSize = new Vector2(),
  12815. _viewportSize = new Vector2(),
  12816. _viewport = new Vector4(),
  12817. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12818. _distanceMaterial = new MeshDistanceMaterial(),
  12819. _materialCache = {},
  12820. _maxTextureSize = _capabilities.maxTextureSize;
  12821. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  12822. const shadowMaterialVertical = new ShaderMaterial( {
  12823. defines: {
  12824. VSM_SAMPLES: 8
  12825. },
  12826. uniforms: {
  12827. shadow_pass: { value: null },
  12828. resolution: { value: new Vector2() },
  12829. radius: { value: 4.0 }
  12830. },
  12831. vertexShader: vertex,
  12832. fragmentShader: fragment
  12833. } );
  12834. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12835. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12836. const fullScreenTri = new BufferGeometry();
  12837. fullScreenTri.setAttribute(
  12838. 'position',
  12839. new BufferAttribute(
  12840. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12841. 3
  12842. )
  12843. );
  12844. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12845. const scope = this;
  12846. this.enabled = false;
  12847. this.autoUpdate = true;
  12848. this.needsUpdate = false;
  12849. this.type = PCFShadowMap;
  12850. this.render = function ( lights, scene, camera ) {
  12851. if ( scope.enabled === false ) return;
  12852. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12853. if ( lights.length === 0 ) return;
  12854. const currentRenderTarget = _renderer.getRenderTarget();
  12855. const activeCubeFace = _renderer.getActiveCubeFace();
  12856. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12857. const _state = _renderer.state;
  12858. // Set GL state for depth map.
  12859. _state.setBlending( NoBlending );
  12860. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12861. _state.buffers.depth.setTest( true );
  12862. _state.setScissorTest( false );
  12863. // render depth map
  12864. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12865. const light = lights[ i ];
  12866. const shadow = light.shadow;
  12867. if ( shadow === undefined ) {
  12868. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12869. continue;
  12870. }
  12871. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12872. _shadowMapSize.copy( shadow.mapSize );
  12873. const shadowFrameExtents = shadow.getFrameExtents();
  12874. _shadowMapSize.multiply( shadowFrameExtents );
  12875. _viewportSize.copy( shadow.mapSize );
  12876. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12877. if ( _shadowMapSize.x > _maxTextureSize ) {
  12878. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12879. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12880. shadow.mapSize.x = _viewportSize.x;
  12881. }
  12882. if ( _shadowMapSize.y > _maxTextureSize ) {
  12883. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12884. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12885. shadow.mapSize.y = _viewportSize.y;
  12886. }
  12887. }
  12888. if ( shadow.map === null ) {
  12889. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  12890. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12891. shadow.map.texture.name = light.name + '.shadowMap';
  12892. shadow.camera.updateProjectionMatrix();
  12893. }
  12894. _renderer.setRenderTarget( shadow.map );
  12895. _renderer.clear();
  12896. const viewportCount = shadow.getViewportCount();
  12897. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12898. const viewport = shadow.getViewport( vp );
  12899. _viewport.set(
  12900. _viewportSize.x * viewport.x,
  12901. _viewportSize.y * viewport.y,
  12902. _viewportSize.x * viewport.z,
  12903. _viewportSize.y * viewport.w
  12904. );
  12905. _state.viewport( _viewport );
  12906. shadow.updateMatrices( light, vp );
  12907. _frustum = shadow.getFrustum();
  12908. renderObject( scene, camera, shadow.camera, light, this.type );
  12909. }
  12910. // do blur pass for VSM
  12911. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  12912. VSMPass( shadow, camera );
  12913. }
  12914. shadow.needsUpdate = false;
  12915. }
  12916. scope.needsUpdate = false;
  12917. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12918. };
  12919. function VSMPass( shadow, camera ) {
  12920. const geometry = _objects.update( fullScreenMesh );
  12921. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12922. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12923. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12924. shadowMaterialVertical.needsUpdate = true;
  12925. shadowMaterialHorizontal.needsUpdate = true;
  12926. }
  12927. if ( shadow.mapPass === null ) {
  12928. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  12929. }
  12930. // vertical pass
  12931. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12932. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12933. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12934. _renderer.setRenderTarget( shadow.mapPass );
  12935. _renderer.clear();
  12936. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12937. // horizontal pass
  12938. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12939. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12940. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12941. _renderer.setRenderTarget( shadow.map );
  12942. _renderer.clear();
  12943. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12944. }
  12945. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12946. let result = null;
  12947. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12948. if ( customMaterial !== undefined ) {
  12949. result = customMaterial;
  12950. } else {
  12951. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12952. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  12953. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12954. ( material.alphaMap && material.alphaTest > 0 ) ||
  12955. ( material.map && material.alphaTest > 0 ) ) {
  12956. // in this case we need a unique material instance reflecting the
  12957. // appropriate state
  12958. const keyA = result.uuid, keyB = material.uuid;
  12959. let materialsForVariant = _materialCache[ keyA ];
  12960. if ( materialsForVariant === undefined ) {
  12961. materialsForVariant = {};
  12962. _materialCache[ keyA ] = materialsForVariant;
  12963. }
  12964. let cachedMaterial = materialsForVariant[ keyB ];
  12965. if ( cachedMaterial === undefined ) {
  12966. cachedMaterial = result.clone();
  12967. materialsForVariant[ keyB ] = cachedMaterial;
  12968. }
  12969. result = cachedMaterial;
  12970. }
  12971. }
  12972. result.visible = material.visible;
  12973. result.wireframe = material.wireframe;
  12974. if ( type === VSMShadowMap ) {
  12975. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12976. } else {
  12977. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12978. }
  12979. result.alphaMap = material.alphaMap;
  12980. result.alphaTest = material.alphaTest;
  12981. result.map = material.map;
  12982. result.clipShadows = material.clipShadows;
  12983. result.clippingPlanes = material.clippingPlanes;
  12984. result.clipIntersection = material.clipIntersection;
  12985. result.displacementMap = material.displacementMap;
  12986. result.displacementScale = material.displacementScale;
  12987. result.displacementBias = material.displacementBias;
  12988. result.wireframeLinewidth = material.wireframeLinewidth;
  12989. result.linewidth = material.linewidth;
  12990. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12991. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12992. result.nearDistance = shadowCameraNear;
  12993. result.farDistance = shadowCameraFar;
  12994. }
  12995. return result;
  12996. }
  12997. function renderObject( object, camera, shadowCamera, light, type ) {
  12998. if ( object.visible === false ) return;
  12999. const visible = object.layers.test( camera.layers );
  13000. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13001. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13002. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13003. const geometry = _objects.update( object );
  13004. const material = object.material;
  13005. if ( Array.isArray( material ) ) {
  13006. const groups = geometry.groups;
  13007. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13008. const group = groups[ k ];
  13009. const groupMaterial = material[ group.materialIndex ];
  13010. if ( groupMaterial && groupMaterial.visible ) {
  13011. const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  13012. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13013. }
  13014. }
  13015. } else if ( material.visible ) {
  13016. const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  13017. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13018. }
  13019. }
  13020. }
  13021. const children = object.children;
  13022. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13023. renderObject( children[ i ], camera, shadowCamera, light, type );
  13024. }
  13025. }
  13026. }
  13027. function WebGLState( gl, extensions, capabilities ) {
  13028. const isWebGL2 = capabilities.isWebGL2;
  13029. function ColorBuffer() {
  13030. let locked = false;
  13031. const color = new Vector4();
  13032. let currentColorMask = null;
  13033. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13034. return {
  13035. setMask: function ( colorMask ) {
  13036. if ( currentColorMask !== colorMask && ! locked ) {
  13037. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13038. currentColorMask = colorMask;
  13039. }
  13040. },
  13041. setLocked: function ( lock ) {
  13042. locked = lock;
  13043. },
  13044. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13045. if ( premultipliedAlpha === true ) {
  13046. r *= a; g *= a; b *= a;
  13047. }
  13048. color.set( r, g, b, a );
  13049. if ( currentColorClear.equals( color ) === false ) {
  13050. gl.clearColor( r, g, b, a );
  13051. currentColorClear.copy( color );
  13052. }
  13053. },
  13054. reset: function () {
  13055. locked = false;
  13056. currentColorMask = null;
  13057. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13058. }
  13059. };
  13060. }
  13061. function DepthBuffer() {
  13062. let locked = false;
  13063. let currentDepthMask = null;
  13064. let currentDepthFunc = null;
  13065. let currentDepthClear = null;
  13066. return {
  13067. setTest: function ( depthTest ) {
  13068. if ( depthTest ) {
  13069. enable( gl.DEPTH_TEST );
  13070. } else {
  13071. disable( gl.DEPTH_TEST );
  13072. }
  13073. },
  13074. setMask: function ( depthMask ) {
  13075. if ( currentDepthMask !== depthMask && ! locked ) {
  13076. gl.depthMask( depthMask );
  13077. currentDepthMask = depthMask;
  13078. }
  13079. },
  13080. setFunc: function ( depthFunc ) {
  13081. if ( currentDepthFunc !== depthFunc ) {
  13082. switch ( depthFunc ) {
  13083. case NeverDepth:
  13084. gl.depthFunc( gl.NEVER );
  13085. break;
  13086. case AlwaysDepth:
  13087. gl.depthFunc( gl.ALWAYS );
  13088. break;
  13089. case LessDepth:
  13090. gl.depthFunc( gl.LESS );
  13091. break;
  13092. case LessEqualDepth:
  13093. gl.depthFunc( gl.LEQUAL );
  13094. break;
  13095. case EqualDepth:
  13096. gl.depthFunc( gl.EQUAL );
  13097. break;
  13098. case GreaterEqualDepth:
  13099. gl.depthFunc( gl.GEQUAL );
  13100. break;
  13101. case GreaterDepth:
  13102. gl.depthFunc( gl.GREATER );
  13103. break;
  13104. case NotEqualDepth:
  13105. gl.depthFunc( gl.NOTEQUAL );
  13106. break;
  13107. default:
  13108. gl.depthFunc( gl.LEQUAL );
  13109. }
  13110. currentDepthFunc = depthFunc;
  13111. }
  13112. },
  13113. setLocked: function ( lock ) {
  13114. locked = lock;
  13115. },
  13116. setClear: function ( depth ) {
  13117. if ( currentDepthClear !== depth ) {
  13118. gl.clearDepth( depth );
  13119. currentDepthClear = depth;
  13120. }
  13121. },
  13122. reset: function () {
  13123. locked = false;
  13124. currentDepthMask = null;
  13125. currentDepthFunc = null;
  13126. currentDepthClear = null;
  13127. }
  13128. };
  13129. }
  13130. function StencilBuffer() {
  13131. let locked = false;
  13132. let currentStencilMask = null;
  13133. let currentStencilFunc = null;
  13134. let currentStencilRef = null;
  13135. let currentStencilFuncMask = null;
  13136. let currentStencilFail = null;
  13137. let currentStencilZFail = null;
  13138. let currentStencilZPass = null;
  13139. let currentStencilClear = null;
  13140. return {
  13141. setTest: function ( stencilTest ) {
  13142. if ( ! locked ) {
  13143. if ( stencilTest ) {
  13144. enable( gl.STENCIL_TEST );
  13145. } else {
  13146. disable( gl.STENCIL_TEST );
  13147. }
  13148. }
  13149. },
  13150. setMask: function ( stencilMask ) {
  13151. if ( currentStencilMask !== stencilMask && ! locked ) {
  13152. gl.stencilMask( stencilMask );
  13153. currentStencilMask = stencilMask;
  13154. }
  13155. },
  13156. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13157. if ( currentStencilFunc !== stencilFunc ||
  13158. currentStencilRef !== stencilRef ||
  13159. currentStencilFuncMask !== stencilMask ) {
  13160. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13161. currentStencilFunc = stencilFunc;
  13162. currentStencilRef = stencilRef;
  13163. currentStencilFuncMask = stencilMask;
  13164. }
  13165. },
  13166. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13167. if ( currentStencilFail !== stencilFail ||
  13168. currentStencilZFail !== stencilZFail ||
  13169. currentStencilZPass !== stencilZPass ) {
  13170. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13171. currentStencilFail = stencilFail;
  13172. currentStencilZFail = stencilZFail;
  13173. currentStencilZPass = stencilZPass;
  13174. }
  13175. },
  13176. setLocked: function ( lock ) {
  13177. locked = lock;
  13178. },
  13179. setClear: function ( stencil ) {
  13180. if ( currentStencilClear !== stencil ) {
  13181. gl.clearStencil( stencil );
  13182. currentStencilClear = stencil;
  13183. }
  13184. },
  13185. reset: function () {
  13186. locked = false;
  13187. currentStencilMask = null;
  13188. currentStencilFunc = null;
  13189. currentStencilRef = null;
  13190. currentStencilFuncMask = null;
  13191. currentStencilFail = null;
  13192. currentStencilZFail = null;
  13193. currentStencilZPass = null;
  13194. currentStencilClear = null;
  13195. }
  13196. };
  13197. }
  13198. //
  13199. const colorBuffer = new ColorBuffer();
  13200. const depthBuffer = new DepthBuffer();
  13201. const stencilBuffer = new StencilBuffer();
  13202. const uboBindings = new WeakMap();
  13203. const uboProgramMap = new WeakMap();
  13204. let enabledCapabilities = {};
  13205. let currentBoundFramebuffers = {};
  13206. let currentDrawbuffers = new WeakMap();
  13207. let defaultDrawbuffers = [];
  13208. let currentProgram = null;
  13209. let currentBlendingEnabled = false;
  13210. let currentBlending = null;
  13211. let currentBlendEquation = null;
  13212. let currentBlendSrc = null;
  13213. let currentBlendDst = null;
  13214. let currentBlendEquationAlpha = null;
  13215. let currentBlendSrcAlpha = null;
  13216. let currentBlendDstAlpha = null;
  13217. let currentPremultipledAlpha = false;
  13218. let currentFlipSided = null;
  13219. let currentCullFace = null;
  13220. let currentLineWidth = null;
  13221. let currentPolygonOffsetFactor = null;
  13222. let currentPolygonOffsetUnits = null;
  13223. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  13224. let lineWidthAvailable = false;
  13225. let version = 0;
  13226. const glVersion = gl.getParameter( gl.VERSION );
  13227. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13228. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13229. lineWidthAvailable = ( version >= 1.0 );
  13230. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13231. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13232. lineWidthAvailable = ( version >= 2.0 );
  13233. }
  13234. let currentTextureSlot = null;
  13235. let currentBoundTextures = {};
  13236. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13237. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13238. const currentScissor = new Vector4().fromArray( scissorParam );
  13239. const currentViewport = new Vector4().fromArray( viewportParam );
  13240. function createTexture( type, target, count ) {
  13241. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13242. const texture = gl.createTexture();
  13243. gl.bindTexture( type, texture );
  13244. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13245. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13246. for ( let i = 0; i < count; i ++ ) {
  13247. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13248. }
  13249. return texture;
  13250. }
  13251. const emptyTextures = {};
  13252. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13253. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13254. // init
  13255. colorBuffer.setClear( 0, 0, 0, 1 );
  13256. depthBuffer.setClear( 1 );
  13257. stencilBuffer.setClear( 0 );
  13258. enable( gl.DEPTH_TEST );
  13259. depthBuffer.setFunc( LessEqualDepth );
  13260. setFlipSided( false );
  13261. setCullFace( CullFaceBack );
  13262. enable( gl.CULL_FACE );
  13263. setBlending( NoBlending );
  13264. //
  13265. function enable( id ) {
  13266. if ( enabledCapabilities[ id ] !== true ) {
  13267. gl.enable( id );
  13268. enabledCapabilities[ id ] = true;
  13269. }
  13270. }
  13271. function disable( id ) {
  13272. if ( enabledCapabilities[ id ] !== false ) {
  13273. gl.disable( id );
  13274. enabledCapabilities[ id ] = false;
  13275. }
  13276. }
  13277. function bindFramebuffer( target, framebuffer ) {
  13278. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13279. gl.bindFramebuffer( target, framebuffer );
  13280. currentBoundFramebuffers[ target ] = framebuffer;
  13281. if ( isWebGL2 ) {
  13282. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13283. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13284. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13285. }
  13286. if ( target === gl.FRAMEBUFFER ) {
  13287. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13288. }
  13289. }
  13290. return true;
  13291. }
  13292. return false;
  13293. }
  13294. function drawBuffers( renderTarget, framebuffer ) {
  13295. let drawBuffers = defaultDrawbuffers;
  13296. let needsUpdate = false;
  13297. if ( renderTarget ) {
  13298. drawBuffers = currentDrawbuffers.get( framebuffer );
  13299. if ( drawBuffers === undefined ) {
  13300. drawBuffers = [];
  13301. currentDrawbuffers.set( framebuffer, drawBuffers );
  13302. }
  13303. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13304. const textures = renderTarget.texture;
  13305. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13306. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13307. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13308. }
  13309. drawBuffers.length = textures.length;
  13310. needsUpdate = true;
  13311. }
  13312. } else {
  13313. if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13314. drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0;
  13315. needsUpdate = true;
  13316. }
  13317. }
  13318. } else {
  13319. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13320. drawBuffers[ 0 ] = gl.BACK;
  13321. needsUpdate = true;
  13322. }
  13323. }
  13324. if ( needsUpdate ) {
  13325. if ( capabilities.isWebGL2 ) {
  13326. gl.drawBuffers( drawBuffers );
  13327. } else {
  13328. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13329. }
  13330. }
  13331. }
  13332. function useProgram( program ) {
  13333. if ( currentProgram !== program ) {
  13334. gl.useProgram( program );
  13335. currentProgram = program;
  13336. return true;
  13337. }
  13338. return false;
  13339. }
  13340. const equationToGL = {
  13341. [ AddEquation ]: gl.FUNC_ADD,
  13342. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13343. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13344. };
  13345. if ( isWebGL2 ) {
  13346. equationToGL[ MinEquation ] = gl.MIN;
  13347. equationToGL[ MaxEquation ] = gl.MAX;
  13348. } else {
  13349. const extension = extensions.get( 'EXT_blend_minmax' );
  13350. if ( extension !== null ) {
  13351. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13352. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13353. }
  13354. }
  13355. const factorToGL = {
  13356. [ ZeroFactor ]: gl.ZERO,
  13357. [ OneFactor ]: gl.ONE,
  13358. [ SrcColorFactor ]: gl.SRC_COLOR,
  13359. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13360. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13361. [ DstColorFactor ]: gl.DST_COLOR,
  13362. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13363. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13364. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13365. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13366. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  13367. };
  13368. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13369. if ( blending === NoBlending ) {
  13370. if ( currentBlendingEnabled === true ) {
  13371. disable( gl.BLEND );
  13372. currentBlendingEnabled = false;
  13373. }
  13374. return;
  13375. }
  13376. if ( currentBlendingEnabled === false ) {
  13377. enable( gl.BLEND );
  13378. currentBlendingEnabled = true;
  13379. }
  13380. if ( blending !== CustomBlending ) {
  13381. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13382. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13383. gl.blendEquation( gl.FUNC_ADD );
  13384. currentBlendEquation = AddEquation;
  13385. currentBlendEquationAlpha = AddEquation;
  13386. }
  13387. if ( premultipliedAlpha ) {
  13388. switch ( blending ) {
  13389. case NormalBlending:
  13390. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13391. break;
  13392. case AdditiveBlending:
  13393. gl.blendFunc( gl.ONE, gl.ONE );
  13394. break;
  13395. case SubtractiveBlending:
  13396. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13397. break;
  13398. case MultiplyBlending:
  13399. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  13400. break;
  13401. default:
  13402. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13403. break;
  13404. }
  13405. } else {
  13406. switch ( blending ) {
  13407. case NormalBlending:
  13408. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13409. break;
  13410. case AdditiveBlending:
  13411. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  13412. break;
  13413. case SubtractiveBlending:
  13414. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13415. break;
  13416. case MultiplyBlending:
  13417. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  13418. break;
  13419. default:
  13420. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13421. break;
  13422. }
  13423. }
  13424. currentBlendSrc = null;
  13425. currentBlendDst = null;
  13426. currentBlendSrcAlpha = null;
  13427. currentBlendDstAlpha = null;
  13428. currentBlending = blending;
  13429. currentPremultipledAlpha = premultipliedAlpha;
  13430. }
  13431. return;
  13432. }
  13433. // custom blending
  13434. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13435. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13436. blendDstAlpha = blendDstAlpha || blendDst;
  13437. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13438. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13439. currentBlendEquation = blendEquation;
  13440. currentBlendEquationAlpha = blendEquationAlpha;
  13441. }
  13442. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13443. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13444. currentBlendSrc = blendSrc;
  13445. currentBlendDst = blendDst;
  13446. currentBlendSrcAlpha = blendSrcAlpha;
  13447. currentBlendDstAlpha = blendDstAlpha;
  13448. }
  13449. currentBlending = blending;
  13450. currentPremultipledAlpha = false;
  13451. }
  13452. function setMaterial( material, frontFaceCW ) {
  13453. material.side === DoubleSide
  13454. ? disable( gl.CULL_FACE )
  13455. : enable( gl.CULL_FACE );
  13456. let flipSided = ( material.side === BackSide );
  13457. if ( frontFaceCW ) flipSided = ! flipSided;
  13458. setFlipSided( flipSided );
  13459. ( material.blending === NormalBlending && material.transparent === false )
  13460. ? setBlending( NoBlending )
  13461. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13462. depthBuffer.setFunc( material.depthFunc );
  13463. depthBuffer.setTest( material.depthTest );
  13464. depthBuffer.setMask( material.depthWrite );
  13465. colorBuffer.setMask( material.colorWrite );
  13466. const stencilWrite = material.stencilWrite;
  13467. stencilBuffer.setTest( stencilWrite );
  13468. if ( stencilWrite ) {
  13469. stencilBuffer.setMask( material.stencilWriteMask );
  13470. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13471. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13472. }
  13473. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13474. material.alphaToCoverage === true
  13475. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  13476. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13477. }
  13478. //
  13479. function setFlipSided( flipSided ) {
  13480. if ( currentFlipSided !== flipSided ) {
  13481. if ( flipSided ) {
  13482. gl.frontFace( gl.CW );
  13483. } else {
  13484. gl.frontFace( gl.CCW );
  13485. }
  13486. currentFlipSided = flipSided;
  13487. }
  13488. }
  13489. function setCullFace( cullFace ) {
  13490. if ( cullFace !== CullFaceNone ) {
  13491. enable( gl.CULL_FACE );
  13492. if ( cullFace !== currentCullFace ) {
  13493. if ( cullFace === CullFaceBack ) {
  13494. gl.cullFace( gl.BACK );
  13495. } else if ( cullFace === CullFaceFront ) {
  13496. gl.cullFace( gl.FRONT );
  13497. } else {
  13498. gl.cullFace( gl.FRONT_AND_BACK );
  13499. }
  13500. }
  13501. } else {
  13502. disable( gl.CULL_FACE );
  13503. }
  13504. currentCullFace = cullFace;
  13505. }
  13506. function setLineWidth( width ) {
  13507. if ( width !== currentLineWidth ) {
  13508. if ( lineWidthAvailable ) gl.lineWidth( width );
  13509. currentLineWidth = width;
  13510. }
  13511. }
  13512. function setPolygonOffset( polygonOffset, factor, units ) {
  13513. if ( polygonOffset ) {
  13514. enable( gl.POLYGON_OFFSET_FILL );
  13515. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13516. gl.polygonOffset( factor, units );
  13517. currentPolygonOffsetFactor = factor;
  13518. currentPolygonOffsetUnits = units;
  13519. }
  13520. } else {
  13521. disable( gl.POLYGON_OFFSET_FILL );
  13522. }
  13523. }
  13524. function setScissorTest( scissorTest ) {
  13525. if ( scissorTest ) {
  13526. enable( gl.SCISSOR_TEST );
  13527. } else {
  13528. disable( gl.SCISSOR_TEST );
  13529. }
  13530. }
  13531. // texture
  13532. function activeTexture( webglSlot ) {
  13533. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13534. if ( currentTextureSlot !== webglSlot ) {
  13535. gl.activeTexture( webglSlot );
  13536. currentTextureSlot = webglSlot;
  13537. }
  13538. }
  13539. function bindTexture( webglType, webglTexture, webglSlot ) {
  13540. if ( webglSlot === undefined ) {
  13541. if ( currentTextureSlot === null ) {
  13542. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13543. } else {
  13544. webglSlot = currentTextureSlot;
  13545. }
  13546. }
  13547. let boundTexture = currentBoundTextures[ webglSlot ];
  13548. if ( boundTexture === undefined ) {
  13549. boundTexture = { type: undefined, texture: undefined };
  13550. currentBoundTextures[ webglSlot ] = boundTexture;
  13551. }
  13552. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13553. if ( currentTextureSlot !== webglSlot ) {
  13554. gl.activeTexture( webglSlot );
  13555. currentTextureSlot = webglSlot;
  13556. }
  13557. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13558. boundTexture.type = webglType;
  13559. boundTexture.texture = webglTexture;
  13560. }
  13561. }
  13562. function unbindTexture() {
  13563. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13564. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13565. gl.bindTexture( boundTexture.type, null );
  13566. boundTexture.type = undefined;
  13567. boundTexture.texture = undefined;
  13568. }
  13569. }
  13570. function compressedTexImage2D() {
  13571. try {
  13572. gl.compressedTexImage2D.apply( gl, arguments );
  13573. } catch ( error ) {
  13574. console.error( 'THREE.WebGLState:', error );
  13575. }
  13576. }
  13577. function compressedTexImage3D() {
  13578. try {
  13579. gl.compressedTexImage3D.apply( gl, arguments );
  13580. } catch ( error ) {
  13581. console.error( 'THREE.WebGLState:', error );
  13582. }
  13583. }
  13584. function texSubImage2D() {
  13585. try {
  13586. gl.texSubImage2D.apply( gl, arguments );
  13587. } catch ( error ) {
  13588. console.error( 'THREE.WebGLState:', error );
  13589. }
  13590. }
  13591. function texSubImage3D() {
  13592. try {
  13593. gl.texSubImage3D.apply( gl, arguments );
  13594. } catch ( error ) {
  13595. console.error( 'THREE.WebGLState:', error );
  13596. }
  13597. }
  13598. function compressedTexSubImage2D() {
  13599. try {
  13600. gl.compressedTexSubImage2D.apply( gl, arguments );
  13601. } catch ( error ) {
  13602. console.error( 'THREE.WebGLState:', error );
  13603. }
  13604. }
  13605. function compressedTexSubImage3D() {
  13606. try {
  13607. gl.compressedTexSubImage3D.apply( gl, arguments );
  13608. } catch ( error ) {
  13609. console.error( 'THREE.WebGLState:', error );
  13610. }
  13611. }
  13612. function texStorage2D() {
  13613. try {
  13614. gl.texStorage2D.apply( gl, arguments );
  13615. } catch ( error ) {
  13616. console.error( 'THREE.WebGLState:', error );
  13617. }
  13618. }
  13619. function texStorage3D() {
  13620. try {
  13621. gl.texStorage3D.apply( gl, arguments );
  13622. } catch ( error ) {
  13623. console.error( 'THREE.WebGLState:', error );
  13624. }
  13625. }
  13626. function texImage2D() {
  13627. try {
  13628. gl.texImage2D.apply( gl, arguments );
  13629. } catch ( error ) {
  13630. console.error( 'THREE.WebGLState:', error );
  13631. }
  13632. }
  13633. function texImage3D() {
  13634. try {
  13635. gl.texImage3D.apply( gl, arguments );
  13636. } catch ( error ) {
  13637. console.error( 'THREE.WebGLState:', error );
  13638. }
  13639. }
  13640. //
  13641. function scissor( scissor ) {
  13642. if ( currentScissor.equals( scissor ) === false ) {
  13643. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13644. currentScissor.copy( scissor );
  13645. }
  13646. }
  13647. function viewport( viewport ) {
  13648. if ( currentViewport.equals( viewport ) === false ) {
  13649. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13650. currentViewport.copy( viewport );
  13651. }
  13652. }
  13653. function updateUBOMapping( uniformsGroup, program ) {
  13654. let mapping = uboProgramMap.get( program );
  13655. if ( mapping === undefined ) {
  13656. mapping = new WeakMap();
  13657. uboProgramMap.set( program, mapping );
  13658. }
  13659. let blockIndex = mapping.get( uniformsGroup );
  13660. if ( blockIndex === undefined ) {
  13661. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13662. mapping.set( uniformsGroup, blockIndex );
  13663. }
  13664. }
  13665. function uniformBlockBinding( uniformsGroup, program ) {
  13666. const mapping = uboProgramMap.get( program );
  13667. const blockIndex = mapping.get( uniformsGroup );
  13668. if ( uboBindings.get( program ) !== blockIndex ) {
  13669. // bind shader specific block index to global block point
  13670. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13671. uboBindings.set( program, blockIndex );
  13672. }
  13673. }
  13674. //
  13675. function reset() {
  13676. // reset state
  13677. gl.disable( gl.BLEND );
  13678. gl.disable( gl.CULL_FACE );
  13679. gl.disable( gl.DEPTH_TEST );
  13680. gl.disable( gl.POLYGON_OFFSET_FILL );
  13681. gl.disable( gl.SCISSOR_TEST );
  13682. gl.disable( gl.STENCIL_TEST );
  13683. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13684. gl.blendEquation( gl.FUNC_ADD );
  13685. gl.blendFunc( gl.ONE, gl.ZERO );
  13686. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  13687. gl.colorMask( true, true, true, true );
  13688. gl.clearColor( 0, 0, 0, 0 );
  13689. gl.depthMask( true );
  13690. gl.depthFunc( gl.LESS );
  13691. gl.clearDepth( 1 );
  13692. gl.stencilMask( 0xffffffff );
  13693. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  13694. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  13695. gl.clearStencil( 0 );
  13696. gl.cullFace( gl.BACK );
  13697. gl.frontFace( gl.CCW );
  13698. gl.polygonOffset( 0, 0 );
  13699. gl.activeTexture( gl.TEXTURE0 );
  13700. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  13701. if ( isWebGL2 === true ) {
  13702. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  13703. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  13704. }
  13705. gl.useProgram( null );
  13706. gl.lineWidth( 1 );
  13707. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13708. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13709. // reset internals
  13710. enabledCapabilities = {};
  13711. currentTextureSlot = null;
  13712. currentBoundTextures = {};
  13713. currentBoundFramebuffers = {};
  13714. currentDrawbuffers = new WeakMap();
  13715. defaultDrawbuffers = [];
  13716. currentProgram = null;
  13717. currentBlendingEnabled = false;
  13718. currentBlending = null;
  13719. currentBlendEquation = null;
  13720. currentBlendSrc = null;
  13721. currentBlendDst = null;
  13722. currentBlendEquationAlpha = null;
  13723. currentBlendSrcAlpha = null;
  13724. currentBlendDstAlpha = null;
  13725. currentPremultipledAlpha = false;
  13726. currentFlipSided = null;
  13727. currentCullFace = null;
  13728. currentLineWidth = null;
  13729. currentPolygonOffsetFactor = null;
  13730. currentPolygonOffsetUnits = null;
  13731. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13732. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13733. colorBuffer.reset();
  13734. depthBuffer.reset();
  13735. stencilBuffer.reset();
  13736. }
  13737. return {
  13738. buffers: {
  13739. color: colorBuffer,
  13740. depth: depthBuffer,
  13741. stencil: stencilBuffer
  13742. },
  13743. enable: enable,
  13744. disable: disable,
  13745. bindFramebuffer: bindFramebuffer,
  13746. drawBuffers: drawBuffers,
  13747. useProgram: useProgram,
  13748. setBlending: setBlending,
  13749. setMaterial: setMaterial,
  13750. setFlipSided: setFlipSided,
  13751. setCullFace: setCullFace,
  13752. setLineWidth: setLineWidth,
  13753. setPolygonOffset: setPolygonOffset,
  13754. setScissorTest: setScissorTest,
  13755. activeTexture: activeTexture,
  13756. bindTexture: bindTexture,
  13757. unbindTexture: unbindTexture,
  13758. compressedTexImage2D: compressedTexImage2D,
  13759. compressedTexImage3D: compressedTexImage3D,
  13760. texImage2D: texImage2D,
  13761. texImage3D: texImage3D,
  13762. updateUBOMapping: updateUBOMapping,
  13763. uniformBlockBinding: uniformBlockBinding,
  13764. texStorage2D: texStorage2D,
  13765. texStorage3D: texStorage3D,
  13766. texSubImage2D: texSubImage2D,
  13767. texSubImage3D: texSubImage3D,
  13768. compressedTexSubImage2D: compressedTexSubImage2D,
  13769. compressedTexSubImage3D: compressedTexSubImage3D,
  13770. scissor: scissor,
  13771. viewport: viewport,
  13772. reset: reset
  13773. };
  13774. }
  13775. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13776. const isWebGL2 = capabilities.isWebGL2;
  13777. const maxTextures = capabilities.maxTextures;
  13778. const maxCubemapSize = capabilities.maxCubemapSize;
  13779. const maxTextureSize = capabilities.maxTextureSize;
  13780. const maxSamples = capabilities.maxSamples;
  13781. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13782. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  13783. const _videoTextures = new WeakMap();
  13784. let _canvas;
  13785. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13786. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13787. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13788. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13789. let useOffscreenCanvas = false;
  13790. try {
  13791. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13792. // eslint-disable-next-line compat/compat
  13793. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13794. } catch ( err ) {
  13795. // Ignore any errors
  13796. }
  13797. function createCanvas( width, height ) {
  13798. // Use OffscreenCanvas when available. Specially needed in web workers
  13799. return useOffscreenCanvas ?
  13800. // eslint-disable-next-line compat/compat
  13801. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13802. }
  13803. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13804. let scale = 1;
  13805. // handle case if texture exceeds max size
  13806. if ( image.width > maxSize || image.height > maxSize ) {
  13807. scale = maxSize / Math.max( image.width, image.height );
  13808. }
  13809. // only perform resize if necessary
  13810. if ( scale < 1 || needsPowerOfTwo === true ) {
  13811. // only perform resize for certain image types
  13812. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13813. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13814. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13815. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13816. const width = floor( scale * image.width );
  13817. const height = floor( scale * image.height );
  13818. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13819. // cube textures can't reuse the same canvas
  13820. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13821. canvas.width = width;
  13822. canvas.height = height;
  13823. const context = canvas.getContext( '2d' );
  13824. context.drawImage( image, 0, 0, width, height );
  13825. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13826. return canvas;
  13827. } else {
  13828. if ( 'data' in image ) {
  13829. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13830. }
  13831. return image;
  13832. }
  13833. }
  13834. return image;
  13835. }
  13836. function isPowerOfTwo$1( image ) {
  13837. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13838. }
  13839. function textureNeedsPowerOfTwo( texture ) {
  13840. if ( isWebGL2 ) return false;
  13841. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13842. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13843. }
  13844. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13845. return texture.generateMipmaps && supportsMips &&
  13846. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13847. }
  13848. function generateMipmap( target ) {
  13849. _gl.generateMipmap( target );
  13850. }
  13851. function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) {
  13852. if ( isWebGL2 === false ) return glFormat;
  13853. if ( internalFormatName !== null ) {
  13854. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13855. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13856. }
  13857. let internalFormat = glFormat;
  13858. if ( glFormat === _gl.RED ) {
  13859. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  13860. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  13861. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  13862. }
  13863. if ( glFormat === _gl.RG ) {
  13864. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  13865. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  13866. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  13867. }
  13868. if ( glFormat === _gl.RGBA ) {
  13869. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  13870. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  13871. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13872. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  13873. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  13874. }
  13875. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  13876. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  13877. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  13878. extensions.get( 'EXT_color_buffer_float' );
  13879. }
  13880. return internalFormat;
  13881. }
  13882. function getMipLevels( texture, image, supportsMips ) {
  13883. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  13884. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13885. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  13886. // user-defined mipmaps
  13887. return texture.mipmaps.length;
  13888. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  13889. return image.mipmaps.length;
  13890. } else {
  13891. // texture without mipmaps (only base level)
  13892. return 1;
  13893. }
  13894. }
  13895. // Fallback filters for non-power-of-2 textures
  13896. function filterFallback( f ) {
  13897. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13898. return _gl.NEAREST;
  13899. }
  13900. return _gl.LINEAR;
  13901. }
  13902. //
  13903. function onTextureDispose( event ) {
  13904. const texture = event.target;
  13905. texture.removeEventListener( 'dispose', onTextureDispose );
  13906. deallocateTexture( texture );
  13907. if ( texture.isVideoTexture ) {
  13908. _videoTextures.delete( texture );
  13909. }
  13910. }
  13911. function onRenderTargetDispose( event ) {
  13912. const renderTarget = event.target;
  13913. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13914. deallocateRenderTarget( renderTarget );
  13915. }
  13916. //
  13917. function deallocateTexture( texture ) {
  13918. const textureProperties = properties.get( texture );
  13919. if ( textureProperties.__webglInit === undefined ) return;
  13920. // check if it's necessary to remove the WebGLTexture object
  13921. const source = texture.source;
  13922. const webglTextures = _sources.get( source );
  13923. if ( webglTextures ) {
  13924. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13925. webglTexture.usedTimes --;
  13926. // the WebGLTexture object is not used anymore, remove it
  13927. if ( webglTexture.usedTimes === 0 ) {
  13928. deleteTexture( texture );
  13929. }
  13930. // remove the weak map entry if no WebGLTexture uses the source anymore
  13931. if ( Object.keys( webglTextures ).length === 0 ) {
  13932. _sources.delete( source );
  13933. }
  13934. }
  13935. properties.remove( texture );
  13936. }
  13937. function deleteTexture( texture ) {
  13938. const textureProperties = properties.get( texture );
  13939. _gl.deleteTexture( textureProperties.__webglTexture );
  13940. const source = texture.source;
  13941. const webglTextures = _sources.get( source );
  13942. delete webglTextures[ textureProperties.__cacheKey ];
  13943. info.memory.textures --;
  13944. }
  13945. function deallocateRenderTarget( renderTarget ) {
  13946. const texture = renderTarget.texture;
  13947. const renderTargetProperties = properties.get( renderTarget );
  13948. const textureProperties = properties.get( texture );
  13949. if ( textureProperties.__webglTexture !== undefined ) {
  13950. _gl.deleteTexture( textureProperties.__webglTexture );
  13951. info.memory.textures --;
  13952. }
  13953. if ( renderTarget.depthTexture ) {
  13954. renderTarget.depthTexture.dispose();
  13955. }
  13956. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13957. for ( let i = 0; i < 6; i ++ ) {
  13958. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13959. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13960. }
  13961. } else {
  13962. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13963. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13964. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13965. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  13966. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  13967. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  13968. }
  13969. }
  13970. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13971. }
  13972. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13973. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13974. const attachmentProperties = properties.get( texture[ i ] );
  13975. if ( attachmentProperties.__webglTexture ) {
  13976. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13977. info.memory.textures --;
  13978. }
  13979. properties.remove( texture[ i ] );
  13980. }
  13981. }
  13982. properties.remove( texture );
  13983. properties.remove( renderTarget );
  13984. }
  13985. //
  13986. let textureUnits = 0;
  13987. function resetTextureUnits() {
  13988. textureUnits = 0;
  13989. }
  13990. function allocateTextureUnit() {
  13991. const textureUnit = textureUnits;
  13992. if ( textureUnit >= maxTextures ) {
  13993. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13994. }
  13995. textureUnits += 1;
  13996. return textureUnit;
  13997. }
  13998. function getTextureCacheKey( texture ) {
  13999. const array = [];
  14000. array.push( texture.wrapS );
  14001. array.push( texture.wrapT );
  14002. array.push( texture.wrapR || 0 );
  14003. array.push( texture.magFilter );
  14004. array.push( texture.minFilter );
  14005. array.push( texture.anisotropy );
  14006. array.push( texture.internalFormat );
  14007. array.push( texture.format );
  14008. array.push( texture.type );
  14009. array.push( texture.generateMipmaps );
  14010. array.push( texture.premultiplyAlpha );
  14011. array.push( texture.flipY );
  14012. array.push( texture.unpackAlignment );
  14013. array.push( texture.encoding );
  14014. return array.join();
  14015. }
  14016. //
  14017. function setTexture2D( texture, slot ) {
  14018. const textureProperties = properties.get( texture );
  14019. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14020. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14021. const image = texture.image;
  14022. if ( image === null ) {
  14023. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14024. } else if ( image.complete === false ) {
  14025. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14026. } else {
  14027. uploadTexture( textureProperties, texture, slot );
  14028. return;
  14029. }
  14030. }
  14031. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14032. }
  14033. function setTexture2DArray( texture, slot ) {
  14034. const textureProperties = properties.get( texture );
  14035. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14036. uploadTexture( textureProperties, texture, slot );
  14037. return;
  14038. }
  14039. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14040. }
  14041. function setTexture3D( texture, slot ) {
  14042. const textureProperties = properties.get( texture );
  14043. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14044. uploadTexture( textureProperties, texture, slot );
  14045. return;
  14046. }
  14047. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14048. }
  14049. function setTextureCube( texture, slot ) {
  14050. const textureProperties = properties.get( texture );
  14051. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14052. uploadCubeTexture( textureProperties, texture, slot );
  14053. return;
  14054. }
  14055. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14056. }
  14057. const wrappingToGL = {
  14058. [ RepeatWrapping ]: _gl.REPEAT,
  14059. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  14060. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  14061. };
  14062. const filterToGL = {
  14063. [ NearestFilter ]: _gl.NEAREST,
  14064. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  14065. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  14066. [ LinearFilter ]: _gl.LINEAR,
  14067. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  14068. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  14069. };
  14070. function setTextureParameters( textureType, texture, supportsMips ) {
  14071. if ( supportsMips ) {
  14072. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  14073. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  14074. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14075. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  14076. }
  14077. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  14078. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  14079. } else {
  14080. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14081. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14082. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14083. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );
  14084. }
  14085. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14086. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14087. }
  14088. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14089. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14090. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14091. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14092. }
  14093. }
  14094. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14095. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14096. if ( texture.magFilter === NearestFilter ) return;
  14097. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14098. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14099. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14100. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14101. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14102. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14103. }
  14104. }
  14105. }
  14106. function initTexture( textureProperties, texture ) {
  14107. let forceUpload = false;
  14108. if ( textureProperties.__webglInit === undefined ) {
  14109. textureProperties.__webglInit = true;
  14110. texture.addEventListener( 'dispose', onTextureDispose );
  14111. }
  14112. // create Source <-> WebGLTextures mapping if necessary
  14113. const source = texture.source;
  14114. let webglTextures = _sources.get( source );
  14115. if ( webglTextures === undefined ) {
  14116. webglTextures = {};
  14117. _sources.set( source, webglTextures );
  14118. }
  14119. // check if there is already a WebGLTexture object for the given texture parameters
  14120. const textureCacheKey = getTextureCacheKey( texture );
  14121. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14122. // if not, create a new instance of WebGLTexture
  14123. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14124. // create new entry
  14125. webglTextures[ textureCacheKey ] = {
  14126. texture: _gl.createTexture(),
  14127. usedTimes: 0
  14128. };
  14129. info.memory.textures ++;
  14130. // when a new instance of WebGLTexture was created, a texture upload is required
  14131. // even if the image contents are identical
  14132. forceUpload = true;
  14133. }
  14134. webglTextures[ textureCacheKey ].usedTimes ++;
  14135. // every time the texture cache key changes, it's necessary to check if an instance of
  14136. // WebGLTexture can be deleted in order to avoid a memory leak.
  14137. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14138. if ( webglTexture !== undefined ) {
  14139. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14140. if ( webglTexture.usedTimes === 0 ) {
  14141. deleteTexture( texture );
  14142. }
  14143. }
  14144. // store references to cache key and WebGLTexture object
  14145. textureProperties.__cacheKey = textureCacheKey;
  14146. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14147. }
  14148. return forceUpload;
  14149. }
  14150. function uploadTexture( textureProperties, texture, slot ) {
  14151. let textureType = _gl.TEXTURE_2D;
  14152. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  14153. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  14154. const forceUpload = initTexture( textureProperties, texture );
  14155. const source = texture.source;
  14156. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14157. const sourceProperties = properties.get( source );
  14158. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14159. state.activeTexture( _gl.TEXTURE0 + slot );
  14160. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14161. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14162. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14163. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  14164. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14165. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  14166. image = verifyColorSpace( texture, image );
  14167. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14168. glFormat = utils.convert( texture.format, texture.encoding );
  14169. let glType = utils.convert( texture.type ),
  14170. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  14171. setTextureParameters( textureType, texture, supportsMips );
  14172. let mipmap;
  14173. const mipmaps = texture.mipmaps;
  14174. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14175. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14176. const levels = getMipLevels( texture, image, supportsMips );
  14177. if ( texture.isDepthTexture ) {
  14178. // populate depth texture with dummy data
  14179. glInternalFormat = _gl.DEPTH_COMPONENT;
  14180. if ( isWebGL2 ) {
  14181. if ( texture.type === FloatType ) {
  14182. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14183. } else if ( texture.type === UnsignedIntType ) {
  14184. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14185. } else if ( texture.type === UnsignedInt248Type ) {
  14186. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14187. } else {
  14188. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  14189. }
  14190. } else {
  14191. if ( texture.type === FloatType ) {
  14192. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14193. }
  14194. }
  14195. // validation checks for WebGL 1
  14196. if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14197. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14198. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14199. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14200. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14201. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14202. texture.type = UnsignedIntType;
  14203. glType = utils.convert( texture.type );
  14204. }
  14205. }
  14206. if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14207. // Depth stencil textures need the DEPTH_STENCIL internal format
  14208. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14209. glInternalFormat = _gl.DEPTH_STENCIL;
  14210. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14211. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14212. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14213. if ( texture.type !== UnsignedInt248Type ) {
  14214. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14215. texture.type = UnsignedInt248Type;
  14216. glType = utils.convert( texture.type );
  14217. }
  14218. }
  14219. //
  14220. if ( allocateMemory ) {
  14221. if ( useTexStorage ) {
  14222. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  14223. } else {
  14224. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14225. }
  14226. }
  14227. } else if ( texture.isDataTexture ) {
  14228. // use manually created mipmaps if available
  14229. // if there are no manual mipmaps
  14230. // set 0 level mipmap and then use GL to generate other mipmap levels
  14231. if ( mipmaps.length > 0 && supportsMips ) {
  14232. if ( useTexStorage && allocateMemory ) {
  14233. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14234. }
  14235. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14236. mipmap = mipmaps[ i ];
  14237. if ( useTexStorage ) {
  14238. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14239. } else {
  14240. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14241. }
  14242. }
  14243. texture.generateMipmaps = false;
  14244. } else {
  14245. if ( useTexStorage ) {
  14246. if ( allocateMemory ) {
  14247. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14248. }
  14249. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14250. } else {
  14251. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14252. }
  14253. }
  14254. } else if ( texture.isCompressedTexture ) {
  14255. if ( texture.isCompressedArrayTexture ) {
  14256. if ( useTexStorage && allocateMemory ) {
  14257. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14258. }
  14259. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14260. mipmap = mipmaps[ i ];
  14261. if ( texture.format !== RGBAFormat ) {
  14262. if ( glFormat !== null ) {
  14263. if ( useTexStorage ) {
  14264. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14265. } else {
  14266. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14267. }
  14268. } else {
  14269. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14270. }
  14271. } else {
  14272. if ( useTexStorage ) {
  14273. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14274. } else {
  14275. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14276. }
  14277. }
  14278. }
  14279. } else {
  14280. if ( useTexStorage && allocateMemory ) {
  14281. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14282. }
  14283. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14284. mipmap = mipmaps[ i ];
  14285. if ( texture.format !== RGBAFormat ) {
  14286. if ( glFormat !== null ) {
  14287. if ( useTexStorage ) {
  14288. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14289. } else {
  14290. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14291. }
  14292. } else {
  14293. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14294. }
  14295. } else {
  14296. if ( useTexStorage ) {
  14297. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14298. } else {
  14299. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14300. }
  14301. }
  14302. }
  14303. }
  14304. } else if ( texture.isDataArrayTexture ) {
  14305. if ( useTexStorage ) {
  14306. if ( allocateMemory ) {
  14307. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  14308. }
  14309. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14310. } else {
  14311. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14312. }
  14313. } else if ( texture.isData3DTexture ) {
  14314. if ( useTexStorage ) {
  14315. if ( allocateMemory ) {
  14316. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  14317. }
  14318. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14319. } else {
  14320. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14321. }
  14322. } else if ( texture.isFramebufferTexture ) {
  14323. if ( allocateMemory ) {
  14324. if ( useTexStorage ) {
  14325. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14326. } else {
  14327. let width = image.width, height = image.height;
  14328. for ( let i = 0; i < levels; i ++ ) {
  14329. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14330. width >>= 1;
  14331. height >>= 1;
  14332. }
  14333. }
  14334. }
  14335. } else {
  14336. // regular Texture (image, video, canvas)
  14337. // use manually created mipmaps if available
  14338. // if there are no manual mipmaps
  14339. // set 0 level mipmap and then use GL to generate other mipmap levels
  14340. if ( mipmaps.length > 0 && supportsMips ) {
  14341. if ( useTexStorage && allocateMemory ) {
  14342. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14343. }
  14344. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14345. mipmap = mipmaps[ i ];
  14346. if ( useTexStorage ) {
  14347. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  14348. } else {
  14349. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  14350. }
  14351. }
  14352. texture.generateMipmaps = false;
  14353. } else {
  14354. if ( useTexStorage ) {
  14355. if ( allocateMemory ) {
  14356. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14357. }
  14358. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  14359. } else {
  14360. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  14361. }
  14362. }
  14363. }
  14364. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14365. generateMipmap( textureType );
  14366. }
  14367. sourceProperties.__version = source.version;
  14368. if ( texture.onUpdate ) texture.onUpdate( texture );
  14369. }
  14370. textureProperties.__version = texture.version;
  14371. }
  14372. function uploadCubeTexture( textureProperties, texture, slot ) {
  14373. if ( texture.image.length !== 6 ) return;
  14374. const forceUpload = initTexture( textureProperties, texture );
  14375. const source = texture.source;
  14376. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14377. const sourceProperties = properties.get( source );
  14378. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14379. state.activeTexture( _gl.TEXTURE0 + slot );
  14380. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14381. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14382. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14383. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  14384. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14385. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14386. const cubeImage = [];
  14387. for ( let i = 0; i < 6; i ++ ) {
  14388. if ( ! isCompressed && ! isDataTexture ) {
  14389. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14390. } else {
  14391. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14392. }
  14393. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14394. }
  14395. const image = cubeImage[ 0 ],
  14396. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14397. glFormat = utils.convert( texture.format, texture.encoding ),
  14398. glType = utils.convert( texture.type ),
  14399. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14400. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14401. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14402. let levels = getMipLevels( texture, image, supportsMips );
  14403. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14404. let mipmaps;
  14405. if ( isCompressed ) {
  14406. if ( useTexStorage && allocateMemory ) {
  14407. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  14408. }
  14409. for ( let i = 0; i < 6; i ++ ) {
  14410. mipmaps = cubeImage[ i ].mipmaps;
  14411. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14412. const mipmap = mipmaps[ j ];
  14413. if ( texture.format !== RGBAFormat ) {
  14414. if ( glFormat !== null ) {
  14415. if ( useTexStorage ) {
  14416. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14417. } else {
  14418. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14419. }
  14420. } else {
  14421. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14422. }
  14423. } else {
  14424. if ( useTexStorage ) {
  14425. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14426. } else {
  14427. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14428. }
  14429. }
  14430. }
  14431. }
  14432. } else {
  14433. mipmaps = texture.mipmaps;
  14434. if ( useTexStorage && allocateMemory ) {
  14435. // TODO: Uniformly handle mipmap definitions
  14436. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14437. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14438. if ( mipmaps.length > 0 ) levels ++;
  14439. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14440. }
  14441. for ( let i = 0; i < 6; i ++ ) {
  14442. if ( isDataTexture ) {
  14443. if ( useTexStorage ) {
  14444. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14445. } else {
  14446. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14447. }
  14448. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14449. const mipmap = mipmaps[ j ];
  14450. const mipmapImage = mipmap.image[ i ].image;
  14451. if ( useTexStorage ) {
  14452. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14453. } else {
  14454. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14455. }
  14456. }
  14457. } else {
  14458. if ( useTexStorage ) {
  14459. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14460. } else {
  14461. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14462. }
  14463. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14464. const mipmap = mipmaps[ j ];
  14465. if ( useTexStorage ) {
  14466. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14467. } else {
  14468. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14469. }
  14470. }
  14471. }
  14472. }
  14473. }
  14474. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14475. // We assume images for cube map have the same size.
  14476. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14477. }
  14478. sourceProperties.__version = source.version;
  14479. if ( texture.onUpdate ) texture.onUpdate( texture );
  14480. }
  14481. textureProperties.__version = texture.version;
  14482. }
  14483. // Render targets
  14484. // Setup storage for target texture and bind it to correct framebuffer
  14485. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14486. const glFormat = utils.convert( texture.format, texture.encoding );
  14487. const glType = utils.convert( texture.type );
  14488. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14489. const renderTargetProperties = properties.get( renderTarget );
  14490. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14491. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  14492. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14493. } else {
  14494. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14495. }
  14496. }
  14497. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14498. if ( useMultisampledRTT( renderTarget ) ) {
  14499. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14500. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  14501. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14502. }
  14503. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14504. }
  14505. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14506. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14507. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14508. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14509. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14510. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14511. const depthTexture = renderTarget.depthTexture;
  14512. if ( depthTexture && depthTexture.isDepthTexture ) {
  14513. if ( depthTexture.type === FloatType ) {
  14514. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14515. } else if ( depthTexture.type === UnsignedIntType ) {
  14516. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14517. }
  14518. }
  14519. const samples = getRenderTargetSamples( renderTarget );
  14520. if ( useMultisampledRTT( renderTarget ) ) {
  14521. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14522. } else {
  14523. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14524. }
  14525. } else {
  14526. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14527. }
  14528. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14529. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14530. const samples = getRenderTargetSamples( renderTarget );
  14531. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14532. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14533. } else if ( useMultisampledRTT( renderTarget ) ) {
  14534. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14535. } else {
  14536. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14537. }
  14538. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14539. } else {
  14540. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14541. for ( let i = 0; i < textures.length; i ++ ) {
  14542. const texture = textures[ i ];
  14543. const glFormat = utils.convert( texture.format, texture.encoding );
  14544. const glType = utils.convert( texture.type );
  14545. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14546. const samples = getRenderTargetSamples( renderTarget );
  14547. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14548. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14549. } else if ( useMultisampledRTT( renderTarget ) ) {
  14550. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14551. } else {
  14552. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14553. }
  14554. }
  14555. }
  14556. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14557. }
  14558. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14559. function setupDepthTexture( framebuffer, renderTarget ) {
  14560. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14561. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14562. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14563. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14564. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14565. }
  14566. // upload an empty depth texture with framebuffer size
  14567. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14568. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14569. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14570. renderTarget.depthTexture.image.width = renderTarget.width;
  14571. renderTarget.depthTexture.image.height = renderTarget.height;
  14572. renderTarget.depthTexture.needsUpdate = true;
  14573. }
  14574. setTexture2D( renderTarget.depthTexture, 0 );
  14575. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14576. const samples = getRenderTargetSamples( renderTarget );
  14577. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14578. if ( useMultisampledRTT( renderTarget ) ) {
  14579. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14580. } else {
  14581. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14582. }
  14583. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14584. if ( useMultisampledRTT( renderTarget ) ) {
  14585. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14586. } else {
  14587. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14588. }
  14589. } else {
  14590. throw new Error( 'Unknown depthTexture format' );
  14591. }
  14592. }
  14593. // Setup GL resources for a non-texture depth buffer
  14594. function setupDepthRenderbuffer( renderTarget ) {
  14595. const renderTargetProperties = properties.get( renderTarget );
  14596. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14597. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14598. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14599. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14600. } else {
  14601. if ( isCube ) {
  14602. renderTargetProperties.__webglDepthbuffer = [];
  14603. for ( let i = 0; i < 6; i ++ ) {
  14604. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  14605. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14606. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14607. }
  14608. } else {
  14609. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14610. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14611. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14612. }
  14613. }
  14614. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14615. }
  14616. // rebind framebuffer with external textures
  14617. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14618. const renderTargetProperties = properties.get( renderTarget );
  14619. if ( colorTexture !== undefined ) {
  14620. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  14621. }
  14622. if ( depthTexture !== undefined ) {
  14623. setupDepthRenderbuffer( renderTarget );
  14624. }
  14625. }
  14626. // Set up GL resources for the render target
  14627. function setupRenderTarget( renderTarget ) {
  14628. const texture = renderTarget.texture;
  14629. const renderTargetProperties = properties.get( renderTarget );
  14630. const textureProperties = properties.get( texture );
  14631. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14632. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14633. if ( textureProperties.__webglTexture === undefined ) {
  14634. textureProperties.__webglTexture = _gl.createTexture();
  14635. }
  14636. textureProperties.__version = texture.version;
  14637. info.memory.textures ++;
  14638. }
  14639. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14640. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14641. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14642. // Setup framebuffer
  14643. if ( isCube ) {
  14644. renderTargetProperties.__webglFramebuffer = [];
  14645. for ( let i = 0; i < 6; i ++ ) {
  14646. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14647. }
  14648. } else {
  14649. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14650. if ( isMultipleRenderTargets ) {
  14651. if ( capabilities.drawBuffers ) {
  14652. const textures = renderTarget.texture;
  14653. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14654. const attachmentProperties = properties.get( textures[ i ] );
  14655. if ( attachmentProperties.__webglTexture === undefined ) {
  14656. attachmentProperties.__webglTexture = _gl.createTexture();
  14657. info.memory.textures ++;
  14658. }
  14659. }
  14660. } else {
  14661. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14662. }
  14663. }
  14664. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14665. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14666. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14667. renderTargetProperties.__webglColorRenderbuffer = [];
  14668. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14669. for ( let i = 0; i < textures.length; i ++ ) {
  14670. const texture = textures[ i ];
  14671. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14672. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14673. const glFormat = utils.convert( texture.format, texture.encoding );
  14674. const glType = utils.convert( texture.type );
  14675. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true );
  14676. const samples = getRenderTargetSamples( renderTarget );
  14677. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14678. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14679. }
  14680. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14681. if ( renderTarget.depthBuffer ) {
  14682. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14683. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14684. }
  14685. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14686. }
  14687. }
  14688. // Setup color buffer
  14689. if ( isCube ) {
  14690. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  14691. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14692. for ( let i = 0; i < 6; i ++ ) {
  14693. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14694. }
  14695. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14696. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14697. }
  14698. state.unbindTexture();
  14699. } else if ( isMultipleRenderTargets ) {
  14700. const textures = renderTarget.texture;
  14701. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14702. const attachment = textures[ i ];
  14703. const attachmentProperties = properties.get( attachment );
  14704. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  14705. setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips );
  14706. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D );
  14707. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14708. generateMipmap( _gl.TEXTURE_2D );
  14709. }
  14710. }
  14711. state.unbindTexture();
  14712. } else {
  14713. let glTextureType = _gl.TEXTURE_2D;
  14714. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14715. if ( isWebGL2 ) {
  14716. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14717. } else {
  14718. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14719. }
  14720. }
  14721. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14722. setTextureParameters( glTextureType, texture, supportsMips );
  14723. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType );
  14724. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14725. generateMipmap( glTextureType );
  14726. }
  14727. state.unbindTexture();
  14728. }
  14729. // Setup depth and stencil buffers
  14730. if ( renderTarget.depthBuffer ) {
  14731. setupDepthRenderbuffer( renderTarget );
  14732. }
  14733. }
  14734. function updateRenderTargetMipmap( renderTarget ) {
  14735. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14736. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14737. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14738. const texture = textures[ i ];
  14739. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14740. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14741. const webglTexture = properties.get( texture ).__webglTexture;
  14742. state.bindTexture( target, webglTexture );
  14743. generateMipmap( target );
  14744. state.unbindTexture();
  14745. }
  14746. }
  14747. }
  14748. function updateMultisampleRenderTarget( renderTarget ) {
  14749. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14750. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14751. const width = renderTarget.width;
  14752. const height = renderTarget.height;
  14753. let mask = _gl.COLOR_BUFFER_BIT;
  14754. const invalidationArray = [];
  14755. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14756. const renderTargetProperties = properties.get( renderTarget );
  14757. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14758. // If MRT we need to remove FBO attachments
  14759. if ( isMultipleRenderTargets ) {
  14760. for ( let i = 0; i < textures.length; i ++ ) {
  14761. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14762. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  14763. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14764. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  14765. }
  14766. }
  14767. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14768. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14769. for ( let i = 0; i < textures.length; i ++ ) {
  14770. invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );
  14771. if ( renderTarget.depthBuffer ) {
  14772. invalidationArray.push( depthStyle );
  14773. }
  14774. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14775. if ( ignoreDepthValues === false ) {
  14776. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  14777. if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  14778. }
  14779. if ( isMultipleRenderTargets ) {
  14780. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14781. }
  14782. if ( ignoreDepthValues === true ) {
  14783. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );
  14784. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  14785. }
  14786. if ( isMultipleRenderTargets ) {
  14787. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14788. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  14789. }
  14790. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  14791. if ( supportsInvalidateFramebuffer ) {
  14792. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );
  14793. }
  14794. }
  14795. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  14796. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  14797. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14798. if ( isMultipleRenderTargets ) {
  14799. for ( let i = 0; i < textures.length; i ++ ) {
  14800. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14801. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14802. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14803. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14804. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  14805. }
  14806. }
  14807. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14808. }
  14809. }
  14810. function getRenderTargetSamples( renderTarget ) {
  14811. return Math.min( maxSamples, renderTarget.samples );
  14812. }
  14813. function useMultisampledRTT( renderTarget ) {
  14814. const renderTargetProperties = properties.get( renderTarget );
  14815. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14816. }
  14817. function updateVideoTexture( texture ) {
  14818. const frame = info.render.frame;
  14819. // Check the last frame we updated the VideoTexture
  14820. if ( _videoTextures.get( texture ) !== frame ) {
  14821. _videoTextures.set( texture, frame );
  14822. texture.update();
  14823. }
  14824. }
  14825. function verifyColorSpace( texture, image ) {
  14826. const encoding = texture.encoding;
  14827. const format = texture.format;
  14828. const type = texture.type;
  14829. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14830. if ( encoding !== LinearEncoding ) {
  14831. // sRGB
  14832. if ( encoding === sRGBEncoding ) {
  14833. if ( isWebGL2 === false ) {
  14834. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14835. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14836. texture.format = _SRGBAFormat;
  14837. // it's not possible to generate mips in WebGL 1 with this extension
  14838. texture.minFilter = LinearFilter;
  14839. texture.generateMipmaps = false;
  14840. } else {
  14841. // slow fallback (CPU decode)
  14842. image = ImageUtils.sRGBToLinear( image );
  14843. }
  14844. } else {
  14845. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14846. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14847. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14848. }
  14849. }
  14850. } else {
  14851. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14852. }
  14853. }
  14854. return image;
  14855. }
  14856. //
  14857. this.allocateTextureUnit = allocateTextureUnit;
  14858. this.resetTextureUnits = resetTextureUnits;
  14859. this.setTexture2D = setTexture2D;
  14860. this.setTexture2DArray = setTexture2DArray;
  14861. this.setTexture3D = setTexture3D;
  14862. this.setTextureCube = setTextureCube;
  14863. this.rebindTextures = rebindTextures;
  14864. this.setupRenderTarget = setupRenderTarget;
  14865. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14866. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14867. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14868. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14869. this.useMultisampledRTT = useMultisampledRTT;
  14870. }
  14871. function WebGLUtils( gl, extensions, capabilities ) {
  14872. const isWebGL2 = capabilities.isWebGL2;
  14873. function convert( p, encoding = null ) {
  14874. let extension;
  14875. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  14876. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  14877. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  14878. if ( p === ByteType ) return gl.BYTE;
  14879. if ( p === ShortType ) return gl.SHORT;
  14880. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  14881. if ( p === IntType ) return gl.INT;
  14882. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  14883. if ( p === FloatType ) return gl.FLOAT;
  14884. if ( p === HalfFloatType ) {
  14885. if ( isWebGL2 ) return gl.HALF_FLOAT;
  14886. extension = extensions.get( 'OES_texture_half_float' );
  14887. if ( extension !== null ) {
  14888. return extension.HALF_FLOAT_OES;
  14889. } else {
  14890. return null;
  14891. }
  14892. }
  14893. if ( p === AlphaFormat ) return gl.ALPHA;
  14894. if ( p === RGBAFormat ) return gl.RGBA;
  14895. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  14896. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  14897. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  14898. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  14899. // WebGL 1 sRGB fallback
  14900. if ( p === _SRGBAFormat ) {
  14901. extension = extensions.get( 'EXT_sRGB' );
  14902. if ( extension !== null ) {
  14903. return extension.SRGB_ALPHA_EXT;
  14904. } else {
  14905. return null;
  14906. }
  14907. }
  14908. // WebGL2 formats.
  14909. if ( p === RedFormat ) return gl.RED;
  14910. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  14911. if ( p === RGFormat ) return gl.RG;
  14912. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  14913. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  14914. // S3TC
  14915. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14916. if ( encoding === sRGBEncoding ) {
  14917. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  14918. if ( extension !== null ) {
  14919. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14920. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14921. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14922. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14923. } else {
  14924. return null;
  14925. }
  14926. } else {
  14927. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14928. if ( extension !== null ) {
  14929. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14930. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14931. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14932. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14933. } else {
  14934. return null;
  14935. }
  14936. }
  14937. }
  14938. // PVRTC
  14939. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14940. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14941. if ( extension !== null ) {
  14942. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14943. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14944. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14945. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14946. } else {
  14947. return null;
  14948. }
  14949. }
  14950. // ETC1
  14951. if ( p === RGB_ETC1_Format ) {
  14952. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14953. if ( extension !== null ) {
  14954. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14955. } else {
  14956. return null;
  14957. }
  14958. }
  14959. // ETC2
  14960. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14961. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14962. if ( extension !== null ) {
  14963. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14964. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14965. } else {
  14966. return null;
  14967. }
  14968. }
  14969. // ASTC
  14970. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14971. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14972. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14973. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14974. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  14975. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14976. if ( extension !== null ) {
  14977. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14978. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14979. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14980. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14981. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14982. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14983. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14984. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14985. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14986. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14987. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14988. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14989. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14990. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14991. } else {
  14992. return null;
  14993. }
  14994. }
  14995. // BPTC
  14996. if ( p === RGBA_BPTC_Format ) {
  14997. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14998. if ( extension !== null ) {
  14999. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15000. } else {
  15001. return null;
  15002. }
  15003. }
  15004. // RGTC
  15005. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15006. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15007. if ( extension !== null ) {
  15008. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15009. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15010. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15011. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15012. } else {
  15013. return null;
  15014. }
  15015. }
  15016. //
  15017. if ( p === UnsignedInt248Type ) {
  15018. if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8;
  15019. extension = extensions.get( 'WEBGL_depth_texture' );
  15020. if ( extension !== null ) {
  15021. return extension.UNSIGNED_INT_24_8_WEBGL;
  15022. } else {
  15023. return null;
  15024. }
  15025. }
  15026. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15027. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15028. }
  15029. return { convert: convert };
  15030. }
  15031. class ArrayCamera extends PerspectiveCamera {
  15032. constructor( array = [] ) {
  15033. super();
  15034. this.isArrayCamera = true;
  15035. this.cameras = array;
  15036. }
  15037. }
  15038. class Group extends Object3D {
  15039. constructor() {
  15040. super();
  15041. this.isGroup = true;
  15042. this.type = 'Group';
  15043. }
  15044. }
  15045. const _moveEvent = { type: 'move' };
  15046. class WebXRController {
  15047. constructor() {
  15048. this._targetRay = null;
  15049. this._grip = null;
  15050. this._hand = null;
  15051. }
  15052. getHandSpace() {
  15053. if ( this._hand === null ) {
  15054. this._hand = new Group();
  15055. this._hand.matrixAutoUpdate = false;
  15056. this._hand.visible = false;
  15057. this._hand.joints = {};
  15058. this._hand.inputState = { pinching: false };
  15059. }
  15060. return this._hand;
  15061. }
  15062. getTargetRaySpace() {
  15063. if ( this._targetRay === null ) {
  15064. this._targetRay = new Group();
  15065. this._targetRay.matrixAutoUpdate = false;
  15066. this._targetRay.visible = false;
  15067. this._targetRay.hasLinearVelocity = false;
  15068. this._targetRay.linearVelocity = new Vector3();
  15069. this._targetRay.hasAngularVelocity = false;
  15070. this._targetRay.angularVelocity = new Vector3();
  15071. }
  15072. return this._targetRay;
  15073. }
  15074. getGripSpace() {
  15075. if ( this._grip === null ) {
  15076. this._grip = new Group();
  15077. this._grip.matrixAutoUpdate = false;
  15078. this._grip.visible = false;
  15079. this._grip.hasLinearVelocity = false;
  15080. this._grip.linearVelocity = new Vector3();
  15081. this._grip.hasAngularVelocity = false;
  15082. this._grip.angularVelocity = new Vector3();
  15083. }
  15084. return this._grip;
  15085. }
  15086. dispatchEvent( event ) {
  15087. if ( this._targetRay !== null ) {
  15088. this._targetRay.dispatchEvent( event );
  15089. }
  15090. if ( this._grip !== null ) {
  15091. this._grip.dispatchEvent( event );
  15092. }
  15093. if ( this._hand !== null ) {
  15094. this._hand.dispatchEvent( event );
  15095. }
  15096. return this;
  15097. }
  15098. connect( inputSource ) {
  15099. if ( inputSource && inputSource.hand ) {
  15100. const hand = this._hand;
  15101. if ( hand ) {
  15102. for ( const inputjoint of inputSource.hand.values() ) {
  15103. // Initialize hand with joints when connected
  15104. this._getHandJoint( hand, inputjoint );
  15105. }
  15106. }
  15107. }
  15108. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15109. return this;
  15110. }
  15111. disconnect( inputSource ) {
  15112. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15113. if ( this._targetRay !== null ) {
  15114. this._targetRay.visible = false;
  15115. }
  15116. if ( this._grip !== null ) {
  15117. this._grip.visible = false;
  15118. }
  15119. if ( this._hand !== null ) {
  15120. this._hand.visible = false;
  15121. }
  15122. return this;
  15123. }
  15124. update( inputSource, frame, referenceSpace ) {
  15125. let inputPose = null;
  15126. let gripPose = null;
  15127. let handPose = null;
  15128. const targetRay = this._targetRay;
  15129. const grip = this._grip;
  15130. const hand = this._hand;
  15131. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15132. if ( hand && inputSource.hand ) {
  15133. handPose = true;
  15134. for ( const inputjoint of inputSource.hand.values() ) {
  15135. // Update the joints groups with the XRJoint poses
  15136. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15137. // The transform of this joint will be updated with the joint pose on each frame
  15138. const joint = this._getHandJoint( hand, inputjoint );
  15139. if ( jointPose !== null ) {
  15140. joint.matrix.fromArray( jointPose.transform.matrix );
  15141. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15142. joint.jointRadius = jointPose.radius;
  15143. }
  15144. joint.visible = jointPose !== null;
  15145. }
  15146. // Custom events
  15147. // Check pinchz
  15148. const indexTip = hand.joints[ 'index-finger-tip' ];
  15149. const thumbTip = hand.joints[ 'thumb-tip' ];
  15150. const distance = indexTip.position.distanceTo( thumbTip.position );
  15151. const distanceToPinch = 0.02;
  15152. const threshold = 0.005;
  15153. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15154. hand.inputState.pinching = false;
  15155. this.dispatchEvent( {
  15156. type: 'pinchend',
  15157. handedness: inputSource.handedness,
  15158. target: this
  15159. } );
  15160. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15161. hand.inputState.pinching = true;
  15162. this.dispatchEvent( {
  15163. type: 'pinchstart',
  15164. handedness: inputSource.handedness,
  15165. target: this
  15166. } );
  15167. }
  15168. } else {
  15169. if ( grip !== null && inputSource.gripSpace ) {
  15170. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15171. if ( gripPose !== null ) {
  15172. grip.matrix.fromArray( gripPose.transform.matrix );
  15173. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15174. if ( gripPose.linearVelocity ) {
  15175. grip.hasLinearVelocity = true;
  15176. grip.linearVelocity.copy( gripPose.linearVelocity );
  15177. } else {
  15178. grip.hasLinearVelocity = false;
  15179. }
  15180. if ( gripPose.angularVelocity ) {
  15181. grip.hasAngularVelocity = true;
  15182. grip.angularVelocity.copy( gripPose.angularVelocity );
  15183. } else {
  15184. grip.hasAngularVelocity = false;
  15185. }
  15186. }
  15187. }
  15188. }
  15189. if ( targetRay !== null ) {
  15190. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15191. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15192. if ( inputPose === null && gripPose !== null ) {
  15193. inputPose = gripPose;
  15194. }
  15195. if ( inputPose !== null ) {
  15196. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15197. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15198. if ( inputPose.linearVelocity ) {
  15199. targetRay.hasLinearVelocity = true;
  15200. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15201. } else {
  15202. targetRay.hasLinearVelocity = false;
  15203. }
  15204. if ( inputPose.angularVelocity ) {
  15205. targetRay.hasAngularVelocity = true;
  15206. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15207. } else {
  15208. targetRay.hasAngularVelocity = false;
  15209. }
  15210. this.dispatchEvent( _moveEvent );
  15211. }
  15212. }
  15213. }
  15214. if ( targetRay !== null ) {
  15215. targetRay.visible = ( inputPose !== null );
  15216. }
  15217. if ( grip !== null ) {
  15218. grip.visible = ( gripPose !== null );
  15219. }
  15220. if ( hand !== null ) {
  15221. hand.visible = ( handPose !== null );
  15222. }
  15223. return this;
  15224. }
  15225. // private method
  15226. _getHandJoint( hand, inputjoint ) {
  15227. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15228. const joint = new Group();
  15229. joint.matrixAutoUpdate = false;
  15230. joint.visible = false;
  15231. hand.joints[ inputjoint.jointName ] = joint;
  15232. hand.add( joint );
  15233. }
  15234. return hand.joints[ inputjoint.jointName ];
  15235. }
  15236. }
  15237. class DepthTexture extends Texture {
  15238. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15239. format = format !== undefined ? format : DepthFormat;
  15240. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15241. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15242. }
  15243. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15244. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15245. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15246. this.isDepthTexture = true;
  15247. this.image = { width: width, height: height };
  15248. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15249. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15250. this.flipY = false;
  15251. this.generateMipmaps = false;
  15252. }
  15253. }
  15254. class WebXRManager extends EventDispatcher {
  15255. constructor( renderer, gl ) {
  15256. super();
  15257. const scope = this;
  15258. let session = null;
  15259. let framebufferScaleFactor = 1.0;
  15260. let referenceSpace = null;
  15261. let referenceSpaceType = 'local-floor';
  15262. // Set default foveation to maximum.
  15263. let foveation = 1.0;
  15264. let customReferenceSpace = null;
  15265. let pose = null;
  15266. let glBinding = null;
  15267. let glProjLayer = null;
  15268. let glBaseLayer = null;
  15269. let xrFrame = null;
  15270. const attributes = gl.getContextAttributes();
  15271. let initialRenderTarget = null;
  15272. let newRenderTarget = null;
  15273. const controllers = [];
  15274. const controllerInputSources = [];
  15275. const planes = new Set();
  15276. const planesLastChangedTimes = new Map();
  15277. //
  15278. const cameraL = new PerspectiveCamera();
  15279. cameraL.layers.enable( 1 );
  15280. cameraL.viewport = new Vector4();
  15281. const cameraR = new PerspectiveCamera();
  15282. cameraR.layers.enable( 2 );
  15283. cameraR.viewport = new Vector4();
  15284. const cameras = [ cameraL, cameraR ];
  15285. const cameraVR = new ArrayCamera();
  15286. cameraVR.layers.enable( 1 );
  15287. cameraVR.layers.enable( 2 );
  15288. let _currentDepthNear = null;
  15289. let _currentDepthFar = null;
  15290. //
  15291. this.cameraAutoUpdate = true;
  15292. this.enabled = false;
  15293. this.isPresenting = false;
  15294. this.getController = function ( index ) {
  15295. let controller = controllers[ index ];
  15296. if ( controller === undefined ) {
  15297. controller = new WebXRController();
  15298. controllers[ index ] = controller;
  15299. }
  15300. return controller.getTargetRaySpace();
  15301. };
  15302. this.getControllerGrip = function ( index ) {
  15303. let controller = controllers[ index ];
  15304. if ( controller === undefined ) {
  15305. controller = new WebXRController();
  15306. controllers[ index ] = controller;
  15307. }
  15308. return controller.getGripSpace();
  15309. };
  15310. this.getHand = function ( index ) {
  15311. let controller = controllers[ index ];
  15312. if ( controller === undefined ) {
  15313. controller = new WebXRController();
  15314. controllers[ index ] = controller;
  15315. }
  15316. return controller.getHandSpace();
  15317. };
  15318. //
  15319. function onSessionEvent( event ) {
  15320. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15321. if ( controllerIndex === - 1 ) {
  15322. return;
  15323. }
  15324. const controller = controllers[ controllerIndex ];
  15325. if ( controller !== undefined ) {
  15326. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15327. }
  15328. }
  15329. function onSessionEnd() {
  15330. session.removeEventListener( 'select', onSessionEvent );
  15331. session.removeEventListener( 'selectstart', onSessionEvent );
  15332. session.removeEventListener( 'selectend', onSessionEvent );
  15333. session.removeEventListener( 'squeeze', onSessionEvent );
  15334. session.removeEventListener( 'squeezestart', onSessionEvent );
  15335. session.removeEventListener( 'squeezeend', onSessionEvent );
  15336. session.removeEventListener( 'end', onSessionEnd );
  15337. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15338. for ( let i = 0; i < controllers.length; i ++ ) {
  15339. const inputSource = controllerInputSources[ i ];
  15340. if ( inputSource === null ) continue;
  15341. controllerInputSources[ i ] = null;
  15342. controllers[ i ].disconnect( inputSource );
  15343. }
  15344. _currentDepthNear = null;
  15345. _currentDepthFar = null;
  15346. // restore framebuffer/rendering state
  15347. renderer.setRenderTarget( initialRenderTarget );
  15348. glBaseLayer = null;
  15349. glProjLayer = null;
  15350. glBinding = null;
  15351. session = null;
  15352. newRenderTarget = null;
  15353. //
  15354. animation.stop();
  15355. scope.isPresenting = false;
  15356. scope.dispatchEvent( { type: 'sessionend' } );
  15357. }
  15358. this.setFramebufferScaleFactor = function ( value ) {
  15359. framebufferScaleFactor = value;
  15360. if ( scope.isPresenting === true ) {
  15361. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15362. }
  15363. };
  15364. this.setReferenceSpaceType = function ( value ) {
  15365. referenceSpaceType = value;
  15366. if ( scope.isPresenting === true ) {
  15367. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15368. }
  15369. };
  15370. this.getReferenceSpace = function () {
  15371. return customReferenceSpace || referenceSpace;
  15372. };
  15373. this.setReferenceSpace = function ( space ) {
  15374. customReferenceSpace = space;
  15375. };
  15376. this.getBaseLayer = function () {
  15377. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15378. };
  15379. this.getBinding = function () {
  15380. return glBinding;
  15381. };
  15382. this.getFrame = function () {
  15383. return xrFrame;
  15384. };
  15385. this.getSession = function () {
  15386. return session;
  15387. };
  15388. this.setSession = async function ( value ) {
  15389. session = value;
  15390. if ( session !== null ) {
  15391. initialRenderTarget = renderer.getRenderTarget();
  15392. session.addEventListener( 'select', onSessionEvent );
  15393. session.addEventListener( 'selectstart', onSessionEvent );
  15394. session.addEventListener( 'selectend', onSessionEvent );
  15395. session.addEventListener( 'squeeze', onSessionEvent );
  15396. session.addEventListener( 'squeezestart', onSessionEvent );
  15397. session.addEventListener( 'squeezeend', onSessionEvent );
  15398. session.addEventListener( 'end', onSessionEnd );
  15399. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15400. if ( attributes.xrCompatible !== true ) {
  15401. await gl.makeXRCompatible();
  15402. }
  15403. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15404. const layerInit = {
  15405. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15406. alpha: attributes.alpha,
  15407. depth: attributes.depth,
  15408. stencil: attributes.stencil,
  15409. framebufferScaleFactor: framebufferScaleFactor
  15410. };
  15411. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15412. session.updateRenderState( { baseLayer: glBaseLayer } );
  15413. newRenderTarget = new WebGLRenderTarget(
  15414. glBaseLayer.framebufferWidth,
  15415. glBaseLayer.framebufferHeight,
  15416. {
  15417. format: RGBAFormat,
  15418. type: UnsignedByteType,
  15419. encoding: renderer.outputEncoding,
  15420. stencilBuffer: attributes.stencil
  15421. }
  15422. );
  15423. } else {
  15424. let depthFormat = null;
  15425. let depthType = null;
  15426. let glDepthFormat = null;
  15427. if ( attributes.depth ) {
  15428. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15429. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15430. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15431. }
  15432. const projectionlayerInit = {
  15433. colorFormat: gl.RGBA8,
  15434. depthFormat: glDepthFormat,
  15435. scaleFactor: framebufferScaleFactor
  15436. };
  15437. glBinding = new XRWebGLBinding( session, gl );
  15438. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15439. session.updateRenderState( { layers: [ glProjLayer ] } );
  15440. newRenderTarget = new WebGLRenderTarget(
  15441. glProjLayer.textureWidth,
  15442. glProjLayer.textureHeight,
  15443. {
  15444. format: RGBAFormat,
  15445. type: UnsignedByteType,
  15446. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15447. stencilBuffer: attributes.stencil,
  15448. encoding: renderer.outputEncoding,
  15449. samples: attributes.antialias ? 4 : 0
  15450. } );
  15451. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15452. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15453. }
  15454. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15455. this.setFoveation( foveation );
  15456. customReferenceSpace = null;
  15457. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15458. animation.setContext( session );
  15459. animation.start();
  15460. scope.isPresenting = true;
  15461. scope.dispatchEvent( { type: 'sessionstart' } );
  15462. }
  15463. };
  15464. function onInputSourcesChange( event ) {
  15465. // Notify disconnected
  15466. for ( let i = 0; i < event.removed.length; i ++ ) {
  15467. const inputSource = event.removed[ i ];
  15468. const index = controllerInputSources.indexOf( inputSource );
  15469. if ( index >= 0 ) {
  15470. controllerInputSources[ index ] = null;
  15471. controllers[ index ].disconnect( inputSource );
  15472. }
  15473. }
  15474. // Notify connected
  15475. for ( let i = 0; i < event.added.length; i ++ ) {
  15476. const inputSource = event.added[ i ];
  15477. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15478. if ( controllerIndex === - 1 ) {
  15479. // Assign input source a controller that currently has no input source
  15480. for ( let i = 0; i < controllers.length; i ++ ) {
  15481. if ( i >= controllerInputSources.length ) {
  15482. controllerInputSources.push( inputSource );
  15483. controllerIndex = i;
  15484. break;
  15485. } else if ( controllerInputSources[ i ] === null ) {
  15486. controllerInputSources[ i ] = inputSource;
  15487. controllerIndex = i;
  15488. break;
  15489. }
  15490. }
  15491. // If all controllers do currently receive input we ignore new ones
  15492. if ( controllerIndex === - 1 ) break;
  15493. }
  15494. const controller = controllers[ controllerIndex ];
  15495. if ( controller ) {
  15496. controller.connect( inputSource );
  15497. }
  15498. }
  15499. }
  15500. //
  15501. const cameraLPos = new Vector3();
  15502. const cameraRPos = new Vector3();
  15503. /**
  15504. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15505. * the cameras' projection and world matrices have already been set.
  15506. * And that near and far planes are identical for both cameras.
  15507. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15508. */
  15509. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15510. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15511. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15512. const ipd = cameraLPos.distanceTo( cameraRPos );
  15513. const projL = cameraL.projectionMatrix.elements;
  15514. const projR = cameraR.projectionMatrix.elements;
  15515. // VR systems will have identical far and near planes, and
  15516. // most likely identical top and bottom frustum extents.
  15517. // Use the left camera for these values.
  15518. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15519. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15520. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15521. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15522. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15523. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15524. const left = near * leftFov;
  15525. const right = near * rightFov;
  15526. // Calculate the new camera's position offset from the
  15527. // left camera. xOffset should be roughly half `ipd`.
  15528. const zOffset = ipd / ( - leftFov + rightFov );
  15529. const xOffset = zOffset * - leftFov;
  15530. // TODO: Better way to apply this offset?
  15531. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15532. camera.translateX( xOffset );
  15533. camera.translateZ( zOffset );
  15534. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15535. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15536. // Find the union of the frustum values of the cameras and scale
  15537. // the values so that the near plane's position does not change in world space,
  15538. // although must now be relative to the new union camera.
  15539. const near2 = near + zOffset;
  15540. const far2 = far + zOffset;
  15541. const left2 = left - xOffset;
  15542. const right2 = right + ( ipd - xOffset );
  15543. const top2 = topFov * far / far2 * near2;
  15544. const bottom2 = bottomFov * far / far2 * near2;
  15545. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15546. }
  15547. function updateCamera( camera, parent ) {
  15548. if ( parent === null ) {
  15549. camera.matrixWorld.copy( camera.matrix );
  15550. } else {
  15551. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15552. }
  15553. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15554. }
  15555. this.updateCamera = function ( camera ) {
  15556. if ( session === null ) return;
  15557. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15558. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15559. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15560. // Note that the new renderState won't apply until the next frame. See #18320
  15561. session.updateRenderState( {
  15562. depthNear: cameraVR.near,
  15563. depthFar: cameraVR.far
  15564. } );
  15565. _currentDepthNear = cameraVR.near;
  15566. _currentDepthFar = cameraVR.far;
  15567. }
  15568. const parent = camera.parent;
  15569. const cameras = cameraVR.cameras;
  15570. updateCamera( cameraVR, parent );
  15571. for ( let i = 0; i < cameras.length; i ++ ) {
  15572. updateCamera( cameras[ i ], parent );
  15573. }
  15574. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15575. // update user camera and its children
  15576. camera.matrix.copy( cameraVR.matrix );
  15577. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15578. const children = camera.children;
  15579. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15580. children[ i ].updateMatrixWorld( true );
  15581. }
  15582. // update projection matrix for proper view frustum culling
  15583. if ( cameras.length === 2 ) {
  15584. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15585. } else {
  15586. // assume single camera setup (AR)
  15587. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15588. }
  15589. };
  15590. this.getCamera = function () {
  15591. return cameraVR;
  15592. };
  15593. this.getFoveation = function () {
  15594. if ( glProjLayer === null && glBaseLayer === null ) {
  15595. return undefined;
  15596. }
  15597. return foveation;
  15598. };
  15599. this.setFoveation = function ( value ) {
  15600. // 0 = no foveation = full resolution
  15601. // 1 = maximum foveation = the edges render at lower resolution
  15602. foveation = value;
  15603. if ( glProjLayer !== null ) {
  15604. glProjLayer.fixedFoveation = value;
  15605. }
  15606. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15607. glBaseLayer.fixedFoveation = value;
  15608. }
  15609. };
  15610. this.getPlanes = function () {
  15611. return planes;
  15612. };
  15613. // Animation Loop
  15614. let onAnimationFrameCallback = null;
  15615. function onAnimationFrame( time, frame ) {
  15616. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15617. xrFrame = frame;
  15618. if ( pose !== null ) {
  15619. const views = pose.views;
  15620. if ( glBaseLayer !== null ) {
  15621. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15622. renderer.setRenderTarget( newRenderTarget );
  15623. }
  15624. let cameraVRNeedsUpdate = false;
  15625. // check if it's necessary to rebuild cameraVR's camera list
  15626. if ( views.length !== cameraVR.cameras.length ) {
  15627. cameraVR.cameras.length = 0;
  15628. cameraVRNeedsUpdate = true;
  15629. }
  15630. for ( let i = 0; i < views.length; i ++ ) {
  15631. const view = views[ i ];
  15632. let viewport = null;
  15633. if ( glBaseLayer !== null ) {
  15634. viewport = glBaseLayer.getViewport( view );
  15635. } else {
  15636. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15637. viewport = glSubImage.viewport;
  15638. // For side-by-side projection, we only produce a single texture for both eyes.
  15639. if ( i === 0 ) {
  15640. renderer.setRenderTargetTextures(
  15641. newRenderTarget,
  15642. glSubImage.colorTexture,
  15643. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15644. renderer.setRenderTarget( newRenderTarget );
  15645. }
  15646. }
  15647. let camera = cameras[ i ];
  15648. if ( camera === undefined ) {
  15649. camera = new PerspectiveCamera();
  15650. camera.layers.enable( i );
  15651. camera.viewport = new Vector4();
  15652. cameras[ i ] = camera;
  15653. }
  15654. camera.matrix.fromArray( view.transform.matrix );
  15655. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15656. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15657. if ( i === 0 ) {
  15658. cameraVR.matrix.copy( camera.matrix );
  15659. }
  15660. if ( cameraVRNeedsUpdate === true ) {
  15661. cameraVR.cameras.push( camera );
  15662. }
  15663. }
  15664. }
  15665. //
  15666. for ( let i = 0; i < controllers.length; i ++ ) {
  15667. const inputSource = controllerInputSources[ i ];
  15668. const controller = controllers[ i ];
  15669. if ( inputSource !== null && controller !== undefined ) {
  15670. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15671. }
  15672. }
  15673. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15674. if ( frame.detectedPlanes ) {
  15675. scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } );
  15676. let planesToRemove = null;
  15677. for ( const plane of planes ) {
  15678. if ( ! frame.detectedPlanes.has( plane ) ) {
  15679. if ( planesToRemove === null ) {
  15680. planesToRemove = [];
  15681. }
  15682. planesToRemove.push( plane );
  15683. }
  15684. }
  15685. if ( planesToRemove !== null ) {
  15686. for ( const plane of planesToRemove ) {
  15687. planes.delete( plane );
  15688. planesLastChangedTimes.delete( plane );
  15689. scope.dispatchEvent( { type: 'planeremoved', data: plane } );
  15690. }
  15691. }
  15692. for ( const plane of frame.detectedPlanes ) {
  15693. if ( ! planes.has( plane ) ) {
  15694. planes.add( plane );
  15695. planesLastChangedTimes.set( plane, frame.lastChangedTime );
  15696. scope.dispatchEvent( { type: 'planeadded', data: plane } );
  15697. } else {
  15698. const lastKnownTime = planesLastChangedTimes.get( plane );
  15699. if ( plane.lastChangedTime > lastKnownTime ) {
  15700. planesLastChangedTimes.set( plane, plane.lastChangedTime );
  15701. scope.dispatchEvent( { type: 'planechanged', data: plane } );
  15702. }
  15703. }
  15704. }
  15705. }
  15706. xrFrame = null;
  15707. }
  15708. const animation = new WebGLAnimation();
  15709. animation.setAnimationLoop( onAnimationFrame );
  15710. this.setAnimationLoop = function ( callback ) {
  15711. onAnimationFrameCallback = callback;
  15712. };
  15713. this.dispose = function () {};
  15714. }
  15715. }
  15716. function WebGLMaterials( renderer, properties ) {
  15717. function refreshFogUniforms( uniforms, fog ) {
  15718. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  15719. if ( fog.isFog ) {
  15720. uniforms.fogNear.value = fog.near;
  15721. uniforms.fogFar.value = fog.far;
  15722. } else if ( fog.isFogExp2 ) {
  15723. uniforms.fogDensity.value = fog.density;
  15724. }
  15725. }
  15726. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15727. if ( material.isMeshBasicMaterial ) {
  15728. refreshUniformsCommon( uniforms, material );
  15729. } else if ( material.isMeshLambertMaterial ) {
  15730. refreshUniformsCommon( uniforms, material );
  15731. } else if ( material.isMeshToonMaterial ) {
  15732. refreshUniformsCommon( uniforms, material );
  15733. refreshUniformsToon( uniforms, material );
  15734. } else if ( material.isMeshPhongMaterial ) {
  15735. refreshUniformsCommon( uniforms, material );
  15736. refreshUniformsPhong( uniforms, material );
  15737. } else if ( material.isMeshStandardMaterial ) {
  15738. refreshUniformsCommon( uniforms, material );
  15739. refreshUniformsStandard( uniforms, material );
  15740. if ( material.isMeshPhysicalMaterial ) {
  15741. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15742. }
  15743. } else if ( material.isMeshMatcapMaterial ) {
  15744. refreshUniformsCommon( uniforms, material );
  15745. refreshUniformsMatcap( uniforms, material );
  15746. } else if ( material.isMeshDepthMaterial ) {
  15747. refreshUniformsCommon( uniforms, material );
  15748. } else if ( material.isMeshDistanceMaterial ) {
  15749. refreshUniformsCommon( uniforms, material );
  15750. refreshUniformsDistance( uniforms, material );
  15751. } else if ( material.isMeshNormalMaterial ) {
  15752. refreshUniformsCommon( uniforms, material );
  15753. } else if ( material.isLineBasicMaterial ) {
  15754. refreshUniformsLine( uniforms, material );
  15755. if ( material.isLineDashedMaterial ) {
  15756. refreshUniformsDash( uniforms, material );
  15757. }
  15758. } else if ( material.isPointsMaterial ) {
  15759. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15760. } else if ( material.isSpriteMaterial ) {
  15761. refreshUniformsSprites( uniforms, material );
  15762. } else if ( material.isShadowMaterial ) {
  15763. uniforms.color.value.copy( material.color );
  15764. uniforms.opacity.value = material.opacity;
  15765. } else if ( material.isShaderMaterial ) {
  15766. material.uniformsNeedUpdate = false; // #15581
  15767. }
  15768. }
  15769. function refreshUniformsCommon( uniforms, material ) {
  15770. uniforms.opacity.value = material.opacity;
  15771. if ( material.color ) {
  15772. uniforms.diffuse.value.copy( material.color );
  15773. }
  15774. if ( material.emissive ) {
  15775. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15776. }
  15777. if ( material.map ) {
  15778. uniforms.map.value = material.map;
  15779. }
  15780. if ( material.alphaMap ) {
  15781. uniforms.alphaMap.value = material.alphaMap;
  15782. }
  15783. if ( material.bumpMap ) {
  15784. uniforms.bumpMap.value = material.bumpMap;
  15785. uniforms.bumpScale.value = material.bumpScale;
  15786. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15787. }
  15788. if ( material.displacementMap ) {
  15789. uniforms.displacementMap.value = material.displacementMap;
  15790. uniforms.displacementScale.value = material.displacementScale;
  15791. uniforms.displacementBias.value = material.displacementBias;
  15792. }
  15793. if ( material.emissiveMap ) {
  15794. uniforms.emissiveMap.value = material.emissiveMap;
  15795. }
  15796. if ( material.normalMap ) {
  15797. uniforms.normalMap.value = material.normalMap;
  15798. uniforms.normalScale.value.copy( material.normalScale );
  15799. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15800. }
  15801. if ( material.specularMap ) {
  15802. uniforms.specularMap.value = material.specularMap;
  15803. }
  15804. if ( material.alphaTest > 0 ) {
  15805. uniforms.alphaTest.value = material.alphaTest;
  15806. }
  15807. const envMap = properties.get( material ).envMap;
  15808. if ( envMap ) {
  15809. uniforms.envMap.value = envMap;
  15810. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15811. uniforms.reflectivity.value = material.reflectivity;
  15812. uniforms.ior.value = material.ior;
  15813. uniforms.refractionRatio.value = material.refractionRatio;
  15814. }
  15815. if ( material.lightMap ) {
  15816. uniforms.lightMap.value = material.lightMap;
  15817. // artist-friendly light intensity scaling factor
  15818. const scaleFactor = ( renderer.useLegacyLights === true ) ? Math.PI : 1;
  15819. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15820. }
  15821. if ( material.aoMap ) {
  15822. uniforms.aoMap.value = material.aoMap;
  15823. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15824. }
  15825. // uv repeat and offset setting priorities
  15826. // 1. color map
  15827. // 2. specular map
  15828. // 3. displacementMap map
  15829. // 4. normal map
  15830. // 5. bump map
  15831. // 6. roughnessMap map
  15832. // 7. metalnessMap map
  15833. // 8. alphaMap map
  15834. // 9. emissiveMap map
  15835. // 10. clearcoat map
  15836. // 11. clearcoat normal map
  15837. // 12. clearcoat roughnessMap map
  15838. // 13. iridescence map
  15839. // 14. iridescence thickness map
  15840. // 15. specular intensity map
  15841. // 16. specular tint map
  15842. // 17. transmission map
  15843. // 18. thickness map
  15844. let uvScaleMap;
  15845. if ( material.map ) {
  15846. uvScaleMap = material.map;
  15847. } else if ( material.specularMap ) {
  15848. uvScaleMap = material.specularMap;
  15849. } else if ( material.displacementMap ) {
  15850. uvScaleMap = material.displacementMap;
  15851. } else if ( material.normalMap ) {
  15852. uvScaleMap = material.normalMap;
  15853. } else if ( material.bumpMap ) {
  15854. uvScaleMap = material.bumpMap;
  15855. } else if ( material.roughnessMap ) {
  15856. uvScaleMap = material.roughnessMap;
  15857. } else if ( material.metalnessMap ) {
  15858. uvScaleMap = material.metalnessMap;
  15859. } else if ( material.alphaMap ) {
  15860. uvScaleMap = material.alphaMap;
  15861. } else if ( material.emissiveMap ) {
  15862. uvScaleMap = material.emissiveMap;
  15863. } else if ( material.clearcoatMap ) {
  15864. uvScaleMap = material.clearcoatMap;
  15865. } else if ( material.clearcoatNormalMap ) {
  15866. uvScaleMap = material.clearcoatNormalMap;
  15867. } else if ( material.clearcoatRoughnessMap ) {
  15868. uvScaleMap = material.clearcoatRoughnessMap;
  15869. } else if ( material.iridescenceMap ) {
  15870. uvScaleMap = material.iridescenceMap;
  15871. } else if ( material.iridescenceThicknessMap ) {
  15872. uvScaleMap = material.iridescenceThicknessMap;
  15873. } else if ( material.specularIntensityMap ) {
  15874. uvScaleMap = material.specularIntensityMap;
  15875. } else if ( material.specularColorMap ) {
  15876. uvScaleMap = material.specularColorMap;
  15877. } else if ( material.transmissionMap ) {
  15878. uvScaleMap = material.transmissionMap;
  15879. } else if ( material.thicknessMap ) {
  15880. uvScaleMap = material.thicknessMap;
  15881. } else if ( material.sheenColorMap ) {
  15882. uvScaleMap = material.sheenColorMap;
  15883. } else if ( material.sheenRoughnessMap ) {
  15884. uvScaleMap = material.sheenRoughnessMap;
  15885. }
  15886. if ( uvScaleMap !== undefined ) {
  15887. // backwards compatibility
  15888. if ( uvScaleMap.isWebGLRenderTarget ) {
  15889. uvScaleMap = uvScaleMap.texture;
  15890. }
  15891. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15892. uvScaleMap.updateMatrix();
  15893. }
  15894. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15895. }
  15896. // uv repeat and offset setting priorities for uv2
  15897. // 1. ao map
  15898. // 2. light map
  15899. let uv2ScaleMap;
  15900. if ( material.aoMap ) {
  15901. uv2ScaleMap = material.aoMap;
  15902. } else if ( material.lightMap ) {
  15903. uv2ScaleMap = material.lightMap;
  15904. }
  15905. if ( uv2ScaleMap !== undefined ) {
  15906. // backwards compatibility
  15907. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15908. uv2ScaleMap = uv2ScaleMap.texture;
  15909. }
  15910. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15911. uv2ScaleMap.updateMatrix();
  15912. }
  15913. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15914. }
  15915. }
  15916. function refreshUniformsLine( uniforms, material ) {
  15917. uniforms.diffuse.value.copy( material.color );
  15918. uniforms.opacity.value = material.opacity;
  15919. }
  15920. function refreshUniformsDash( uniforms, material ) {
  15921. uniforms.dashSize.value = material.dashSize;
  15922. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15923. uniforms.scale.value = material.scale;
  15924. }
  15925. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15926. uniforms.diffuse.value.copy( material.color );
  15927. uniforms.opacity.value = material.opacity;
  15928. uniforms.size.value = material.size * pixelRatio;
  15929. uniforms.scale.value = height * 0.5;
  15930. if ( material.map ) {
  15931. uniforms.map.value = material.map;
  15932. }
  15933. if ( material.alphaMap ) {
  15934. uniforms.alphaMap.value = material.alphaMap;
  15935. }
  15936. if ( material.alphaTest > 0 ) {
  15937. uniforms.alphaTest.value = material.alphaTest;
  15938. }
  15939. // uv repeat and offset setting priorities
  15940. // 1. color map
  15941. // 2. alpha map
  15942. let uvScaleMap;
  15943. if ( material.map ) {
  15944. uvScaleMap = material.map;
  15945. } else if ( material.alphaMap ) {
  15946. uvScaleMap = material.alphaMap;
  15947. }
  15948. if ( uvScaleMap !== undefined ) {
  15949. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15950. uvScaleMap.updateMatrix();
  15951. }
  15952. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15953. }
  15954. }
  15955. function refreshUniformsSprites( uniforms, material ) {
  15956. uniforms.diffuse.value.copy( material.color );
  15957. uniforms.opacity.value = material.opacity;
  15958. uniforms.rotation.value = material.rotation;
  15959. if ( material.map ) {
  15960. uniforms.map.value = material.map;
  15961. }
  15962. if ( material.alphaMap ) {
  15963. uniforms.alphaMap.value = material.alphaMap;
  15964. }
  15965. if ( material.alphaTest > 0 ) {
  15966. uniforms.alphaTest.value = material.alphaTest;
  15967. }
  15968. // uv repeat and offset setting priorities
  15969. // 1. color map
  15970. // 2. alpha map
  15971. let uvScaleMap;
  15972. if ( material.map ) {
  15973. uvScaleMap = material.map;
  15974. } else if ( material.alphaMap ) {
  15975. uvScaleMap = material.alphaMap;
  15976. }
  15977. if ( uvScaleMap !== undefined ) {
  15978. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15979. uvScaleMap.updateMatrix();
  15980. }
  15981. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15982. }
  15983. }
  15984. function refreshUniformsPhong( uniforms, material ) {
  15985. uniforms.specular.value.copy( material.specular );
  15986. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15987. }
  15988. function refreshUniformsToon( uniforms, material ) {
  15989. if ( material.gradientMap ) {
  15990. uniforms.gradientMap.value = material.gradientMap;
  15991. }
  15992. }
  15993. function refreshUniformsStandard( uniforms, material ) {
  15994. uniforms.roughness.value = material.roughness;
  15995. uniforms.metalness.value = material.metalness;
  15996. if ( material.roughnessMap ) {
  15997. uniforms.roughnessMap.value = material.roughnessMap;
  15998. }
  15999. if ( material.metalnessMap ) {
  16000. uniforms.metalnessMap.value = material.metalnessMap;
  16001. }
  16002. const envMap = properties.get( material ).envMap;
  16003. if ( envMap ) {
  16004. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16005. uniforms.envMapIntensity.value = material.envMapIntensity;
  16006. }
  16007. }
  16008. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16009. uniforms.ior.value = material.ior; // also part of uniforms common
  16010. if ( material.sheen > 0 ) {
  16011. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16012. uniforms.sheenRoughness.value = material.sheenRoughness;
  16013. if ( material.sheenColorMap ) {
  16014. uniforms.sheenColorMap.value = material.sheenColorMap;
  16015. }
  16016. if ( material.sheenRoughnessMap ) {
  16017. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16018. }
  16019. }
  16020. if ( material.clearcoat > 0 ) {
  16021. uniforms.clearcoat.value = material.clearcoat;
  16022. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16023. if ( material.clearcoatMap ) {
  16024. uniforms.clearcoatMap.value = material.clearcoatMap;
  16025. }
  16026. if ( material.clearcoatRoughnessMap ) {
  16027. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16028. }
  16029. if ( material.clearcoatNormalMap ) {
  16030. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16031. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16032. if ( material.side === BackSide ) {
  16033. uniforms.clearcoatNormalScale.value.negate();
  16034. }
  16035. }
  16036. }
  16037. if ( material.iridescence > 0 ) {
  16038. uniforms.iridescence.value = material.iridescence;
  16039. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16040. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16041. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16042. if ( material.iridescenceMap ) {
  16043. uniforms.iridescenceMap.value = material.iridescenceMap;
  16044. }
  16045. if ( material.iridescenceThicknessMap ) {
  16046. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16047. }
  16048. }
  16049. if ( material.transmission > 0 ) {
  16050. uniforms.transmission.value = material.transmission;
  16051. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16052. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16053. if ( material.transmissionMap ) {
  16054. uniforms.transmissionMap.value = material.transmissionMap;
  16055. }
  16056. uniforms.thickness.value = material.thickness;
  16057. if ( material.thicknessMap ) {
  16058. uniforms.thicknessMap.value = material.thicknessMap;
  16059. }
  16060. uniforms.attenuationDistance.value = material.attenuationDistance;
  16061. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16062. }
  16063. uniforms.specularIntensity.value = material.specularIntensity;
  16064. uniforms.specularColor.value.copy( material.specularColor );
  16065. if ( material.specularIntensityMap ) {
  16066. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16067. }
  16068. if ( material.specularColorMap ) {
  16069. uniforms.specularColorMap.value = material.specularColorMap;
  16070. }
  16071. }
  16072. function refreshUniformsMatcap( uniforms, material ) {
  16073. if ( material.matcap ) {
  16074. uniforms.matcap.value = material.matcap;
  16075. }
  16076. }
  16077. function refreshUniformsDistance( uniforms, material ) {
  16078. uniforms.referencePosition.value.copy( material.referencePosition );
  16079. uniforms.nearDistance.value = material.nearDistance;
  16080. uniforms.farDistance.value = material.farDistance;
  16081. }
  16082. return {
  16083. refreshFogUniforms: refreshFogUniforms,
  16084. refreshMaterialUniforms: refreshMaterialUniforms
  16085. };
  16086. }
  16087. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16088. let buffers = {};
  16089. let updateList = {};
  16090. let allocatedBindingPoints = [];
  16091. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program
  16092. function bind( uniformsGroup, program ) {
  16093. const webglProgram = program.program;
  16094. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16095. }
  16096. function update( uniformsGroup, program ) {
  16097. let buffer = buffers[ uniformsGroup.id ];
  16098. if ( buffer === undefined ) {
  16099. prepareUniformsGroup( uniformsGroup );
  16100. buffer = createBuffer( uniformsGroup );
  16101. buffers[ uniformsGroup.id ] = buffer;
  16102. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16103. }
  16104. // ensure to update the binding points/block indices mapping for this program
  16105. const webglProgram = program.program;
  16106. state.updateUBOMapping( uniformsGroup, webglProgram );
  16107. // update UBO once per frame
  16108. const frame = info.render.frame;
  16109. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16110. updateBufferData( uniformsGroup );
  16111. updateList[ uniformsGroup.id ] = frame;
  16112. }
  16113. }
  16114. function createBuffer( uniformsGroup ) {
  16115. // the setup of an UBO is independent of a particular shader program but global
  16116. const bindingPointIndex = allocateBindingPointIndex();
  16117. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16118. const buffer = gl.createBuffer();
  16119. const size = uniformsGroup.__size;
  16120. const usage = uniformsGroup.usage;
  16121. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16122. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  16123. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16124. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  16125. return buffer;
  16126. }
  16127. function allocateBindingPointIndex() {
  16128. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16129. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16130. allocatedBindingPoints.push( i );
  16131. return i;
  16132. }
  16133. }
  16134. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16135. return 0;
  16136. }
  16137. function updateBufferData( uniformsGroup ) {
  16138. const buffer = buffers[ uniformsGroup.id ];
  16139. const uniforms = uniformsGroup.uniforms;
  16140. const cache = uniformsGroup.__cache;
  16141. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16142. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16143. const uniform = uniforms[ i ];
  16144. // partly update the buffer if necessary
  16145. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  16146. const offset = uniform.__offset;
  16147. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16148. let arrayOffset = 0;
  16149. for ( let i = 0; i < values.length; i ++ ) {
  16150. const value = values[ i ];
  16151. const info = getUniformSize( value );
  16152. if ( typeof value === 'number' ) {
  16153. uniform.__data[ 0 ] = value;
  16154. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  16155. } else if ( value.isMatrix3 ) {
  16156. // manually converting 3x3 to 3x4
  16157. uniform.__data[ 0 ] = value.elements[ 0 ];
  16158. uniform.__data[ 1 ] = value.elements[ 1 ];
  16159. uniform.__data[ 2 ] = value.elements[ 2 ];
  16160. uniform.__data[ 3 ] = value.elements[ 0 ];
  16161. uniform.__data[ 4 ] = value.elements[ 3 ];
  16162. uniform.__data[ 5 ] = value.elements[ 4 ];
  16163. uniform.__data[ 6 ] = value.elements[ 5 ];
  16164. uniform.__data[ 7 ] = value.elements[ 0 ];
  16165. uniform.__data[ 8 ] = value.elements[ 6 ];
  16166. uniform.__data[ 9 ] = value.elements[ 7 ];
  16167. uniform.__data[ 10 ] = value.elements[ 8 ];
  16168. uniform.__data[ 11 ] = value.elements[ 0 ];
  16169. } else {
  16170. value.toArray( uniform.__data, arrayOffset );
  16171. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16172. }
  16173. }
  16174. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  16175. }
  16176. }
  16177. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16178. }
  16179. function hasUniformChanged( uniform, index, cache ) {
  16180. const value = uniform.value;
  16181. if ( cache[ index ] === undefined ) {
  16182. // cache entry does not exist so far
  16183. if ( typeof value === 'number' ) {
  16184. cache[ index ] = value;
  16185. } else {
  16186. const values = Array.isArray( value ) ? value : [ value ];
  16187. const tempValues = [];
  16188. for ( let i = 0; i < values.length; i ++ ) {
  16189. tempValues.push( values[ i ].clone() );
  16190. }
  16191. cache[ index ] = tempValues;
  16192. }
  16193. return true;
  16194. } else {
  16195. // compare current value with cached entry
  16196. if ( typeof value === 'number' ) {
  16197. if ( cache[ index ] !== value ) {
  16198. cache[ index ] = value;
  16199. return true;
  16200. }
  16201. } else {
  16202. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  16203. const values = Array.isArray( value ) ? value : [ value ];
  16204. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  16205. const cachedObject = cachedObjects[ i ];
  16206. if ( cachedObject.equals( values[ i ] ) === false ) {
  16207. cachedObject.copy( values[ i ] );
  16208. return true;
  16209. }
  16210. }
  16211. }
  16212. }
  16213. return false;
  16214. }
  16215. function prepareUniformsGroup( uniformsGroup ) {
  16216. // determine total buffer size according to the STD140 layout
  16217. // Hint: STD140 is the only supported layout in WebGL 2
  16218. const uniforms = uniformsGroup.uniforms;
  16219. let offset = 0; // global buffer offset in bytes
  16220. const chunkSize = 16; // size of a chunk in bytes
  16221. let chunkOffset = 0; // offset within a single chunk in bytes
  16222. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16223. const uniform = uniforms[ i ];
  16224. const infos = {
  16225. boundary: 0, // bytes
  16226. storage: 0 // bytes
  16227. };
  16228. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16229. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  16230. const value = values[ j ];
  16231. const info = getUniformSize( value );
  16232. infos.boundary += info.boundary;
  16233. infos.storage += info.storage;
  16234. }
  16235. // the following two properties will be used for partial buffer updates
  16236. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16237. uniform.__offset = offset;
  16238. //
  16239. if ( i > 0 ) {
  16240. chunkOffset = offset % chunkSize;
  16241. const remainingSizeInChunk = chunkSize - chunkOffset;
  16242. // check for chunk overflow
  16243. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16244. // add padding and adjust offset
  16245. offset += ( chunkSize - chunkOffset );
  16246. uniform.__offset = offset;
  16247. }
  16248. }
  16249. offset += infos.storage;
  16250. }
  16251. // ensure correct final padding
  16252. chunkOffset = offset % chunkSize;
  16253. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16254. //
  16255. uniformsGroup.__size = offset;
  16256. uniformsGroup.__cache = {};
  16257. return this;
  16258. }
  16259. function getUniformSize( value ) {
  16260. const info = {
  16261. boundary: 0, // bytes
  16262. storage: 0 // bytes
  16263. };
  16264. // determine sizes according to STD140
  16265. if ( typeof value === 'number' ) {
  16266. // float/int
  16267. info.boundary = 4;
  16268. info.storage = 4;
  16269. } else if ( value.isVector2 ) {
  16270. // vec2
  16271. info.boundary = 8;
  16272. info.storage = 8;
  16273. } else if ( value.isVector3 || value.isColor ) {
  16274. // vec3
  16275. info.boundary = 16;
  16276. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16277. } else if ( value.isVector4 ) {
  16278. // vec4
  16279. info.boundary = 16;
  16280. info.storage = 16;
  16281. } else if ( value.isMatrix3 ) {
  16282. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16283. info.boundary = 48;
  16284. info.storage = 48;
  16285. } else if ( value.isMatrix4 ) {
  16286. // mat4
  16287. info.boundary = 64;
  16288. info.storage = 64;
  16289. } else if ( value.isTexture ) {
  16290. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16291. } else {
  16292. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16293. }
  16294. return info;
  16295. }
  16296. function onUniformsGroupsDispose( event ) {
  16297. const uniformsGroup = event.target;
  16298. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16299. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16300. allocatedBindingPoints.splice( index, 1 );
  16301. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16302. delete buffers[ uniformsGroup.id ];
  16303. delete updateList[ uniformsGroup.id ];
  16304. }
  16305. function dispose() {
  16306. for ( const id in buffers ) {
  16307. gl.deleteBuffer( buffers[ id ] );
  16308. }
  16309. allocatedBindingPoints = [];
  16310. buffers = {};
  16311. updateList = {};
  16312. }
  16313. return {
  16314. bind: bind,
  16315. update: update,
  16316. dispose: dispose
  16317. };
  16318. }
  16319. function createCanvasElement() {
  16320. const canvas = createElementNS( 'canvas' );
  16321. canvas.style.display = 'block';
  16322. return canvas;
  16323. }
  16324. function WebGLRenderer( parameters = {} ) {
  16325. this.isWebGLRenderer = true;
  16326. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  16327. _context = parameters.context !== undefined ? parameters.context : null,
  16328. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16329. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16330. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16331. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16332. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16333. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  16334. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  16335. let _alpha;
  16336. if ( _context !== null ) {
  16337. _alpha = _context.getContextAttributes().alpha;
  16338. } else {
  16339. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  16340. }
  16341. let currentRenderList = null;
  16342. let currentRenderState = null;
  16343. // render() can be called from within a callback triggered by another render.
  16344. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16345. const renderListStack = [];
  16346. const renderStateStack = [];
  16347. // public properties
  16348. this.domElement = _canvas;
  16349. // Debug configuration container
  16350. this.debug = {
  16351. /**
  16352. * Enables error checking and reporting when shader programs are being compiled
  16353. * @type {boolean}
  16354. */
  16355. checkShaderErrors: true
  16356. };
  16357. // clearing
  16358. this.autoClear = true;
  16359. this.autoClearColor = true;
  16360. this.autoClearDepth = true;
  16361. this.autoClearStencil = true;
  16362. // scene graph
  16363. this.sortObjects = true;
  16364. // user-defined clipping
  16365. this.clippingPlanes = [];
  16366. this.localClippingEnabled = false;
  16367. // physically based shading
  16368. this.outputEncoding = LinearEncoding;
  16369. // physical lights
  16370. this.useLegacyLights = true;
  16371. // tone mapping
  16372. this.toneMapping = NoToneMapping;
  16373. this.toneMappingExposure = 1.0;
  16374. // internal properties
  16375. const _this = this;
  16376. let _isContextLost = false;
  16377. // internal state cache
  16378. let _currentActiveCubeFace = 0;
  16379. let _currentActiveMipmapLevel = 0;
  16380. let _currentRenderTarget = null;
  16381. let _currentMaterialId = - 1;
  16382. let _currentCamera = null;
  16383. const _currentViewport = new Vector4();
  16384. const _currentScissor = new Vector4();
  16385. let _currentScissorTest = null;
  16386. //
  16387. let _width = _canvas.width;
  16388. let _height = _canvas.height;
  16389. let _pixelRatio = 1;
  16390. let _opaqueSort = null;
  16391. let _transparentSort = null;
  16392. const _viewport = new Vector4( 0, 0, _width, _height );
  16393. const _scissor = new Vector4( 0, 0, _width, _height );
  16394. let _scissorTest = false;
  16395. // frustum
  16396. const _frustum = new Frustum();
  16397. // clipping
  16398. let _clippingEnabled = false;
  16399. let _localClippingEnabled = false;
  16400. // transmission
  16401. let _transmissionRenderTarget = null;
  16402. // camera matrices cache
  16403. const _projScreenMatrix = new Matrix4();
  16404. const _vector3 = new Vector3();
  16405. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16406. function getTargetPixelRatio() {
  16407. return _currentRenderTarget === null ? _pixelRatio : 1;
  16408. }
  16409. // initialize
  16410. let _gl = _context;
  16411. function getContext( contextNames, contextAttributes ) {
  16412. for ( let i = 0; i < contextNames.length; i ++ ) {
  16413. const contextName = contextNames[ i ];
  16414. const context = _canvas.getContext( contextName, contextAttributes );
  16415. if ( context !== null ) return context;
  16416. }
  16417. return null;
  16418. }
  16419. try {
  16420. const contextAttributes = {
  16421. alpha: true,
  16422. depth: _depth,
  16423. stencil: _stencil,
  16424. antialias: _antialias,
  16425. premultipliedAlpha: _premultipliedAlpha,
  16426. preserveDrawingBuffer: _preserveDrawingBuffer,
  16427. powerPreference: _powerPreference,
  16428. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16429. };
  16430. // OffscreenCanvas does not have setAttribute, see #22811
  16431. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16432. // event listeners must be registered before WebGL context is created, see #12753
  16433. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16434. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16435. _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16436. if ( _gl === null ) {
  16437. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16438. if ( _this.isWebGL1Renderer === true ) {
  16439. contextNames.shift();
  16440. }
  16441. _gl = getContext( contextNames, contextAttributes );
  16442. if ( _gl === null ) {
  16443. if ( getContext( contextNames ) ) {
  16444. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16445. } else {
  16446. throw new Error( 'Error creating WebGL context.' );
  16447. }
  16448. }
  16449. }
  16450. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16451. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16452. _gl.getShaderPrecisionFormat = function () {
  16453. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16454. };
  16455. }
  16456. } catch ( error ) {
  16457. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16458. throw error;
  16459. }
  16460. let extensions, capabilities, state, info;
  16461. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16462. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16463. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16464. let utils, bindingStates, uniformsGroups;
  16465. function initGLContext() {
  16466. extensions = new WebGLExtensions( _gl );
  16467. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16468. extensions.init( capabilities );
  16469. utils = new WebGLUtils( _gl, extensions, capabilities );
  16470. state = new WebGLState( _gl, extensions, capabilities );
  16471. info = new WebGLInfo( _gl );
  16472. properties = new WebGLProperties();
  16473. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16474. cubemaps = new WebGLCubeMaps( _this );
  16475. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16476. attributes = new WebGLAttributes( _gl, capabilities );
  16477. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16478. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16479. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16480. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16481. clipping = new WebGLClipping( properties );
  16482. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16483. materials = new WebGLMaterials( _this, properties );
  16484. renderLists = new WebGLRenderLists();
  16485. renderStates = new WebGLRenderStates( extensions, capabilities );
  16486. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha );
  16487. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16488. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16489. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16490. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16491. info.programs = programCache.programs;
  16492. _this.capabilities = capabilities;
  16493. _this.extensions = extensions;
  16494. _this.properties = properties;
  16495. _this.renderLists = renderLists;
  16496. _this.shadowMap = shadowMap;
  16497. _this.state = state;
  16498. _this.info = info;
  16499. }
  16500. initGLContext();
  16501. // xr
  16502. const xr = new WebXRManager( _this, _gl );
  16503. this.xr = xr;
  16504. // API
  16505. this.getContext = function () {
  16506. return _gl;
  16507. };
  16508. this.getContextAttributes = function () {
  16509. return _gl.getContextAttributes();
  16510. };
  16511. this.forceContextLoss = function () {
  16512. const extension = extensions.get( 'WEBGL_lose_context' );
  16513. if ( extension ) extension.loseContext();
  16514. };
  16515. this.forceContextRestore = function () {
  16516. const extension = extensions.get( 'WEBGL_lose_context' );
  16517. if ( extension ) extension.restoreContext();
  16518. };
  16519. this.getPixelRatio = function () {
  16520. return _pixelRatio;
  16521. };
  16522. this.setPixelRatio = function ( value ) {
  16523. if ( value === undefined ) return;
  16524. _pixelRatio = value;
  16525. this.setSize( _width, _height, false );
  16526. };
  16527. this.getSize = function ( target ) {
  16528. return target.set( _width, _height );
  16529. };
  16530. this.setSize = function ( width, height, updateStyle = true ) {
  16531. if ( xr.isPresenting ) {
  16532. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16533. return;
  16534. }
  16535. _width = width;
  16536. _height = height;
  16537. _canvas.width = Math.floor( width * _pixelRatio );
  16538. _canvas.height = Math.floor( height * _pixelRatio );
  16539. if ( updateStyle === true ) {
  16540. _canvas.style.width = width + 'px';
  16541. _canvas.style.height = height + 'px';
  16542. }
  16543. this.setViewport( 0, 0, width, height );
  16544. };
  16545. this.getDrawingBufferSize = function ( target ) {
  16546. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16547. };
  16548. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16549. _width = width;
  16550. _height = height;
  16551. _pixelRatio = pixelRatio;
  16552. _canvas.width = Math.floor( width * pixelRatio );
  16553. _canvas.height = Math.floor( height * pixelRatio );
  16554. this.setViewport( 0, 0, width, height );
  16555. };
  16556. this.getCurrentViewport = function ( target ) {
  16557. return target.copy( _currentViewport );
  16558. };
  16559. this.getViewport = function ( target ) {
  16560. return target.copy( _viewport );
  16561. };
  16562. this.setViewport = function ( x, y, width, height ) {
  16563. if ( x.isVector4 ) {
  16564. _viewport.set( x.x, x.y, x.z, x.w );
  16565. } else {
  16566. _viewport.set( x, y, width, height );
  16567. }
  16568. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16569. };
  16570. this.getScissor = function ( target ) {
  16571. return target.copy( _scissor );
  16572. };
  16573. this.setScissor = function ( x, y, width, height ) {
  16574. if ( x.isVector4 ) {
  16575. _scissor.set( x.x, x.y, x.z, x.w );
  16576. } else {
  16577. _scissor.set( x, y, width, height );
  16578. }
  16579. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16580. };
  16581. this.getScissorTest = function () {
  16582. return _scissorTest;
  16583. };
  16584. this.setScissorTest = function ( boolean ) {
  16585. state.setScissorTest( _scissorTest = boolean );
  16586. };
  16587. this.setOpaqueSort = function ( method ) {
  16588. _opaqueSort = method;
  16589. };
  16590. this.setTransparentSort = function ( method ) {
  16591. _transparentSort = method;
  16592. };
  16593. // Clearing
  16594. this.getClearColor = function ( target ) {
  16595. return target.copy( background.getClearColor() );
  16596. };
  16597. this.setClearColor = function () {
  16598. background.setClearColor.apply( background, arguments );
  16599. };
  16600. this.getClearAlpha = function () {
  16601. return background.getClearAlpha();
  16602. };
  16603. this.setClearAlpha = function () {
  16604. background.setClearAlpha.apply( background, arguments );
  16605. };
  16606. this.clear = function ( color = true, depth = true, stencil = true ) {
  16607. let bits = 0;
  16608. if ( color ) bits |= _gl.COLOR_BUFFER_BIT;
  16609. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  16610. if ( stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  16611. _gl.clear( bits );
  16612. };
  16613. this.clearColor = function () {
  16614. this.clear( true, false, false );
  16615. };
  16616. this.clearDepth = function () {
  16617. this.clear( false, true, false );
  16618. };
  16619. this.clearStencil = function () {
  16620. this.clear( false, false, true );
  16621. };
  16622. //
  16623. this.dispose = function () {
  16624. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16625. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16626. _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16627. renderLists.dispose();
  16628. renderStates.dispose();
  16629. properties.dispose();
  16630. cubemaps.dispose();
  16631. cubeuvmaps.dispose();
  16632. objects.dispose();
  16633. bindingStates.dispose();
  16634. uniformsGroups.dispose();
  16635. programCache.dispose();
  16636. xr.dispose();
  16637. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16638. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16639. if ( _transmissionRenderTarget ) {
  16640. _transmissionRenderTarget.dispose();
  16641. _transmissionRenderTarget = null;
  16642. }
  16643. animation.stop();
  16644. };
  16645. // Events
  16646. function onContextLost( event ) {
  16647. event.preventDefault();
  16648. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16649. _isContextLost = true;
  16650. }
  16651. function onContextRestore( /* event */ ) {
  16652. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16653. _isContextLost = false;
  16654. const infoAutoReset = info.autoReset;
  16655. const shadowMapEnabled = shadowMap.enabled;
  16656. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16657. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16658. const shadowMapType = shadowMap.type;
  16659. initGLContext();
  16660. info.autoReset = infoAutoReset;
  16661. shadowMap.enabled = shadowMapEnabled;
  16662. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16663. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16664. shadowMap.type = shadowMapType;
  16665. }
  16666. function onContextCreationError( event ) {
  16667. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16668. }
  16669. function onMaterialDispose( event ) {
  16670. const material = event.target;
  16671. material.removeEventListener( 'dispose', onMaterialDispose );
  16672. deallocateMaterial( material );
  16673. }
  16674. // Buffer deallocation
  16675. function deallocateMaterial( material ) {
  16676. releaseMaterialProgramReferences( material );
  16677. properties.remove( material );
  16678. }
  16679. function releaseMaterialProgramReferences( material ) {
  16680. const programs = properties.get( material ).programs;
  16681. if ( programs !== undefined ) {
  16682. programs.forEach( function ( program ) {
  16683. programCache.releaseProgram( program );
  16684. } );
  16685. if ( material.isShaderMaterial ) {
  16686. programCache.releaseShaderCache( material );
  16687. }
  16688. }
  16689. }
  16690. // Buffer rendering
  16691. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16692. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16693. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16694. const program = setProgram( camera, scene, geometry, material, object );
  16695. state.setMaterial( material, frontFaceCW );
  16696. //
  16697. let index = geometry.index;
  16698. let rangeFactor = 1;
  16699. if ( material.wireframe === true ) {
  16700. index = geometries.getWireframeAttribute( geometry );
  16701. rangeFactor = 2;
  16702. }
  16703. //
  16704. const drawRange = geometry.drawRange;
  16705. const position = geometry.attributes.position;
  16706. let drawStart = drawRange.start * rangeFactor;
  16707. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  16708. if ( group !== null ) {
  16709. drawStart = Math.max( drawStart, group.start * rangeFactor );
  16710. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  16711. }
  16712. if ( index !== null ) {
  16713. drawStart = Math.max( drawStart, 0 );
  16714. drawEnd = Math.min( drawEnd, index.count );
  16715. } else if ( position !== undefined && position !== null ) {
  16716. drawStart = Math.max( drawStart, 0 );
  16717. drawEnd = Math.min( drawEnd, position.count );
  16718. }
  16719. const drawCount = drawEnd - drawStart;
  16720. if ( drawCount < 0 || drawCount === Infinity ) return;
  16721. //
  16722. bindingStates.setup( object, material, program, geometry, index );
  16723. let attribute;
  16724. let renderer = bufferRenderer;
  16725. if ( index !== null ) {
  16726. attribute = attributes.get( index );
  16727. renderer = indexedBufferRenderer;
  16728. renderer.setIndex( attribute );
  16729. }
  16730. //
  16731. if ( object.isMesh ) {
  16732. if ( material.wireframe === true ) {
  16733. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16734. renderer.setMode( _gl.LINES );
  16735. } else {
  16736. renderer.setMode( _gl.TRIANGLES );
  16737. }
  16738. } else if ( object.isLine ) {
  16739. let lineWidth = material.linewidth;
  16740. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16741. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16742. if ( object.isLineSegments ) {
  16743. renderer.setMode( _gl.LINES );
  16744. } else if ( object.isLineLoop ) {
  16745. renderer.setMode( _gl.LINE_LOOP );
  16746. } else {
  16747. renderer.setMode( _gl.LINE_STRIP );
  16748. }
  16749. } else if ( object.isPoints ) {
  16750. renderer.setMode( _gl.POINTS );
  16751. } else if ( object.isSprite ) {
  16752. renderer.setMode( _gl.TRIANGLES );
  16753. }
  16754. if ( object.isInstancedMesh ) {
  16755. renderer.renderInstances( drawStart, drawCount, object.count );
  16756. } else if ( geometry.isInstancedBufferGeometry ) {
  16757. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  16758. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  16759. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16760. } else {
  16761. renderer.render( drawStart, drawCount );
  16762. }
  16763. };
  16764. // Compile
  16765. this.compile = function ( scene, camera ) {
  16766. function prepare( material, scene, object ) {
  16767. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16768. material.side = BackSide;
  16769. material.needsUpdate = true;
  16770. getProgram( material, scene, object );
  16771. material.side = FrontSide;
  16772. material.needsUpdate = true;
  16773. getProgram( material, scene, object );
  16774. material.side = DoubleSide;
  16775. } else {
  16776. getProgram( material, scene, object );
  16777. }
  16778. }
  16779. currentRenderState = renderStates.get( scene );
  16780. currentRenderState.init();
  16781. renderStateStack.push( currentRenderState );
  16782. scene.traverseVisible( function ( object ) {
  16783. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16784. currentRenderState.pushLight( object );
  16785. if ( object.castShadow ) {
  16786. currentRenderState.pushShadow( object );
  16787. }
  16788. }
  16789. } );
  16790. currentRenderState.setupLights( _this.useLegacyLights );
  16791. scene.traverse( function ( object ) {
  16792. const material = object.material;
  16793. if ( material ) {
  16794. if ( Array.isArray( material ) ) {
  16795. for ( let i = 0; i < material.length; i ++ ) {
  16796. const material2 = material[ i ];
  16797. prepare( material2, scene, object );
  16798. }
  16799. } else {
  16800. prepare( material, scene, object );
  16801. }
  16802. }
  16803. } );
  16804. renderStateStack.pop();
  16805. currentRenderState = null;
  16806. };
  16807. // Animation Loop
  16808. let onAnimationFrameCallback = null;
  16809. function onAnimationFrame( time ) {
  16810. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16811. }
  16812. function onXRSessionStart() {
  16813. animation.stop();
  16814. }
  16815. function onXRSessionEnd() {
  16816. animation.start();
  16817. }
  16818. const animation = new WebGLAnimation();
  16819. animation.setAnimationLoop( onAnimationFrame );
  16820. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16821. this.setAnimationLoop = function ( callback ) {
  16822. onAnimationFrameCallback = callback;
  16823. xr.setAnimationLoop( callback );
  16824. ( callback === null ) ? animation.stop() : animation.start();
  16825. };
  16826. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16827. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16828. // Rendering
  16829. this.render = function ( scene, camera ) {
  16830. if ( camera !== undefined && camera.isCamera !== true ) {
  16831. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16832. return;
  16833. }
  16834. if ( _isContextLost === true ) return;
  16835. // update scene graph
  16836. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16837. // update camera matrices and frustum
  16838. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16839. if ( xr.enabled === true && xr.isPresenting === true ) {
  16840. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16841. camera = xr.getCamera(); // use XR camera for rendering
  16842. }
  16843. //
  16844. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16845. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16846. currentRenderState.init();
  16847. renderStateStack.push( currentRenderState );
  16848. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16849. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16850. _localClippingEnabled = this.localClippingEnabled;
  16851. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  16852. currentRenderList = renderLists.get( scene, renderListStack.length );
  16853. currentRenderList.init();
  16854. renderListStack.push( currentRenderList );
  16855. projectObject( scene, camera, 0, _this.sortObjects );
  16856. currentRenderList.finish();
  16857. if ( _this.sortObjects === true ) {
  16858. currentRenderList.sort( _opaqueSort, _transparentSort );
  16859. }
  16860. //
  16861. if ( _clippingEnabled === true ) clipping.beginShadows();
  16862. const shadowsArray = currentRenderState.state.shadowsArray;
  16863. shadowMap.render( shadowsArray, scene, camera );
  16864. if ( _clippingEnabled === true ) clipping.endShadows();
  16865. //
  16866. if ( this.info.autoReset === true ) this.info.reset();
  16867. //
  16868. background.render( currentRenderList, scene );
  16869. // render scene
  16870. currentRenderState.setupLights( _this.useLegacyLights );
  16871. if ( camera.isArrayCamera ) {
  16872. const cameras = camera.cameras;
  16873. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16874. const camera2 = cameras[ i ];
  16875. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16876. }
  16877. } else {
  16878. renderScene( currentRenderList, scene, camera );
  16879. }
  16880. //
  16881. if ( _currentRenderTarget !== null ) {
  16882. // resolve multisample renderbuffers to a single-sample texture if necessary
  16883. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16884. // Generate mipmap if we're using any kind of mipmap filtering
  16885. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16886. }
  16887. //
  16888. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16889. // _gl.finish();
  16890. bindingStates.resetDefaultState();
  16891. _currentMaterialId = - 1;
  16892. _currentCamera = null;
  16893. renderStateStack.pop();
  16894. if ( renderStateStack.length > 0 ) {
  16895. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16896. } else {
  16897. currentRenderState = null;
  16898. }
  16899. renderListStack.pop();
  16900. if ( renderListStack.length > 0 ) {
  16901. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16902. } else {
  16903. currentRenderList = null;
  16904. }
  16905. };
  16906. function projectObject( object, camera, groupOrder, sortObjects ) {
  16907. if ( object.visible === false ) return;
  16908. const visible = object.layers.test( camera.layers );
  16909. if ( visible ) {
  16910. if ( object.isGroup ) {
  16911. groupOrder = object.renderOrder;
  16912. } else if ( object.isLOD ) {
  16913. if ( object.autoUpdate === true ) object.update( camera );
  16914. } else if ( object.isLight ) {
  16915. currentRenderState.pushLight( object );
  16916. if ( object.castShadow ) {
  16917. currentRenderState.pushShadow( object );
  16918. }
  16919. } else if ( object.isSprite ) {
  16920. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16921. if ( sortObjects ) {
  16922. _vector3.setFromMatrixPosition( object.matrixWorld )
  16923. .applyMatrix4( _projScreenMatrix );
  16924. }
  16925. const geometry = objects.update( object );
  16926. const material = object.material;
  16927. if ( material.visible ) {
  16928. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16929. }
  16930. }
  16931. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16932. if ( object.isSkinnedMesh ) {
  16933. // update skeleton only once in a frame
  16934. if ( object.skeleton.frame !== info.render.frame ) {
  16935. object.skeleton.update();
  16936. object.skeleton.frame = info.render.frame;
  16937. }
  16938. }
  16939. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16940. if ( sortObjects ) {
  16941. _vector3.setFromMatrixPosition( object.matrixWorld )
  16942. .applyMatrix4( _projScreenMatrix );
  16943. }
  16944. const geometry = objects.update( object );
  16945. const material = object.material;
  16946. if ( Array.isArray( material ) ) {
  16947. const groups = geometry.groups;
  16948. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16949. const group = groups[ i ];
  16950. const groupMaterial = material[ group.materialIndex ];
  16951. if ( groupMaterial && groupMaterial.visible ) {
  16952. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16953. }
  16954. }
  16955. } else if ( material.visible ) {
  16956. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16957. }
  16958. }
  16959. }
  16960. }
  16961. const children = object.children;
  16962. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16963. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16964. }
  16965. }
  16966. function renderScene( currentRenderList, scene, camera, viewport ) {
  16967. const opaqueObjects = currentRenderList.opaque;
  16968. const transmissiveObjects = currentRenderList.transmissive;
  16969. const transparentObjects = currentRenderList.transparent;
  16970. currentRenderState.setupLightsView( camera );
  16971. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  16972. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  16973. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16974. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16975. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16976. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16977. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16978. state.buffers.depth.setTest( true );
  16979. state.buffers.depth.setMask( true );
  16980. state.buffers.color.setMask( true );
  16981. state.setPolygonOffset( false );
  16982. }
  16983. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  16984. if ( _transmissionRenderTarget === null ) {
  16985. const isWebGL2 = capabilities.isWebGL2;
  16986. _transmissionRenderTarget = new WebGLRenderTarget( 1024, 1024, {
  16987. generateMipmaps: true,
  16988. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  16989. minFilter: LinearMipmapLinearFilter,
  16990. samples: ( isWebGL2 && _antialias === true ) ? 4 : 0
  16991. } );
  16992. // debug
  16993. /*
  16994. const geometry = new PlaneGeometry();
  16995. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  16996. const mesh = new Mesh( geometry, material );
  16997. scene.add( mesh );
  16998. */
  16999. }
  17000. //
  17001. const currentRenderTarget = _this.getRenderTarget();
  17002. _this.setRenderTarget( _transmissionRenderTarget );
  17003. _this.clear();
  17004. // Turn off the features which can affect the frag color for opaque objects pass.
  17005. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17006. const currentToneMapping = _this.toneMapping;
  17007. _this.toneMapping = NoToneMapping;
  17008. renderObjects( opaqueObjects, scene, camera );
  17009. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17010. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17011. let renderTargetNeedsUpdate = false;
  17012. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17013. const renderItem = transmissiveObjects[ i ];
  17014. const object = renderItem.object;
  17015. const geometry = renderItem.geometry;
  17016. const material = renderItem.material;
  17017. const group = renderItem.group;
  17018. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17019. const currentSide = material.side;
  17020. material.side = BackSide;
  17021. material.needsUpdate = true;
  17022. renderObject( object, scene, camera, geometry, material, group );
  17023. material.side = currentSide;
  17024. material.needsUpdate = true;
  17025. renderTargetNeedsUpdate = true;
  17026. }
  17027. }
  17028. if ( renderTargetNeedsUpdate === true ) {
  17029. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17030. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17031. }
  17032. _this.setRenderTarget( currentRenderTarget );
  17033. _this.toneMapping = currentToneMapping;
  17034. }
  17035. function renderObjects( renderList, scene, camera ) {
  17036. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17037. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17038. const renderItem = renderList[ i ];
  17039. const object = renderItem.object;
  17040. const geometry = renderItem.geometry;
  17041. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17042. const group = renderItem.group;
  17043. if ( object.layers.test( camera.layers ) ) {
  17044. renderObject( object, scene, camera, geometry, material, group );
  17045. }
  17046. }
  17047. }
  17048. function renderObject( object, scene, camera, geometry, material, group ) {
  17049. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17050. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17051. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17052. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17053. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17054. material.side = BackSide;
  17055. material.needsUpdate = true;
  17056. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17057. material.side = FrontSide;
  17058. material.needsUpdate = true;
  17059. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17060. material.side = DoubleSide;
  17061. } else {
  17062. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17063. }
  17064. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17065. }
  17066. function getProgram( material, scene, object ) {
  17067. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17068. const materialProperties = properties.get( material );
  17069. const lights = currentRenderState.state.lights;
  17070. const shadowsArray = currentRenderState.state.shadowsArray;
  17071. const lightsStateVersion = lights.state.version;
  17072. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17073. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17074. let programs = materialProperties.programs;
  17075. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17076. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17077. materialProperties.fog = scene.fog;
  17078. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17079. if ( programs === undefined ) {
  17080. // new material
  17081. material.addEventListener( 'dispose', onMaterialDispose );
  17082. programs = new Map();
  17083. materialProperties.programs = programs;
  17084. }
  17085. let program = programs.get( programCacheKey );
  17086. if ( program !== undefined ) {
  17087. // early out if program and light state is identical
  17088. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17089. updateCommonMaterialProperties( material, parameters );
  17090. return program;
  17091. }
  17092. } else {
  17093. parameters.uniforms = programCache.getUniforms( material );
  17094. material.onBuild( object, parameters, _this );
  17095. material.onBeforeCompile( parameters, _this );
  17096. program = programCache.acquireProgram( parameters, programCacheKey );
  17097. programs.set( programCacheKey, program );
  17098. materialProperties.uniforms = parameters.uniforms;
  17099. }
  17100. const uniforms = materialProperties.uniforms;
  17101. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17102. uniforms.clippingPlanes = clipping.uniform;
  17103. }
  17104. updateCommonMaterialProperties( material, parameters );
  17105. // store the light setup it was created for
  17106. materialProperties.needsLights = materialNeedsLights( material );
  17107. materialProperties.lightsStateVersion = lightsStateVersion;
  17108. if ( materialProperties.needsLights ) {
  17109. // wire up the material to this renderer's lighting state
  17110. uniforms.ambientLightColor.value = lights.state.ambient;
  17111. uniforms.lightProbe.value = lights.state.probe;
  17112. uniforms.directionalLights.value = lights.state.directional;
  17113. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17114. uniforms.spotLights.value = lights.state.spot;
  17115. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17116. uniforms.rectAreaLights.value = lights.state.rectArea;
  17117. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17118. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17119. uniforms.pointLights.value = lights.state.point;
  17120. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17121. uniforms.hemisphereLights.value = lights.state.hemi;
  17122. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17123. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17124. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17125. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17126. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17127. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17128. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17129. // TODO (abelnation): add area lights shadow info to uniforms
  17130. }
  17131. const progUniforms = program.getUniforms();
  17132. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17133. materialProperties.currentProgram = program;
  17134. materialProperties.uniformsList = uniformsList;
  17135. return program;
  17136. }
  17137. function updateCommonMaterialProperties( material, parameters ) {
  17138. const materialProperties = properties.get( material );
  17139. materialProperties.outputEncoding = parameters.outputEncoding;
  17140. materialProperties.instancing = parameters.instancing;
  17141. materialProperties.skinning = parameters.skinning;
  17142. materialProperties.morphTargets = parameters.morphTargets;
  17143. materialProperties.morphNormals = parameters.morphNormals;
  17144. materialProperties.morphColors = parameters.morphColors;
  17145. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17146. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17147. materialProperties.numIntersection = parameters.numClipIntersection;
  17148. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17149. materialProperties.vertexTangents = parameters.vertexTangents;
  17150. materialProperties.toneMapping = parameters.toneMapping;
  17151. }
  17152. function setProgram( camera, scene, geometry, material, object ) {
  17153. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17154. textures.resetTextureUnits();
  17155. const fog = scene.fog;
  17156. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17157. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  17158. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17159. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17160. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  17161. const morphTargets = !! geometry.morphAttributes.position;
  17162. const morphNormals = !! geometry.morphAttributes.normal;
  17163. const morphColors = !! geometry.morphAttributes.color;
  17164. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  17165. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17166. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  17167. const materialProperties = properties.get( material );
  17168. const lights = currentRenderState.state.lights;
  17169. if ( _clippingEnabled === true ) {
  17170. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17171. const useCache =
  17172. camera === _currentCamera &&
  17173. material.id === _currentMaterialId;
  17174. // we might want to call this function with some ClippingGroup
  17175. // object instead of the material, once it becomes feasible
  17176. // (#8465, #8379)
  17177. clipping.setState( material, camera, useCache );
  17178. }
  17179. }
  17180. //
  17181. let needsProgramChange = false;
  17182. if ( material.version === materialProperties.__version ) {
  17183. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17184. needsProgramChange = true;
  17185. } else if ( materialProperties.outputEncoding !== encoding ) {
  17186. needsProgramChange = true;
  17187. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17188. needsProgramChange = true;
  17189. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17190. needsProgramChange = true;
  17191. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17192. needsProgramChange = true;
  17193. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17194. needsProgramChange = true;
  17195. } else if ( materialProperties.envMap !== envMap ) {
  17196. needsProgramChange = true;
  17197. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17198. needsProgramChange = true;
  17199. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17200. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17201. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17202. needsProgramChange = true;
  17203. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17204. needsProgramChange = true;
  17205. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17206. needsProgramChange = true;
  17207. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17208. needsProgramChange = true;
  17209. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17210. needsProgramChange = true;
  17211. } else if ( materialProperties.morphColors !== morphColors ) {
  17212. needsProgramChange = true;
  17213. } else if ( materialProperties.toneMapping !== toneMapping ) {
  17214. needsProgramChange = true;
  17215. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  17216. needsProgramChange = true;
  17217. }
  17218. } else {
  17219. needsProgramChange = true;
  17220. materialProperties.__version = material.version;
  17221. }
  17222. //
  17223. let program = materialProperties.currentProgram;
  17224. if ( needsProgramChange === true ) {
  17225. program = getProgram( material, scene, object );
  17226. }
  17227. let refreshProgram = false;
  17228. let refreshMaterial = false;
  17229. let refreshLights = false;
  17230. const p_uniforms = program.getUniforms(),
  17231. m_uniforms = materialProperties.uniforms;
  17232. if ( state.useProgram( program.program ) ) {
  17233. refreshProgram = true;
  17234. refreshMaterial = true;
  17235. refreshLights = true;
  17236. }
  17237. if ( material.id !== _currentMaterialId ) {
  17238. _currentMaterialId = material.id;
  17239. refreshMaterial = true;
  17240. }
  17241. if ( refreshProgram || _currentCamera !== camera ) {
  17242. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17243. if ( capabilities.logarithmicDepthBuffer ) {
  17244. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17245. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17246. }
  17247. if ( _currentCamera !== camera ) {
  17248. _currentCamera = camera;
  17249. // lighting uniforms depend on the camera so enforce an update
  17250. // now, in case this material supports lights - or later, when
  17251. // the next material that does gets activated:
  17252. refreshMaterial = true; // set to true on material change
  17253. refreshLights = true; // remains set until update done
  17254. }
  17255. // load material specific uniforms
  17256. // (shader material also gets them for the sake of genericity)
  17257. if ( material.isShaderMaterial ||
  17258. material.isMeshPhongMaterial ||
  17259. material.isMeshToonMaterial ||
  17260. material.isMeshStandardMaterial ||
  17261. material.envMap ) {
  17262. const uCamPos = p_uniforms.map.cameraPosition;
  17263. if ( uCamPos !== undefined ) {
  17264. uCamPos.setValue( _gl,
  17265. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17266. }
  17267. }
  17268. if ( material.isMeshPhongMaterial ||
  17269. material.isMeshToonMaterial ||
  17270. material.isMeshLambertMaterial ||
  17271. material.isMeshBasicMaterial ||
  17272. material.isMeshStandardMaterial ||
  17273. material.isShaderMaterial ) {
  17274. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17275. }
  17276. if ( material.isMeshPhongMaterial ||
  17277. material.isMeshToonMaterial ||
  17278. material.isMeshLambertMaterial ||
  17279. material.isMeshBasicMaterial ||
  17280. material.isMeshStandardMaterial ||
  17281. material.isShaderMaterial ||
  17282. material.isShadowMaterial ||
  17283. object.isSkinnedMesh ) {
  17284. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17285. }
  17286. }
  17287. // skinning and morph target uniforms must be set even if material didn't change
  17288. // auto-setting of texture unit for bone and morph texture must go before other textures
  17289. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17290. if ( object.isSkinnedMesh ) {
  17291. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17292. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17293. const skeleton = object.skeleton;
  17294. if ( skeleton ) {
  17295. if ( capabilities.floatVertexTextures ) {
  17296. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17297. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17298. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17299. } else {
  17300. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17301. }
  17302. }
  17303. }
  17304. const morphAttributes = geometry.morphAttributes;
  17305. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17306. morphtargets.update( object, geometry, program );
  17307. }
  17308. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17309. materialProperties.receiveShadow = object.receiveShadow;
  17310. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17311. }
  17312. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17313. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17314. m_uniforms.envMap.value = envMap;
  17315. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17316. }
  17317. if ( refreshMaterial ) {
  17318. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17319. if ( materialProperties.needsLights ) {
  17320. // the current material requires lighting info
  17321. // note: all lighting uniforms are always set correctly
  17322. // they simply reference the renderer's state for their
  17323. // values
  17324. //
  17325. // use the current material's .needsUpdate flags to set
  17326. // the GL state when required
  17327. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17328. }
  17329. // refresh uniforms common to several materials
  17330. if ( fog && material.fog === true ) {
  17331. materials.refreshFogUniforms( m_uniforms, fog );
  17332. }
  17333. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17334. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17335. }
  17336. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17337. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17338. material.uniformsNeedUpdate = false;
  17339. }
  17340. if ( material.isSpriteMaterial ) {
  17341. p_uniforms.setValue( _gl, 'center', object.center );
  17342. }
  17343. // common matrices
  17344. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17345. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17346. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17347. // UBOs
  17348. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17349. const groups = material.uniformsGroups;
  17350. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17351. if ( capabilities.isWebGL2 ) {
  17352. const group = groups[ i ];
  17353. uniformsGroups.update( group, program );
  17354. uniformsGroups.bind( group, program );
  17355. } else {
  17356. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17357. }
  17358. }
  17359. }
  17360. return program;
  17361. }
  17362. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17363. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17364. uniforms.ambientLightColor.needsUpdate = value;
  17365. uniforms.lightProbe.needsUpdate = value;
  17366. uniforms.directionalLights.needsUpdate = value;
  17367. uniforms.directionalLightShadows.needsUpdate = value;
  17368. uniforms.pointLights.needsUpdate = value;
  17369. uniforms.pointLightShadows.needsUpdate = value;
  17370. uniforms.spotLights.needsUpdate = value;
  17371. uniforms.spotLightShadows.needsUpdate = value;
  17372. uniforms.rectAreaLights.needsUpdate = value;
  17373. uniforms.hemisphereLights.needsUpdate = value;
  17374. }
  17375. function materialNeedsLights( material ) {
  17376. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17377. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17378. ( material.isShaderMaterial && material.lights === true );
  17379. }
  17380. this.getActiveCubeFace = function () {
  17381. return _currentActiveCubeFace;
  17382. };
  17383. this.getActiveMipmapLevel = function () {
  17384. return _currentActiveMipmapLevel;
  17385. };
  17386. this.getRenderTarget = function () {
  17387. return _currentRenderTarget;
  17388. };
  17389. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17390. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17391. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17392. const renderTargetProperties = properties.get( renderTarget );
  17393. renderTargetProperties.__hasExternalTextures = true;
  17394. if ( renderTargetProperties.__hasExternalTextures ) {
  17395. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17396. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17397. // The multisample_render_to_texture extension doesn't work properly if there
  17398. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17399. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17400. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17401. renderTargetProperties.__useRenderToTexture = false;
  17402. }
  17403. }
  17404. }
  17405. };
  17406. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17407. const renderTargetProperties = properties.get( renderTarget );
  17408. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17409. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17410. };
  17411. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17412. _currentRenderTarget = renderTarget;
  17413. _currentActiveCubeFace = activeCubeFace;
  17414. _currentActiveMipmapLevel = activeMipmapLevel;
  17415. let useDefaultFramebuffer = true;
  17416. let framebuffer = null;
  17417. let isCube = false;
  17418. let isRenderTarget3D = false;
  17419. if ( renderTarget ) {
  17420. const renderTargetProperties = properties.get( renderTarget );
  17421. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17422. // We need to make sure to rebind the framebuffer.
  17423. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  17424. useDefaultFramebuffer = false;
  17425. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17426. textures.setupRenderTarget( renderTarget );
  17427. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17428. // Color and depth texture must be rebound in order for the swapchain to update.
  17429. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17430. }
  17431. const texture = renderTarget.texture;
  17432. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17433. isRenderTarget3D = true;
  17434. }
  17435. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17436. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17437. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17438. isCube = true;
  17439. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17440. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17441. } else {
  17442. framebuffer = __webglFramebuffer;
  17443. }
  17444. _currentViewport.copy( renderTarget.viewport );
  17445. _currentScissor.copy( renderTarget.scissor );
  17446. _currentScissorTest = renderTarget.scissorTest;
  17447. } else {
  17448. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17449. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17450. _currentScissorTest = _scissorTest;
  17451. }
  17452. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17453. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17454. state.drawBuffers( renderTarget, framebuffer );
  17455. }
  17456. state.viewport( _currentViewport );
  17457. state.scissor( _currentScissor );
  17458. state.setScissorTest( _currentScissorTest );
  17459. if ( isCube ) {
  17460. const textureProperties = properties.get( renderTarget.texture );
  17461. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17462. } else if ( isRenderTarget3D ) {
  17463. const textureProperties = properties.get( renderTarget.texture );
  17464. const layer = activeCubeFace || 0;
  17465. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17466. }
  17467. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17468. };
  17469. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17470. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17471. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17472. return;
  17473. }
  17474. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17475. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17476. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17477. }
  17478. if ( framebuffer ) {
  17479. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17480. try {
  17481. const texture = renderTarget.texture;
  17482. const textureFormat = texture.format;
  17483. const textureType = texture.type;
  17484. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  17485. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17486. return;
  17487. }
  17488. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17489. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  17490. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17491. ! halfFloatSupportedByExt ) {
  17492. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17493. return;
  17494. }
  17495. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17496. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17497. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17498. }
  17499. } finally {
  17500. // restore framebuffer of current render target if necessary
  17501. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17502. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17503. }
  17504. }
  17505. };
  17506. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17507. const levelScale = Math.pow( 2, - level );
  17508. const width = Math.floor( texture.image.width * levelScale );
  17509. const height = Math.floor( texture.image.height * levelScale );
  17510. textures.setTexture2D( texture, 0 );
  17511. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  17512. state.unbindTexture();
  17513. };
  17514. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17515. const width = srcTexture.image.width;
  17516. const height = srcTexture.image.height;
  17517. const glFormat = utils.convert( dstTexture.format );
  17518. const glType = utils.convert( dstTexture.type );
  17519. textures.setTexture2D( dstTexture, 0 );
  17520. // As another texture upload may have changed pixelStorei
  17521. // parameters, make sure they are correct for the dstTexture
  17522. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17523. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17524. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17525. if ( srcTexture.isDataTexture ) {
  17526. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17527. } else {
  17528. if ( srcTexture.isCompressedTexture ) {
  17529. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17530. } else {
  17531. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17532. }
  17533. }
  17534. // Generate mipmaps only when copying level 0
  17535. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  17536. state.unbindTexture();
  17537. };
  17538. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17539. if ( _this.isWebGL1Renderer ) {
  17540. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17541. return;
  17542. }
  17543. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17544. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17545. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17546. const glFormat = utils.convert( dstTexture.format );
  17547. const glType = utils.convert( dstTexture.type );
  17548. let glTarget;
  17549. if ( dstTexture.isData3DTexture ) {
  17550. textures.setTexture3D( dstTexture, 0 );
  17551. glTarget = _gl.TEXTURE_3D;
  17552. } else if ( dstTexture.isDataArrayTexture ) {
  17553. textures.setTexture2DArray( dstTexture, 0 );
  17554. glTarget = _gl.TEXTURE_2D_ARRAY;
  17555. } else {
  17556. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17557. return;
  17558. }
  17559. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17560. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17561. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17562. const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  17563. const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  17564. const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  17565. const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  17566. const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  17567. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17568. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  17569. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  17570. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );
  17571. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );
  17572. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );
  17573. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17574. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17575. } else {
  17576. if ( srcTexture.isCompressedArrayTexture ) {
  17577. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17578. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17579. } else {
  17580. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17581. }
  17582. }
  17583. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );
  17584. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );
  17585. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );
  17586. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );
  17587. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );
  17588. // Generate mipmaps only when copying level 0
  17589. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17590. state.unbindTexture();
  17591. };
  17592. this.initTexture = function ( texture ) {
  17593. if ( texture.isCubeTexture ) {
  17594. textures.setTextureCube( texture, 0 );
  17595. } else if ( texture.isData3DTexture ) {
  17596. textures.setTexture3D( texture, 0 );
  17597. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17598. textures.setTexture2DArray( texture, 0 );
  17599. } else {
  17600. textures.setTexture2D( texture, 0 );
  17601. }
  17602. state.unbindTexture();
  17603. };
  17604. this.resetState = function () {
  17605. _currentActiveCubeFace = 0;
  17606. _currentActiveMipmapLevel = 0;
  17607. _currentRenderTarget = null;
  17608. state.reset();
  17609. bindingStates.reset();
  17610. };
  17611. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17612. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17613. }
  17614. }
  17615. Object.defineProperties( WebGLRenderer.prototype, {
  17616. // @deprecated since r150
  17617. physicallyCorrectLights: {
  17618. get: function () {
  17619. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17620. return ! this.useLegacyLights;
  17621. },
  17622. set: function ( value ) {
  17623. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17624. this.useLegacyLights = ! value;
  17625. }
  17626. }
  17627. } );
  17628. class WebGL1Renderer extends WebGLRenderer {}
  17629. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17630. class FogExp2 {
  17631. constructor( color, density = 0.00025 ) {
  17632. this.isFogExp2 = true;
  17633. this.name = '';
  17634. this.color = new Color( color );
  17635. this.density = density;
  17636. }
  17637. clone() {
  17638. return new FogExp2( this.color, this.density );
  17639. }
  17640. toJSON( /* meta */ ) {
  17641. return {
  17642. type: 'FogExp2',
  17643. color: this.color.getHex(),
  17644. density: this.density
  17645. };
  17646. }
  17647. }
  17648. class Fog {
  17649. constructor( color, near = 1, far = 1000 ) {
  17650. this.isFog = true;
  17651. this.name = '';
  17652. this.color = new Color( color );
  17653. this.near = near;
  17654. this.far = far;
  17655. }
  17656. clone() {
  17657. return new Fog( this.color, this.near, this.far );
  17658. }
  17659. toJSON( /* meta */ ) {
  17660. return {
  17661. type: 'Fog',
  17662. color: this.color.getHex(),
  17663. near: this.near,
  17664. far: this.far
  17665. };
  17666. }
  17667. }
  17668. class Scene extends Object3D {
  17669. constructor() {
  17670. super();
  17671. this.isScene = true;
  17672. this.type = 'Scene';
  17673. this.background = null;
  17674. this.environment = null;
  17675. this.fog = null;
  17676. this.backgroundBlurriness = 0;
  17677. this.backgroundIntensity = 1;
  17678. this.overrideMaterial = null;
  17679. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17680. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17681. }
  17682. }
  17683. copy( source, recursive ) {
  17684. super.copy( source, recursive );
  17685. if ( source.background !== null ) this.background = source.background.clone();
  17686. if ( source.environment !== null ) this.environment = source.environment.clone();
  17687. if ( source.fog !== null ) this.fog = source.fog.clone();
  17688. this.backgroundBlurriness = source.backgroundBlurriness;
  17689. this.backgroundIntensity = source.backgroundIntensity;
  17690. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17691. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17692. return this;
  17693. }
  17694. toJSON( meta ) {
  17695. const data = super.toJSON( meta );
  17696. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17697. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17698. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17699. return data;
  17700. }
  17701. // @deprecated
  17702. get autoUpdate() {
  17703. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17704. return this.matrixWorldAutoUpdate;
  17705. }
  17706. set autoUpdate( value ) {
  17707. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17708. this.matrixWorldAutoUpdate = value;
  17709. }
  17710. }
  17711. class InterleavedBuffer {
  17712. constructor( array, stride ) {
  17713. this.isInterleavedBuffer = true;
  17714. this.array = array;
  17715. this.stride = stride;
  17716. this.count = array !== undefined ? array.length / stride : 0;
  17717. this.usage = StaticDrawUsage;
  17718. this.updateRange = { offset: 0, count: - 1 };
  17719. this.version = 0;
  17720. this.uuid = generateUUID();
  17721. }
  17722. onUploadCallback() {}
  17723. set needsUpdate( value ) {
  17724. if ( value === true ) this.version ++;
  17725. }
  17726. setUsage( value ) {
  17727. this.usage = value;
  17728. return this;
  17729. }
  17730. copy( source ) {
  17731. this.array = new source.array.constructor( source.array );
  17732. this.count = source.count;
  17733. this.stride = source.stride;
  17734. this.usage = source.usage;
  17735. return this;
  17736. }
  17737. copyAt( index1, attribute, index2 ) {
  17738. index1 *= this.stride;
  17739. index2 *= attribute.stride;
  17740. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17741. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17742. }
  17743. return this;
  17744. }
  17745. set( value, offset = 0 ) {
  17746. this.array.set( value, offset );
  17747. return this;
  17748. }
  17749. clone( data ) {
  17750. if ( data.arrayBuffers === undefined ) {
  17751. data.arrayBuffers = {};
  17752. }
  17753. if ( this.array.buffer._uuid === undefined ) {
  17754. this.array.buffer._uuid = generateUUID();
  17755. }
  17756. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17757. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17758. }
  17759. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17760. const ib = new this.constructor( array, this.stride );
  17761. ib.setUsage( this.usage );
  17762. return ib;
  17763. }
  17764. onUpload( callback ) {
  17765. this.onUploadCallback = callback;
  17766. return this;
  17767. }
  17768. toJSON( data ) {
  17769. if ( data.arrayBuffers === undefined ) {
  17770. data.arrayBuffers = {};
  17771. }
  17772. // generate UUID for array buffer if necessary
  17773. if ( this.array.buffer._uuid === undefined ) {
  17774. this.array.buffer._uuid = generateUUID();
  17775. }
  17776. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17777. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17778. }
  17779. //
  17780. return {
  17781. uuid: this.uuid,
  17782. buffer: this.array.buffer._uuid,
  17783. type: this.array.constructor.name,
  17784. stride: this.stride
  17785. };
  17786. }
  17787. }
  17788. const _vector$5 = /*@__PURE__*/ new Vector3();
  17789. class InterleavedBufferAttribute {
  17790. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17791. this.isInterleavedBufferAttribute = true;
  17792. this.name = '';
  17793. this.data = interleavedBuffer;
  17794. this.itemSize = itemSize;
  17795. this.offset = offset;
  17796. this.normalized = normalized;
  17797. }
  17798. get count() {
  17799. return this.data.count;
  17800. }
  17801. get array() {
  17802. return this.data.array;
  17803. }
  17804. set needsUpdate( value ) {
  17805. this.data.needsUpdate = value;
  17806. }
  17807. applyMatrix4( m ) {
  17808. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17809. _vector$5.fromBufferAttribute( this, i );
  17810. _vector$5.applyMatrix4( m );
  17811. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  17812. }
  17813. return this;
  17814. }
  17815. applyNormalMatrix( m ) {
  17816. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17817. _vector$5.fromBufferAttribute( this, i );
  17818. _vector$5.applyNormalMatrix( m );
  17819. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  17820. }
  17821. return this;
  17822. }
  17823. transformDirection( m ) {
  17824. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17825. _vector$5.fromBufferAttribute( this, i );
  17826. _vector$5.transformDirection( m );
  17827. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  17828. }
  17829. return this;
  17830. }
  17831. setX( index, x ) {
  17832. if ( this.normalized ) x = normalize( x, this.array );
  17833. this.data.array[ index * this.data.stride + this.offset ] = x;
  17834. return this;
  17835. }
  17836. setY( index, y ) {
  17837. if ( this.normalized ) y = normalize( y, this.array );
  17838. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17839. return this;
  17840. }
  17841. setZ( index, z ) {
  17842. if ( this.normalized ) z = normalize( z, this.array );
  17843. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17844. return this;
  17845. }
  17846. setW( index, w ) {
  17847. if ( this.normalized ) w = normalize( w, this.array );
  17848. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17849. return this;
  17850. }
  17851. getX( index ) {
  17852. let x = this.data.array[ index * this.data.stride + this.offset ];
  17853. if ( this.normalized ) x = denormalize( x, this.array );
  17854. return x;
  17855. }
  17856. getY( index ) {
  17857. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17858. if ( this.normalized ) y = denormalize( y, this.array );
  17859. return y;
  17860. }
  17861. getZ( index ) {
  17862. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17863. if ( this.normalized ) z = denormalize( z, this.array );
  17864. return z;
  17865. }
  17866. getW( index ) {
  17867. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17868. if ( this.normalized ) w = denormalize( w, this.array );
  17869. return w;
  17870. }
  17871. setXY( index, x, y ) {
  17872. index = index * this.data.stride + this.offset;
  17873. if ( this.normalized ) {
  17874. x = normalize( x, this.array );
  17875. y = normalize( y, this.array );
  17876. }
  17877. this.data.array[ index + 0 ] = x;
  17878. this.data.array[ index + 1 ] = y;
  17879. return this;
  17880. }
  17881. setXYZ( index, x, y, z ) {
  17882. index = index * this.data.stride + this.offset;
  17883. if ( this.normalized ) {
  17884. x = normalize( x, this.array );
  17885. y = normalize( y, this.array );
  17886. z = normalize( z, this.array );
  17887. }
  17888. this.data.array[ index + 0 ] = x;
  17889. this.data.array[ index + 1 ] = y;
  17890. this.data.array[ index + 2 ] = z;
  17891. return this;
  17892. }
  17893. setXYZW( index, x, y, z, w ) {
  17894. index = index * this.data.stride + this.offset;
  17895. if ( this.normalized ) {
  17896. x = normalize( x, this.array );
  17897. y = normalize( y, this.array );
  17898. z = normalize( z, this.array );
  17899. w = normalize( w, this.array );
  17900. }
  17901. this.data.array[ index + 0 ] = x;
  17902. this.data.array[ index + 1 ] = y;
  17903. this.data.array[ index + 2 ] = z;
  17904. this.data.array[ index + 3 ] = w;
  17905. return this;
  17906. }
  17907. clone( data ) {
  17908. if ( data === undefined ) {
  17909. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17910. const array = [];
  17911. for ( let i = 0; i < this.count; i ++ ) {
  17912. const index = i * this.data.stride + this.offset;
  17913. for ( let j = 0; j < this.itemSize; j ++ ) {
  17914. array.push( this.data.array[ index + j ] );
  17915. }
  17916. }
  17917. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17918. } else {
  17919. if ( data.interleavedBuffers === undefined ) {
  17920. data.interleavedBuffers = {};
  17921. }
  17922. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17923. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17924. }
  17925. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17926. }
  17927. }
  17928. toJSON( data ) {
  17929. if ( data === undefined ) {
  17930. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17931. const array = [];
  17932. for ( let i = 0; i < this.count; i ++ ) {
  17933. const index = i * this.data.stride + this.offset;
  17934. for ( let j = 0; j < this.itemSize; j ++ ) {
  17935. array.push( this.data.array[ index + j ] );
  17936. }
  17937. }
  17938. // de-interleave data and save it as an ordinary buffer attribute for now
  17939. return {
  17940. itemSize: this.itemSize,
  17941. type: this.array.constructor.name,
  17942. array: array,
  17943. normalized: this.normalized
  17944. };
  17945. } else {
  17946. // save as true interleaved attribute
  17947. if ( data.interleavedBuffers === undefined ) {
  17948. data.interleavedBuffers = {};
  17949. }
  17950. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17951. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17952. }
  17953. return {
  17954. isInterleavedBufferAttribute: true,
  17955. itemSize: this.itemSize,
  17956. data: this.data.uuid,
  17957. offset: this.offset,
  17958. normalized: this.normalized
  17959. };
  17960. }
  17961. }
  17962. }
  17963. class SpriteMaterial extends Material {
  17964. constructor( parameters ) {
  17965. super();
  17966. this.isSpriteMaterial = true;
  17967. this.type = 'SpriteMaterial';
  17968. this.color = new Color( 0xffffff );
  17969. this.map = null;
  17970. this.alphaMap = null;
  17971. this.rotation = 0;
  17972. this.sizeAttenuation = true;
  17973. this.transparent = true;
  17974. this.fog = true;
  17975. this.setValues( parameters );
  17976. }
  17977. copy( source ) {
  17978. super.copy( source );
  17979. this.color.copy( source.color );
  17980. this.map = source.map;
  17981. this.alphaMap = source.alphaMap;
  17982. this.rotation = source.rotation;
  17983. this.sizeAttenuation = source.sizeAttenuation;
  17984. this.fog = source.fog;
  17985. return this;
  17986. }
  17987. }
  17988. let _geometry;
  17989. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17990. const _worldScale = /*@__PURE__*/ new Vector3();
  17991. const _mvPosition = /*@__PURE__*/ new Vector3();
  17992. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17993. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17994. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17995. const _vA = /*@__PURE__*/ new Vector3();
  17996. const _vB = /*@__PURE__*/ new Vector3();
  17997. const _vC = /*@__PURE__*/ new Vector3();
  17998. const _uvA = /*@__PURE__*/ new Vector2();
  17999. const _uvB = /*@__PURE__*/ new Vector2();
  18000. const _uvC = /*@__PURE__*/ new Vector2();
  18001. class Sprite extends Object3D {
  18002. constructor( material ) {
  18003. super();
  18004. this.isSprite = true;
  18005. this.type = 'Sprite';
  18006. if ( _geometry === undefined ) {
  18007. _geometry = new BufferGeometry();
  18008. const float32Array = new Float32Array( [
  18009. - 0.5, - 0.5, 0, 0, 0,
  18010. 0.5, - 0.5, 0, 1, 0,
  18011. 0.5, 0.5, 0, 1, 1,
  18012. - 0.5, 0.5, 0, 0, 1
  18013. ] );
  18014. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18015. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18016. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18017. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18018. }
  18019. this.geometry = _geometry;
  18020. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18021. this.center = new Vector2( 0.5, 0.5 );
  18022. }
  18023. raycast( raycaster, intersects ) {
  18024. if ( raycaster.camera === null ) {
  18025. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18026. }
  18027. _worldScale.setFromMatrixScale( this.matrixWorld );
  18028. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18029. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18030. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18031. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18032. _worldScale.multiplyScalar( - _mvPosition.z );
  18033. }
  18034. const rotation = this.material.rotation;
  18035. let sin, cos;
  18036. if ( rotation !== 0 ) {
  18037. cos = Math.cos( rotation );
  18038. sin = Math.sin( rotation );
  18039. }
  18040. const center = this.center;
  18041. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18042. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18043. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18044. _uvA.set( 0, 0 );
  18045. _uvB.set( 1, 0 );
  18046. _uvC.set( 1, 1 );
  18047. // check first triangle
  18048. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18049. if ( intersect === null ) {
  18050. // check second triangle
  18051. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18052. _uvB.set( 0, 1 );
  18053. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18054. if ( intersect === null ) {
  18055. return;
  18056. }
  18057. }
  18058. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18059. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18060. intersects.push( {
  18061. distance: distance,
  18062. point: _intersectPoint.clone(),
  18063. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18064. face: null,
  18065. object: this
  18066. } );
  18067. }
  18068. copy( source, recursive ) {
  18069. super.copy( source, recursive );
  18070. if ( source.center !== undefined ) this.center.copy( source.center );
  18071. this.material = source.material;
  18072. return this;
  18073. }
  18074. }
  18075. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18076. // compute position in camera space
  18077. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18078. // to check if rotation is not zero
  18079. if ( sin !== undefined ) {
  18080. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18081. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18082. } else {
  18083. _rotatedPosition.copy( _alignedPosition );
  18084. }
  18085. vertexPosition.copy( mvPosition );
  18086. vertexPosition.x += _rotatedPosition.x;
  18087. vertexPosition.y += _rotatedPosition.y;
  18088. // transform to world space
  18089. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18090. }
  18091. const _v1$2 = /*@__PURE__*/ new Vector3();
  18092. const _v2$1 = /*@__PURE__*/ new Vector3();
  18093. class LOD extends Object3D {
  18094. constructor() {
  18095. super();
  18096. this._currentLevel = 0;
  18097. this.type = 'LOD';
  18098. Object.defineProperties( this, {
  18099. levels: {
  18100. enumerable: true,
  18101. value: []
  18102. },
  18103. isLOD: {
  18104. value: true,
  18105. }
  18106. } );
  18107. this.autoUpdate = true;
  18108. }
  18109. copy( source ) {
  18110. super.copy( source, false );
  18111. const levels = source.levels;
  18112. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18113. const level = levels[ i ];
  18114. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18115. }
  18116. this.autoUpdate = source.autoUpdate;
  18117. return this;
  18118. }
  18119. addLevel( object, distance = 0, hysteresis = 0 ) {
  18120. distance = Math.abs( distance );
  18121. const levels = this.levels;
  18122. let l;
  18123. for ( l = 0; l < levels.length; l ++ ) {
  18124. if ( distance < levels[ l ].distance ) {
  18125. break;
  18126. }
  18127. }
  18128. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18129. this.add( object );
  18130. return this;
  18131. }
  18132. getCurrentLevel() {
  18133. return this._currentLevel;
  18134. }
  18135. getObjectForDistance( distance ) {
  18136. const levels = this.levels;
  18137. if ( levels.length > 0 ) {
  18138. let i, l;
  18139. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18140. let levelDistance = levels[ i ].distance;
  18141. if ( levels[ i ].object.visible ) {
  18142. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18143. }
  18144. if ( distance < levelDistance ) {
  18145. break;
  18146. }
  18147. }
  18148. return levels[ i - 1 ].object;
  18149. }
  18150. return null;
  18151. }
  18152. raycast( raycaster, intersects ) {
  18153. const levels = this.levels;
  18154. if ( levels.length > 0 ) {
  18155. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18156. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18157. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18158. }
  18159. }
  18160. update( camera ) {
  18161. const levels = this.levels;
  18162. if ( levels.length > 1 ) {
  18163. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18164. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18165. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18166. levels[ 0 ].object.visible = true;
  18167. let i, l;
  18168. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18169. let levelDistance = levels[ i ].distance;
  18170. if ( levels[ i ].object.visible ) {
  18171. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18172. }
  18173. if ( distance >= levelDistance ) {
  18174. levels[ i - 1 ].object.visible = false;
  18175. levels[ i ].object.visible = true;
  18176. } else {
  18177. break;
  18178. }
  18179. }
  18180. this._currentLevel = i - 1;
  18181. for ( ; i < l; i ++ ) {
  18182. levels[ i ].object.visible = false;
  18183. }
  18184. }
  18185. }
  18186. toJSON( meta ) {
  18187. const data = super.toJSON( meta );
  18188. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18189. data.object.levels = [];
  18190. const levels = this.levels;
  18191. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18192. const level = levels[ i ];
  18193. data.object.levels.push( {
  18194. object: level.object.uuid,
  18195. distance: level.distance,
  18196. hysteresis: level.hysteresis
  18197. } );
  18198. }
  18199. return data;
  18200. }
  18201. }
  18202. const _basePosition = /*@__PURE__*/ new Vector3();
  18203. const _skinIndex = /*@__PURE__*/ new Vector4();
  18204. const _skinWeight = /*@__PURE__*/ new Vector4();
  18205. const _vector3 = /*@__PURE__*/ new Vector3();
  18206. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18207. class SkinnedMesh extends Mesh {
  18208. constructor( geometry, material ) {
  18209. super( geometry, material );
  18210. this.isSkinnedMesh = true;
  18211. this.type = 'SkinnedMesh';
  18212. this.bindMode = 'attached';
  18213. this.bindMatrix = new Matrix4();
  18214. this.bindMatrixInverse = new Matrix4();
  18215. }
  18216. copy( source, recursive ) {
  18217. super.copy( source, recursive );
  18218. this.bindMode = source.bindMode;
  18219. this.bindMatrix.copy( source.bindMatrix );
  18220. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18221. this.skeleton = source.skeleton;
  18222. return this;
  18223. }
  18224. bind( skeleton, bindMatrix ) {
  18225. this.skeleton = skeleton;
  18226. if ( bindMatrix === undefined ) {
  18227. this.updateMatrixWorld( true );
  18228. this.skeleton.calculateInverses();
  18229. bindMatrix = this.matrixWorld;
  18230. }
  18231. this.bindMatrix.copy( bindMatrix );
  18232. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18233. }
  18234. pose() {
  18235. this.skeleton.pose();
  18236. }
  18237. normalizeSkinWeights() {
  18238. const vector = new Vector4();
  18239. const skinWeight = this.geometry.attributes.skinWeight;
  18240. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18241. vector.fromBufferAttribute( skinWeight, i );
  18242. const scale = 1.0 / vector.manhattanLength();
  18243. if ( scale !== Infinity ) {
  18244. vector.multiplyScalar( scale );
  18245. } else {
  18246. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18247. }
  18248. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18249. }
  18250. }
  18251. updateMatrixWorld( force ) {
  18252. super.updateMatrixWorld( force );
  18253. if ( this.bindMode === 'attached' ) {
  18254. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18255. } else if ( this.bindMode === 'detached' ) {
  18256. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18257. } else {
  18258. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18259. }
  18260. }
  18261. applyBoneTransform( index, vector ) {
  18262. const skeleton = this.skeleton;
  18263. const geometry = this.geometry;
  18264. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18265. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18266. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  18267. vector.set( 0, 0, 0 );
  18268. for ( let i = 0; i < 4; i ++ ) {
  18269. const weight = _skinWeight.getComponent( i );
  18270. if ( weight !== 0 ) {
  18271. const boneIndex = _skinIndex.getComponent( i );
  18272. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18273. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18274. }
  18275. }
  18276. return vector.applyMatrix4( this.bindMatrixInverse );
  18277. }
  18278. // @deprecated
  18279. boneTransform( index, vector ) {
  18280. console.warn( 'THREE.SkinnedMesh: .boneTransform() was renamed to .applyBoneTransform() in r151.' );
  18281. return this.applyBoneTransform( index, vector );
  18282. }
  18283. }
  18284. class Bone extends Object3D {
  18285. constructor() {
  18286. super();
  18287. this.isBone = true;
  18288. this.type = 'Bone';
  18289. }
  18290. }
  18291. class DataTexture extends Texture {
  18292. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  18293. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18294. this.isDataTexture = true;
  18295. this.image = { data: data, width: width, height: height };
  18296. this.generateMipmaps = false;
  18297. this.flipY = false;
  18298. this.unpackAlignment = 1;
  18299. }
  18300. }
  18301. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18302. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18303. class Skeleton {
  18304. constructor( bones = [], boneInverses = [] ) {
  18305. this.uuid = generateUUID();
  18306. this.bones = bones.slice( 0 );
  18307. this.boneInverses = boneInverses;
  18308. this.boneMatrices = null;
  18309. this.boneTexture = null;
  18310. this.boneTextureSize = 0;
  18311. this.frame = - 1;
  18312. this.init();
  18313. }
  18314. init() {
  18315. const bones = this.bones;
  18316. const boneInverses = this.boneInverses;
  18317. this.boneMatrices = new Float32Array( bones.length * 16 );
  18318. // calculate inverse bone matrices if necessary
  18319. if ( boneInverses.length === 0 ) {
  18320. this.calculateInverses();
  18321. } else {
  18322. // handle special case
  18323. if ( bones.length !== boneInverses.length ) {
  18324. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18325. this.boneInverses = [];
  18326. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18327. this.boneInverses.push( new Matrix4() );
  18328. }
  18329. }
  18330. }
  18331. }
  18332. calculateInverses() {
  18333. this.boneInverses.length = 0;
  18334. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18335. const inverse = new Matrix4();
  18336. if ( this.bones[ i ] ) {
  18337. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18338. }
  18339. this.boneInverses.push( inverse );
  18340. }
  18341. }
  18342. pose() {
  18343. // recover the bind-time world matrices
  18344. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18345. const bone = this.bones[ i ];
  18346. if ( bone ) {
  18347. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18348. }
  18349. }
  18350. // compute the local matrices, positions, rotations and scales
  18351. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18352. const bone = this.bones[ i ];
  18353. if ( bone ) {
  18354. if ( bone.parent && bone.parent.isBone ) {
  18355. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18356. bone.matrix.multiply( bone.matrixWorld );
  18357. } else {
  18358. bone.matrix.copy( bone.matrixWorld );
  18359. }
  18360. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18361. }
  18362. }
  18363. }
  18364. update() {
  18365. const bones = this.bones;
  18366. const boneInverses = this.boneInverses;
  18367. const boneMatrices = this.boneMatrices;
  18368. const boneTexture = this.boneTexture;
  18369. // flatten bone matrices to array
  18370. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18371. // compute the offset between the current and the original transform
  18372. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18373. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18374. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18375. }
  18376. if ( boneTexture !== null ) {
  18377. boneTexture.needsUpdate = true;
  18378. }
  18379. }
  18380. clone() {
  18381. return new Skeleton( this.bones, this.boneInverses );
  18382. }
  18383. computeBoneTexture() {
  18384. // layout (1 matrix = 4 pixels)
  18385. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18386. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18387. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18388. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18389. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18390. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18391. size = ceilPowerOfTwo( size );
  18392. size = Math.max( size, 4 );
  18393. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18394. boneMatrices.set( this.boneMatrices ); // copy current values
  18395. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18396. boneTexture.needsUpdate = true;
  18397. this.boneMatrices = boneMatrices;
  18398. this.boneTexture = boneTexture;
  18399. this.boneTextureSize = size;
  18400. return this;
  18401. }
  18402. getBoneByName( name ) {
  18403. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18404. const bone = this.bones[ i ];
  18405. if ( bone.name === name ) {
  18406. return bone;
  18407. }
  18408. }
  18409. return undefined;
  18410. }
  18411. dispose( ) {
  18412. if ( this.boneTexture !== null ) {
  18413. this.boneTexture.dispose();
  18414. this.boneTexture = null;
  18415. }
  18416. }
  18417. fromJSON( json, bones ) {
  18418. this.uuid = json.uuid;
  18419. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18420. const uuid = json.bones[ i ];
  18421. let bone = bones[ uuid ];
  18422. if ( bone === undefined ) {
  18423. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18424. bone = new Bone();
  18425. }
  18426. this.bones.push( bone );
  18427. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18428. }
  18429. this.init();
  18430. return this;
  18431. }
  18432. toJSON() {
  18433. const data = {
  18434. metadata: {
  18435. version: 4.5,
  18436. type: 'Skeleton',
  18437. generator: 'Skeleton.toJSON'
  18438. },
  18439. bones: [],
  18440. boneInverses: []
  18441. };
  18442. data.uuid = this.uuid;
  18443. const bones = this.bones;
  18444. const boneInverses = this.boneInverses;
  18445. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18446. const bone = bones[ i ];
  18447. data.bones.push( bone.uuid );
  18448. const boneInverse = boneInverses[ i ];
  18449. data.boneInverses.push( boneInverse.toArray() );
  18450. }
  18451. return data;
  18452. }
  18453. }
  18454. class InstancedBufferAttribute extends BufferAttribute {
  18455. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18456. super( array, itemSize, normalized );
  18457. this.isInstancedBufferAttribute = true;
  18458. this.meshPerAttribute = meshPerAttribute;
  18459. }
  18460. copy( source ) {
  18461. super.copy( source );
  18462. this.meshPerAttribute = source.meshPerAttribute;
  18463. return this;
  18464. }
  18465. toJSON() {
  18466. const data = super.toJSON();
  18467. data.meshPerAttribute = this.meshPerAttribute;
  18468. data.isInstancedBufferAttribute = true;
  18469. return data;
  18470. }
  18471. }
  18472. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18473. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18474. const _instanceIntersects = [];
  18475. const _box3 = /*@__PURE__*/ new Box3();
  18476. const _identity = /*@__PURE__*/ new Matrix4();
  18477. const _mesh = /*@__PURE__*/ new Mesh();
  18478. const _sphere$2 = /*@__PURE__*/ new Sphere();
  18479. class InstancedMesh extends Mesh {
  18480. constructor( geometry, material, count ) {
  18481. super( geometry, material );
  18482. this.isInstancedMesh = true;
  18483. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18484. this.instanceColor = null;
  18485. this.count = count;
  18486. this.boundingBox = null;
  18487. this.boundingSphere = null;
  18488. for ( let i = 0; i < count; i ++ ) {
  18489. this.setMatrixAt( i, _identity );
  18490. }
  18491. }
  18492. computeBoundingBox() {
  18493. const geometry = this.geometry;
  18494. const count = this.count;
  18495. if ( this.boundingBox === null ) {
  18496. this.boundingBox = new Box3();
  18497. }
  18498. if ( geometry.boundingBox === null ) {
  18499. geometry.computeBoundingBox();
  18500. }
  18501. this.boundingBox.makeEmpty();
  18502. for ( let i = 0; i < count; i ++ ) {
  18503. this.getMatrixAt( i, _instanceLocalMatrix );
  18504. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18505. this.boundingBox.union( _box3 );
  18506. }
  18507. }
  18508. computeBoundingSphere() {
  18509. const geometry = this.geometry;
  18510. const count = this.count;
  18511. if ( this.boundingSphere === null ) {
  18512. this.boundingSphere = new Sphere();
  18513. }
  18514. if ( geometry.boundingSphere === null ) {
  18515. geometry.computeBoundingSphere();
  18516. }
  18517. this.boundingSphere.makeEmpty();
  18518. for ( let i = 0; i < count; i ++ ) {
  18519. this.getMatrixAt( i, _instanceLocalMatrix );
  18520. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18521. this.boundingSphere.union( _sphere$2 );
  18522. }
  18523. }
  18524. copy( source, recursive ) {
  18525. super.copy( source, recursive );
  18526. this.instanceMatrix.copy( source.instanceMatrix );
  18527. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18528. this.count = source.count;
  18529. return this;
  18530. }
  18531. getColorAt( index, color ) {
  18532. color.fromArray( this.instanceColor.array, index * 3 );
  18533. }
  18534. getMatrixAt( index, matrix ) {
  18535. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18536. }
  18537. raycast( raycaster, intersects ) {
  18538. const matrixWorld = this.matrixWorld;
  18539. const raycastTimes = this.count;
  18540. _mesh.geometry = this.geometry;
  18541. _mesh.material = this.material;
  18542. if ( _mesh.material === undefined ) return;
  18543. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18544. // calculate the world matrix for each instance
  18545. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18546. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18547. // the mesh represents this single instance
  18548. _mesh.matrixWorld = _instanceWorldMatrix;
  18549. _mesh.raycast( raycaster, _instanceIntersects );
  18550. // process the result of raycast
  18551. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18552. const intersect = _instanceIntersects[ i ];
  18553. intersect.instanceId = instanceId;
  18554. intersect.object = this;
  18555. intersects.push( intersect );
  18556. }
  18557. _instanceIntersects.length = 0;
  18558. }
  18559. }
  18560. setColorAt( index, color ) {
  18561. if ( this.instanceColor === null ) {
  18562. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18563. }
  18564. color.toArray( this.instanceColor.array, index * 3 );
  18565. }
  18566. setMatrixAt( index, matrix ) {
  18567. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18568. }
  18569. updateMorphTargets() {
  18570. }
  18571. dispose() {
  18572. this.dispatchEvent( { type: 'dispose' } );
  18573. }
  18574. }
  18575. class LineBasicMaterial extends Material {
  18576. constructor( parameters ) {
  18577. super();
  18578. this.isLineBasicMaterial = true;
  18579. this.type = 'LineBasicMaterial';
  18580. this.color = new Color( 0xffffff );
  18581. this.linewidth = 1;
  18582. this.linecap = 'round';
  18583. this.linejoin = 'round';
  18584. this.fog = true;
  18585. this.setValues( parameters );
  18586. }
  18587. copy( source ) {
  18588. super.copy( source );
  18589. this.color.copy( source.color );
  18590. this.linewidth = source.linewidth;
  18591. this.linecap = source.linecap;
  18592. this.linejoin = source.linejoin;
  18593. this.fog = source.fog;
  18594. return this;
  18595. }
  18596. }
  18597. const _start$1 = /*@__PURE__*/ new Vector3();
  18598. const _end$1 = /*@__PURE__*/ new Vector3();
  18599. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18600. const _ray$1 = /*@__PURE__*/ new Ray();
  18601. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18602. class Line extends Object3D {
  18603. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18604. super();
  18605. this.isLine = true;
  18606. this.type = 'Line';
  18607. this.geometry = geometry;
  18608. this.material = material;
  18609. this.updateMorphTargets();
  18610. }
  18611. copy( source, recursive ) {
  18612. super.copy( source, recursive );
  18613. this.material = source.material;
  18614. this.geometry = source.geometry;
  18615. return this;
  18616. }
  18617. computeLineDistances() {
  18618. const geometry = this.geometry;
  18619. // we assume non-indexed geometry
  18620. if ( geometry.index === null ) {
  18621. const positionAttribute = geometry.attributes.position;
  18622. const lineDistances = [ 0 ];
  18623. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18624. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18625. _end$1.fromBufferAttribute( positionAttribute, i );
  18626. lineDistances[ i ] = lineDistances[ i - 1 ];
  18627. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18628. }
  18629. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18630. } else {
  18631. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18632. }
  18633. return this;
  18634. }
  18635. raycast( raycaster, intersects ) {
  18636. const geometry = this.geometry;
  18637. const matrixWorld = this.matrixWorld;
  18638. const threshold = raycaster.params.Line.threshold;
  18639. const drawRange = geometry.drawRange;
  18640. // Checking boundingSphere distance to ray
  18641. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18642. _sphere$1.copy( geometry.boundingSphere );
  18643. _sphere$1.applyMatrix4( matrixWorld );
  18644. _sphere$1.radius += threshold;
  18645. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18646. //
  18647. _inverseMatrix$1.copy( matrixWorld ).invert();
  18648. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18649. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18650. const localThresholdSq = localThreshold * localThreshold;
  18651. const vStart = new Vector3();
  18652. const vEnd = new Vector3();
  18653. const interSegment = new Vector3();
  18654. const interRay = new Vector3();
  18655. const step = this.isLineSegments ? 2 : 1;
  18656. const index = geometry.index;
  18657. const attributes = geometry.attributes;
  18658. const positionAttribute = attributes.position;
  18659. if ( index !== null ) {
  18660. const start = Math.max( 0, drawRange.start );
  18661. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18662. for ( let i = start, l = end - 1; i < l; i += step ) {
  18663. const a = index.getX( i );
  18664. const b = index.getX( i + 1 );
  18665. vStart.fromBufferAttribute( positionAttribute, a );
  18666. vEnd.fromBufferAttribute( positionAttribute, b );
  18667. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18668. if ( distSq > localThresholdSq ) continue;
  18669. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18670. const distance = raycaster.ray.origin.distanceTo( interRay );
  18671. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18672. intersects.push( {
  18673. distance: distance,
  18674. // What do we want? intersection point on the ray or on the segment??
  18675. // point: raycaster.ray.at( distance ),
  18676. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18677. index: i,
  18678. face: null,
  18679. faceIndex: null,
  18680. object: this
  18681. } );
  18682. }
  18683. } else {
  18684. const start = Math.max( 0, drawRange.start );
  18685. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18686. for ( let i = start, l = end - 1; i < l; i += step ) {
  18687. vStart.fromBufferAttribute( positionAttribute, i );
  18688. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18689. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18690. if ( distSq > localThresholdSq ) continue;
  18691. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18692. const distance = raycaster.ray.origin.distanceTo( interRay );
  18693. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18694. intersects.push( {
  18695. distance: distance,
  18696. // What do we want? intersection point on the ray or on the segment??
  18697. // point: raycaster.ray.at( distance ),
  18698. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18699. index: i,
  18700. face: null,
  18701. faceIndex: null,
  18702. object: this
  18703. } );
  18704. }
  18705. }
  18706. }
  18707. updateMorphTargets() {
  18708. const geometry = this.geometry;
  18709. const morphAttributes = geometry.morphAttributes;
  18710. const keys = Object.keys( morphAttributes );
  18711. if ( keys.length > 0 ) {
  18712. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18713. if ( morphAttribute !== undefined ) {
  18714. this.morphTargetInfluences = [];
  18715. this.morphTargetDictionary = {};
  18716. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18717. const name = morphAttribute[ m ].name || String( m );
  18718. this.morphTargetInfluences.push( 0 );
  18719. this.morphTargetDictionary[ name ] = m;
  18720. }
  18721. }
  18722. }
  18723. }
  18724. }
  18725. const _start = /*@__PURE__*/ new Vector3();
  18726. const _end = /*@__PURE__*/ new Vector3();
  18727. class LineSegments extends Line {
  18728. constructor( geometry, material ) {
  18729. super( geometry, material );
  18730. this.isLineSegments = true;
  18731. this.type = 'LineSegments';
  18732. }
  18733. computeLineDistances() {
  18734. const geometry = this.geometry;
  18735. // we assume non-indexed geometry
  18736. if ( geometry.index === null ) {
  18737. const positionAttribute = geometry.attributes.position;
  18738. const lineDistances = [];
  18739. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18740. _start.fromBufferAttribute( positionAttribute, i );
  18741. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18742. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18743. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18744. }
  18745. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18746. } else {
  18747. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18748. }
  18749. return this;
  18750. }
  18751. }
  18752. class LineLoop extends Line {
  18753. constructor( geometry, material ) {
  18754. super( geometry, material );
  18755. this.isLineLoop = true;
  18756. this.type = 'LineLoop';
  18757. }
  18758. }
  18759. class PointsMaterial extends Material {
  18760. constructor( parameters ) {
  18761. super();
  18762. this.isPointsMaterial = true;
  18763. this.type = 'PointsMaterial';
  18764. this.color = new Color( 0xffffff );
  18765. this.map = null;
  18766. this.alphaMap = null;
  18767. this.size = 1;
  18768. this.sizeAttenuation = true;
  18769. this.fog = true;
  18770. this.setValues( parameters );
  18771. }
  18772. copy( source ) {
  18773. super.copy( source );
  18774. this.color.copy( source.color );
  18775. this.map = source.map;
  18776. this.alphaMap = source.alphaMap;
  18777. this.size = source.size;
  18778. this.sizeAttenuation = source.sizeAttenuation;
  18779. this.fog = source.fog;
  18780. return this;
  18781. }
  18782. }
  18783. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18784. const _ray = /*@__PURE__*/ new Ray();
  18785. const _sphere = /*@__PURE__*/ new Sphere();
  18786. const _position$2 = /*@__PURE__*/ new Vector3();
  18787. class Points extends Object3D {
  18788. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18789. super();
  18790. this.isPoints = true;
  18791. this.type = 'Points';
  18792. this.geometry = geometry;
  18793. this.material = material;
  18794. this.updateMorphTargets();
  18795. }
  18796. copy( source, recursive ) {
  18797. super.copy( source, recursive );
  18798. this.material = source.material;
  18799. this.geometry = source.geometry;
  18800. return this;
  18801. }
  18802. raycast( raycaster, intersects ) {
  18803. const geometry = this.geometry;
  18804. const matrixWorld = this.matrixWorld;
  18805. const threshold = raycaster.params.Points.threshold;
  18806. const drawRange = geometry.drawRange;
  18807. // Checking boundingSphere distance to ray
  18808. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18809. _sphere.copy( geometry.boundingSphere );
  18810. _sphere.applyMatrix4( matrixWorld );
  18811. _sphere.radius += threshold;
  18812. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18813. //
  18814. _inverseMatrix.copy( matrixWorld ).invert();
  18815. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18816. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18817. const localThresholdSq = localThreshold * localThreshold;
  18818. const index = geometry.index;
  18819. const attributes = geometry.attributes;
  18820. const positionAttribute = attributes.position;
  18821. if ( index !== null ) {
  18822. const start = Math.max( 0, drawRange.start );
  18823. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18824. for ( let i = start, il = end; i < il; i ++ ) {
  18825. const a = index.getX( i );
  18826. _position$2.fromBufferAttribute( positionAttribute, a );
  18827. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18828. }
  18829. } else {
  18830. const start = Math.max( 0, drawRange.start );
  18831. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18832. for ( let i = start, l = end; i < l; i ++ ) {
  18833. _position$2.fromBufferAttribute( positionAttribute, i );
  18834. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18835. }
  18836. }
  18837. }
  18838. updateMorphTargets() {
  18839. const geometry = this.geometry;
  18840. const morphAttributes = geometry.morphAttributes;
  18841. const keys = Object.keys( morphAttributes );
  18842. if ( keys.length > 0 ) {
  18843. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18844. if ( morphAttribute !== undefined ) {
  18845. this.morphTargetInfluences = [];
  18846. this.morphTargetDictionary = {};
  18847. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18848. const name = morphAttribute[ m ].name || String( m );
  18849. this.morphTargetInfluences.push( 0 );
  18850. this.morphTargetDictionary[ name ] = m;
  18851. }
  18852. }
  18853. }
  18854. }
  18855. }
  18856. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18857. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18858. if ( rayPointDistanceSq < localThresholdSq ) {
  18859. const intersectPoint = new Vector3();
  18860. _ray.closestPointToPoint( point, intersectPoint );
  18861. intersectPoint.applyMatrix4( matrixWorld );
  18862. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18863. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18864. intersects.push( {
  18865. distance: distance,
  18866. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18867. point: intersectPoint,
  18868. index: index,
  18869. face: null,
  18870. object: object
  18871. } );
  18872. }
  18873. }
  18874. class VideoTexture extends Texture {
  18875. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18876. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18877. this.isVideoTexture = true;
  18878. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18879. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18880. this.generateMipmaps = false;
  18881. const scope = this;
  18882. function updateVideo() {
  18883. scope.needsUpdate = true;
  18884. video.requestVideoFrameCallback( updateVideo );
  18885. }
  18886. if ( 'requestVideoFrameCallback' in video ) {
  18887. video.requestVideoFrameCallback( updateVideo );
  18888. }
  18889. }
  18890. clone() {
  18891. return new this.constructor( this.image ).copy( this );
  18892. }
  18893. update() {
  18894. const video = this.image;
  18895. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18896. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18897. this.needsUpdate = true;
  18898. }
  18899. }
  18900. }
  18901. class FramebufferTexture extends Texture {
  18902. constructor( width, height, format ) {
  18903. super( { width, height } );
  18904. this.isFramebufferTexture = true;
  18905. this.format = format;
  18906. this.magFilter = NearestFilter;
  18907. this.minFilter = NearestFilter;
  18908. this.generateMipmaps = false;
  18909. this.needsUpdate = true;
  18910. }
  18911. }
  18912. class CompressedTexture extends Texture {
  18913. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18914. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18915. this.isCompressedTexture = true;
  18916. this.image = { width: width, height: height };
  18917. this.mipmaps = mipmaps;
  18918. // no flipping for cube textures
  18919. // (also flipping doesn't work for compressed textures )
  18920. this.flipY = false;
  18921. // can't generate mipmaps for compressed textures
  18922. // mips must be embedded in DDS files
  18923. this.generateMipmaps = false;
  18924. }
  18925. }
  18926. class CompressedArrayTexture extends CompressedTexture {
  18927. constructor( mipmaps, width, height, depth, format, type ) {
  18928. super( mipmaps, width, height, format, type );
  18929. this.isCompressedArrayTexture = true;
  18930. this.image.depth = depth;
  18931. this.wrapR = ClampToEdgeWrapping;
  18932. }
  18933. }
  18934. class CanvasTexture extends Texture {
  18935. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18936. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18937. this.isCanvasTexture = true;
  18938. this.needsUpdate = true;
  18939. }
  18940. }
  18941. /**
  18942. * Extensible curve object.
  18943. *
  18944. * Some common of curve methods:
  18945. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18946. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18947. * .getPoints(), .getSpacedPoints()
  18948. * .getLength()
  18949. * .updateArcLengths()
  18950. *
  18951. * This following curves inherit from THREE.Curve:
  18952. *
  18953. * -- 2D curves --
  18954. * THREE.ArcCurve
  18955. * THREE.CubicBezierCurve
  18956. * THREE.EllipseCurve
  18957. * THREE.LineCurve
  18958. * THREE.QuadraticBezierCurve
  18959. * THREE.SplineCurve
  18960. *
  18961. * -- 3D curves --
  18962. * THREE.CatmullRomCurve3
  18963. * THREE.CubicBezierCurve3
  18964. * THREE.LineCurve3
  18965. * THREE.QuadraticBezierCurve3
  18966. *
  18967. * A series of curves can be represented as a THREE.CurvePath.
  18968. *
  18969. **/
  18970. class Curve {
  18971. constructor() {
  18972. this.type = 'Curve';
  18973. this.arcLengthDivisions = 200;
  18974. }
  18975. // Virtual base class method to overwrite and implement in subclasses
  18976. // - t [0 .. 1]
  18977. getPoint( /* t, optionalTarget */ ) {
  18978. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18979. return null;
  18980. }
  18981. // Get point at relative position in curve according to arc length
  18982. // - u [0 .. 1]
  18983. getPointAt( u, optionalTarget ) {
  18984. const t = this.getUtoTmapping( u );
  18985. return this.getPoint( t, optionalTarget );
  18986. }
  18987. // Get sequence of points using getPoint( t )
  18988. getPoints( divisions = 5 ) {
  18989. const points = [];
  18990. for ( let d = 0; d <= divisions; d ++ ) {
  18991. points.push( this.getPoint( d / divisions ) );
  18992. }
  18993. return points;
  18994. }
  18995. // Get sequence of points using getPointAt( u )
  18996. getSpacedPoints( divisions = 5 ) {
  18997. const points = [];
  18998. for ( let d = 0; d <= divisions; d ++ ) {
  18999. points.push( this.getPointAt( d / divisions ) );
  19000. }
  19001. return points;
  19002. }
  19003. // Get total curve arc length
  19004. getLength() {
  19005. const lengths = this.getLengths();
  19006. return lengths[ lengths.length - 1 ];
  19007. }
  19008. // Get list of cumulative segment lengths
  19009. getLengths( divisions = this.arcLengthDivisions ) {
  19010. if ( this.cacheArcLengths &&
  19011. ( this.cacheArcLengths.length === divisions + 1 ) &&
  19012. ! this.needsUpdate ) {
  19013. return this.cacheArcLengths;
  19014. }
  19015. this.needsUpdate = false;
  19016. const cache = [];
  19017. let current, last = this.getPoint( 0 );
  19018. let sum = 0;
  19019. cache.push( 0 );
  19020. for ( let p = 1; p <= divisions; p ++ ) {
  19021. current = this.getPoint( p / divisions );
  19022. sum += current.distanceTo( last );
  19023. cache.push( sum );
  19024. last = current;
  19025. }
  19026. this.cacheArcLengths = cache;
  19027. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  19028. }
  19029. updateArcLengths() {
  19030. this.needsUpdate = true;
  19031. this.getLengths();
  19032. }
  19033. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19034. getUtoTmapping( u, distance ) {
  19035. const arcLengths = this.getLengths();
  19036. let i = 0;
  19037. const il = arcLengths.length;
  19038. let targetArcLength; // The targeted u distance value to get
  19039. if ( distance ) {
  19040. targetArcLength = distance;
  19041. } else {
  19042. targetArcLength = u * arcLengths[ il - 1 ];
  19043. }
  19044. // binary search for the index with largest value smaller than target u distance
  19045. let low = 0, high = il - 1, comparison;
  19046. while ( low <= high ) {
  19047. 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
  19048. comparison = arcLengths[ i ] - targetArcLength;
  19049. if ( comparison < 0 ) {
  19050. low = i + 1;
  19051. } else if ( comparison > 0 ) {
  19052. high = i - 1;
  19053. } else {
  19054. high = i;
  19055. break;
  19056. // DONE
  19057. }
  19058. }
  19059. i = high;
  19060. if ( arcLengths[ i ] === targetArcLength ) {
  19061. return i / ( il - 1 );
  19062. }
  19063. // we could get finer grain at lengths, or use simple interpolation between two points
  19064. const lengthBefore = arcLengths[ i ];
  19065. const lengthAfter = arcLengths[ i + 1 ];
  19066. const segmentLength = lengthAfter - lengthBefore;
  19067. // determine where we are between the 'before' and 'after' points
  19068. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  19069. // add that fractional amount to t
  19070. const t = ( i + segmentFraction ) / ( il - 1 );
  19071. return t;
  19072. }
  19073. // Returns a unit vector tangent at t
  19074. // In case any sub curve does not implement its tangent derivation,
  19075. // 2 points a small delta apart will be used to find its gradient
  19076. // which seems to give a reasonable approximation
  19077. getTangent( t, optionalTarget ) {
  19078. const delta = 0.0001;
  19079. let t1 = t - delta;
  19080. let t2 = t + delta;
  19081. // Capping in case of danger
  19082. if ( t1 < 0 ) t1 = 0;
  19083. if ( t2 > 1 ) t2 = 1;
  19084. const pt1 = this.getPoint( t1 );
  19085. const pt2 = this.getPoint( t2 );
  19086. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  19087. tangent.copy( pt2 ).sub( pt1 ).normalize();
  19088. return tangent;
  19089. }
  19090. getTangentAt( u, optionalTarget ) {
  19091. const t = this.getUtoTmapping( u );
  19092. return this.getTangent( t, optionalTarget );
  19093. }
  19094. computeFrenetFrames( segments, closed ) {
  19095. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19096. const normal = new Vector3();
  19097. const tangents = [];
  19098. const normals = [];
  19099. const binormals = [];
  19100. const vec = new Vector3();
  19101. const mat = new Matrix4();
  19102. // compute the tangent vectors for each segment on the curve
  19103. for ( let i = 0; i <= segments; i ++ ) {
  19104. const u = i / segments;
  19105. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  19106. }
  19107. // select an initial normal vector perpendicular to the first tangent vector,
  19108. // and in the direction of the minimum tangent xyz component
  19109. normals[ 0 ] = new Vector3();
  19110. binormals[ 0 ] = new Vector3();
  19111. let min = Number.MAX_VALUE;
  19112. const tx = Math.abs( tangents[ 0 ].x );
  19113. const ty = Math.abs( tangents[ 0 ].y );
  19114. const tz = Math.abs( tangents[ 0 ].z );
  19115. if ( tx <= min ) {
  19116. min = tx;
  19117. normal.set( 1, 0, 0 );
  19118. }
  19119. if ( ty <= min ) {
  19120. min = ty;
  19121. normal.set( 0, 1, 0 );
  19122. }
  19123. if ( tz <= min ) {
  19124. normal.set( 0, 0, 1 );
  19125. }
  19126. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19127. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19128. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19129. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  19130. for ( let i = 1; i <= segments; i ++ ) {
  19131. normals[ i ] = normals[ i - 1 ].clone();
  19132. binormals[ i ] = binormals[ i - 1 ].clone();
  19133. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19134. if ( vec.length() > Number.EPSILON ) {
  19135. vec.normalize();
  19136. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19137. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19138. }
  19139. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19140. }
  19141. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19142. if ( closed === true ) {
  19143. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  19144. theta /= segments;
  19145. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  19146. theta = - theta;
  19147. }
  19148. for ( let i = 1; i <= segments; i ++ ) {
  19149. // twist a little...
  19150. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19151. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19152. }
  19153. }
  19154. return {
  19155. tangents: tangents,
  19156. normals: normals,
  19157. binormals: binormals
  19158. };
  19159. }
  19160. clone() {
  19161. return new this.constructor().copy( this );
  19162. }
  19163. copy( source ) {
  19164. this.arcLengthDivisions = source.arcLengthDivisions;
  19165. return this;
  19166. }
  19167. toJSON() {
  19168. const data = {
  19169. metadata: {
  19170. version: 4.5,
  19171. type: 'Curve',
  19172. generator: 'Curve.toJSON'
  19173. }
  19174. };
  19175. data.arcLengthDivisions = this.arcLengthDivisions;
  19176. data.type = this.type;
  19177. return data;
  19178. }
  19179. fromJSON( json ) {
  19180. this.arcLengthDivisions = json.arcLengthDivisions;
  19181. return this;
  19182. }
  19183. }
  19184. class EllipseCurve extends Curve {
  19185. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  19186. super();
  19187. this.isEllipseCurve = true;
  19188. this.type = 'EllipseCurve';
  19189. this.aX = aX;
  19190. this.aY = aY;
  19191. this.xRadius = xRadius;
  19192. this.yRadius = yRadius;
  19193. this.aStartAngle = aStartAngle;
  19194. this.aEndAngle = aEndAngle;
  19195. this.aClockwise = aClockwise;
  19196. this.aRotation = aRotation;
  19197. }
  19198. getPoint( t, optionalTarget ) {
  19199. const point = optionalTarget || new Vector2();
  19200. const twoPi = Math.PI * 2;
  19201. let deltaAngle = this.aEndAngle - this.aStartAngle;
  19202. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  19203. // ensures that deltaAngle is 0 .. 2 PI
  19204. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  19205. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  19206. if ( deltaAngle < Number.EPSILON ) {
  19207. if ( samePoints ) {
  19208. deltaAngle = 0;
  19209. } else {
  19210. deltaAngle = twoPi;
  19211. }
  19212. }
  19213. if ( this.aClockwise === true && ! samePoints ) {
  19214. if ( deltaAngle === twoPi ) {
  19215. deltaAngle = - twoPi;
  19216. } else {
  19217. deltaAngle = deltaAngle - twoPi;
  19218. }
  19219. }
  19220. const angle = this.aStartAngle + t * deltaAngle;
  19221. let x = this.aX + this.xRadius * Math.cos( angle );
  19222. let y = this.aY + this.yRadius * Math.sin( angle );
  19223. if ( this.aRotation !== 0 ) {
  19224. const cos = Math.cos( this.aRotation );
  19225. const sin = Math.sin( this.aRotation );
  19226. const tx = x - this.aX;
  19227. const ty = y - this.aY;
  19228. // Rotate the point about the center of the ellipse.
  19229. x = tx * cos - ty * sin + this.aX;
  19230. y = tx * sin + ty * cos + this.aY;
  19231. }
  19232. return point.set( x, y );
  19233. }
  19234. copy( source ) {
  19235. super.copy( source );
  19236. this.aX = source.aX;
  19237. this.aY = source.aY;
  19238. this.xRadius = source.xRadius;
  19239. this.yRadius = source.yRadius;
  19240. this.aStartAngle = source.aStartAngle;
  19241. this.aEndAngle = source.aEndAngle;
  19242. this.aClockwise = source.aClockwise;
  19243. this.aRotation = source.aRotation;
  19244. return this;
  19245. }
  19246. toJSON() {
  19247. const data = super.toJSON();
  19248. data.aX = this.aX;
  19249. data.aY = this.aY;
  19250. data.xRadius = this.xRadius;
  19251. data.yRadius = this.yRadius;
  19252. data.aStartAngle = this.aStartAngle;
  19253. data.aEndAngle = this.aEndAngle;
  19254. data.aClockwise = this.aClockwise;
  19255. data.aRotation = this.aRotation;
  19256. return data;
  19257. }
  19258. fromJSON( json ) {
  19259. super.fromJSON( json );
  19260. this.aX = json.aX;
  19261. this.aY = json.aY;
  19262. this.xRadius = json.xRadius;
  19263. this.yRadius = json.yRadius;
  19264. this.aStartAngle = json.aStartAngle;
  19265. this.aEndAngle = json.aEndAngle;
  19266. this.aClockwise = json.aClockwise;
  19267. this.aRotation = json.aRotation;
  19268. return this;
  19269. }
  19270. }
  19271. class ArcCurve extends EllipseCurve {
  19272. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19273. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19274. this.isArcCurve = true;
  19275. this.type = 'ArcCurve';
  19276. }
  19277. }
  19278. /**
  19279. * Centripetal CatmullRom Curve - which is useful for avoiding
  19280. * cusps and self-intersections in non-uniform catmull rom curves.
  19281. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19282. *
  19283. * curve.type accepts centripetal(default), chordal and catmullrom
  19284. * curve.tension is used for catmullrom which defaults to 0.5
  19285. */
  19286. /*
  19287. Based on an optimized c++ solution in
  19288. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19289. - http://ideone.com/NoEbVM
  19290. This CubicPoly class could be used for reusing some variables and calculations,
  19291. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19292. which can be placed in CurveUtils.
  19293. */
  19294. function CubicPoly() {
  19295. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  19296. /*
  19297. * Compute coefficients for a cubic polynomial
  19298. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19299. * such that
  19300. * p(0) = x0, p(1) = x1
  19301. * and
  19302. * p'(0) = t0, p'(1) = t1.
  19303. */
  19304. function init( x0, x1, t0, t1 ) {
  19305. c0 = x0;
  19306. c1 = t0;
  19307. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19308. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19309. }
  19310. return {
  19311. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19312. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19313. },
  19314. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19315. // compute tangents when parameterized in [t1,t2]
  19316. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19317. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19318. // rescale tangents for parametrization in [0,1]
  19319. t1 *= dt1;
  19320. t2 *= dt1;
  19321. init( x1, x2, t1, t2 );
  19322. },
  19323. calc: function ( t ) {
  19324. const t2 = t * t;
  19325. const t3 = t2 * t;
  19326. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19327. }
  19328. };
  19329. }
  19330. //
  19331. const tmp = /*@__PURE__*/ new Vector3();
  19332. const px = /*@__PURE__*/ new CubicPoly();
  19333. const py = /*@__PURE__*/ new CubicPoly();
  19334. const pz = /*@__PURE__*/ new CubicPoly();
  19335. class CatmullRomCurve3 extends Curve {
  19336. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19337. super();
  19338. this.isCatmullRomCurve3 = true;
  19339. this.type = 'CatmullRomCurve3';
  19340. this.points = points;
  19341. this.closed = closed;
  19342. this.curveType = curveType;
  19343. this.tension = tension;
  19344. }
  19345. getPoint( t, optionalTarget = new Vector3() ) {
  19346. const point = optionalTarget;
  19347. const points = this.points;
  19348. const l = points.length;
  19349. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19350. let intPoint = Math.floor( p );
  19351. let weight = p - intPoint;
  19352. if ( this.closed ) {
  19353. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19354. } else if ( weight === 0 && intPoint === l - 1 ) {
  19355. intPoint = l - 2;
  19356. weight = 1;
  19357. }
  19358. let p0, p3; // 4 points (p1 & p2 defined below)
  19359. if ( this.closed || intPoint > 0 ) {
  19360. p0 = points[ ( intPoint - 1 ) % l ];
  19361. } else {
  19362. // extrapolate first point
  19363. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19364. p0 = tmp;
  19365. }
  19366. const p1 = points[ intPoint % l ];
  19367. const p2 = points[ ( intPoint + 1 ) % l ];
  19368. if ( this.closed || intPoint + 2 < l ) {
  19369. p3 = points[ ( intPoint + 2 ) % l ];
  19370. } else {
  19371. // extrapolate last point
  19372. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19373. p3 = tmp;
  19374. }
  19375. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19376. // init Centripetal / Chordal Catmull-Rom
  19377. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19378. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19379. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19380. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19381. // safety check for repeated points
  19382. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19383. if ( dt0 < 1e-4 ) dt0 = dt1;
  19384. if ( dt2 < 1e-4 ) dt2 = dt1;
  19385. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19386. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19387. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19388. } else if ( this.curveType === 'catmullrom' ) {
  19389. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19390. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19391. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19392. }
  19393. point.set(
  19394. px.calc( weight ),
  19395. py.calc( weight ),
  19396. pz.calc( weight )
  19397. );
  19398. return point;
  19399. }
  19400. copy( source ) {
  19401. super.copy( source );
  19402. this.points = [];
  19403. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19404. const point = source.points[ i ];
  19405. this.points.push( point.clone() );
  19406. }
  19407. this.closed = source.closed;
  19408. this.curveType = source.curveType;
  19409. this.tension = source.tension;
  19410. return this;
  19411. }
  19412. toJSON() {
  19413. const data = super.toJSON();
  19414. data.points = [];
  19415. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19416. const point = this.points[ i ];
  19417. data.points.push( point.toArray() );
  19418. }
  19419. data.closed = this.closed;
  19420. data.curveType = this.curveType;
  19421. data.tension = this.tension;
  19422. return data;
  19423. }
  19424. fromJSON( json ) {
  19425. super.fromJSON( json );
  19426. this.points = [];
  19427. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19428. const point = json.points[ i ];
  19429. this.points.push( new Vector3().fromArray( point ) );
  19430. }
  19431. this.closed = json.closed;
  19432. this.curveType = json.curveType;
  19433. this.tension = json.tension;
  19434. return this;
  19435. }
  19436. }
  19437. /**
  19438. * Bezier Curves formulas obtained from
  19439. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19440. */
  19441. function CatmullRom( t, p0, p1, p2, p3 ) {
  19442. const v0 = ( p2 - p0 ) * 0.5;
  19443. const v1 = ( p3 - p1 ) * 0.5;
  19444. const t2 = t * t;
  19445. const t3 = t * t2;
  19446. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19447. }
  19448. //
  19449. function QuadraticBezierP0( t, p ) {
  19450. const k = 1 - t;
  19451. return k * k * p;
  19452. }
  19453. function QuadraticBezierP1( t, p ) {
  19454. return 2 * ( 1 - t ) * t * p;
  19455. }
  19456. function QuadraticBezierP2( t, p ) {
  19457. return t * t * p;
  19458. }
  19459. function QuadraticBezier( t, p0, p1, p2 ) {
  19460. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19461. QuadraticBezierP2( t, p2 );
  19462. }
  19463. //
  19464. function CubicBezierP0( t, p ) {
  19465. const k = 1 - t;
  19466. return k * k * k * p;
  19467. }
  19468. function CubicBezierP1( t, p ) {
  19469. const k = 1 - t;
  19470. return 3 * k * k * t * p;
  19471. }
  19472. function CubicBezierP2( t, p ) {
  19473. return 3 * ( 1 - t ) * t * t * p;
  19474. }
  19475. function CubicBezierP3( t, p ) {
  19476. return t * t * t * p;
  19477. }
  19478. function CubicBezier( t, p0, p1, p2, p3 ) {
  19479. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19480. CubicBezierP3( t, p3 );
  19481. }
  19482. class CubicBezierCurve extends Curve {
  19483. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19484. super();
  19485. this.isCubicBezierCurve = true;
  19486. this.type = 'CubicBezierCurve';
  19487. this.v0 = v0;
  19488. this.v1 = v1;
  19489. this.v2 = v2;
  19490. this.v3 = v3;
  19491. }
  19492. getPoint( t, optionalTarget = new Vector2() ) {
  19493. const point = optionalTarget;
  19494. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19495. point.set(
  19496. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19497. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19498. );
  19499. return point;
  19500. }
  19501. copy( source ) {
  19502. super.copy( source );
  19503. this.v0.copy( source.v0 );
  19504. this.v1.copy( source.v1 );
  19505. this.v2.copy( source.v2 );
  19506. this.v3.copy( source.v3 );
  19507. return this;
  19508. }
  19509. toJSON() {
  19510. const data = super.toJSON();
  19511. data.v0 = this.v0.toArray();
  19512. data.v1 = this.v1.toArray();
  19513. data.v2 = this.v2.toArray();
  19514. data.v3 = this.v3.toArray();
  19515. return data;
  19516. }
  19517. fromJSON( json ) {
  19518. super.fromJSON( json );
  19519. this.v0.fromArray( json.v0 );
  19520. this.v1.fromArray( json.v1 );
  19521. this.v2.fromArray( json.v2 );
  19522. this.v3.fromArray( json.v3 );
  19523. return this;
  19524. }
  19525. }
  19526. class CubicBezierCurve3 extends Curve {
  19527. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19528. super();
  19529. this.isCubicBezierCurve3 = true;
  19530. this.type = 'CubicBezierCurve3';
  19531. this.v0 = v0;
  19532. this.v1 = v1;
  19533. this.v2 = v2;
  19534. this.v3 = v3;
  19535. }
  19536. getPoint( t, optionalTarget = new Vector3() ) {
  19537. const point = optionalTarget;
  19538. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19539. point.set(
  19540. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19541. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19542. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19543. );
  19544. return point;
  19545. }
  19546. copy( source ) {
  19547. super.copy( source );
  19548. this.v0.copy( source.v0 );
  19549. this.v1.copy( source.v1 );
  19550. this.v2.copy( source.v2 );
  19551. this.v3.copy( source.v3 );
  19552. return this;
  19553. }
  19554. toJSON() {
  19555. const data = super.toJSON();
  19556. data.v0 = this.v0.toArray();
  19557. data.v1 = this.v1.toArray();
  19558. data.v2 = this.v2.toArray();
  19559. data.v3 = this.v3.toArray();
  19560. return data;
  19561. }
  19562. fromJSON( json ) {
  19563. super.fromJSON( json );
  19564. this.v0.fromArray( json.v0 );
  19565. this.v1.fromArray( json.v1 );
  19566. this.v2.fromArray( json.v2 );
  19567. this.v3.fromArray( json.v3 );
  19568. return this;
  19569. }
  19570. }
  19571. class LineCurve extends Curve {
  19572. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19573. super();
  19574. this.isLineCurve = true;
  19575. this.type = 'LineCurve';
  19576. this.v1 = v1;
  19577. this.v2 = v2;
  19578. }
  19579. getPoint( t, optionalTarget = new Vector2() ) {
  19580. const point = optionalTarget;
  19581. if ( t === 1 ) {
  19582. point.copy( this.v2 );
  19583. } else {
  19584. point.copy( this.v2 ).sub( this.v1 );
  19585. point.multiplyScalar( t ).add( this.v1 );
  19586. }
  19587. return point;
  19588. }
  19589. // Line curve is linear, so we can overwrite default getPointAt
  19590. getPointAt( u, optionalTarget ) {
  19591. return this.getPoint( u, optionalTarget );
  19592. }
  19593. getTangent( t, optionalTarget = new Vector2() ) {
  19594. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  19595. }
  19596. getTangentAt( u, optionalTarget ) {
  19597. return this.getTangent( u, optionalTarget );
  19598. }
  19599. copy( source ) {
  19600. super.copy( source );
  19601. this.v1.copy( source.v1 );
  19602. this.v2.copy( source.v2 );
  19603. return this;
  19604. }
  19605. toJSON() {
  19606. const data = super.toJSON();
  19607. data.v1 = this.v1.toArray();
  19608. data.v2 = this.v2.toArray();
  19609. return data;
  19610. }
  19611. fromJSON( json ) {
  19612. super.fromJSON( json );
  19613. this.v1.fromArray( json.v1 );
  19614. this.v2.fromArray( json.v2 );
  19615. return this;
  19616. }
  19617. }
  19618. class LineCurve3 extends Curve {
  19619. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19620. super();
  19621. this.isLineCurve3 = true;
  19622. this.type = 'LineCurve3';
  19623. this.v1 = v1;
  19624. this.v2 = v2;
  19625. }
  19626. getPoint( t, optionalTarget = new Vector3() ) {
  19627. const point = optionalTarget;
  19628. if ( t === 1 ) {
  19629. point.copy( this.v2 );
  19630. } else {
  19631. point.copy( this.v2 ).sub( this.v1 );
  19632. point.multiplyScalar( t ).add( this.v1 );
  19633. }
  19634. return point;
  19635. }
  19636. // Line curve is linear, so we can overwrite default getPointAt
  19637. getPointAt( u, optionalTarget ) {
  19638. return this.getPoint( u, optionalTarget );
  19639. }
  19640. getTangent( t, optionalTarget = new Vector3() ) {
  19641. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  19642. }
  19643. getTangentAt( u, optionalTarget ) {
  19644. return this.getTangent( u, optionalTarget );
  19645. }
  19646. copy( source ) {
  19647. super.copy( source );
  19648. this.v1.copy( source.v1 );
  19649. this.v2.copy( source.v2 );
  19650. return this;
  19651. }
  19652. toJSON() {
  19653. const data = super.toJSON();
  19654. data.v1 = this.v1.toArray();
  19655. data.v2 = this.v2.toArray();
  19656. return data;
  19657. }
  19658. fromJSON( json ) {
  19659. super.fromJSON( json );
  19660. this.v1.fromArray( json.v1 );
  19661. this.v2.fromArray( json.v2 );
  19662. return this;
  19663. }
  19664. }
  19665. class QuadraticBezierCurve extends Curve {
  19666. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19667. super();
  19668. this.isQuadraticBezierCurve = true;
  19669. this.type = 'QuadraticBezierCurve';
  19670. this.v0 = v0;
  19671. this.v1 = v1;
  19672. this.v2 = v2;
  19673. }
  19674. getPoint( t, optionalTarget = new Vector2() ) {
  19675. const point = optionalTarget;
  19676. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19677. point.set(
  19678. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19679. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19680. );
  19681. return point;
  19682. }
  19683. copy( source ) {
  19684. super.copy( source );
  19685. this.v0.copy( source.v0 );
  19686. this.v1.copy( source.v1 );
  19687. this.v2.copy( source.v2 );
  19688. return this;
  19689. }
  19690. toJSON() {
  19691. const data = super.toJSON();
  19692. data.v0 = this.v0.toArray();
  19693. data.v1 = this.v1.toArray();
  19694. data.v2 = this.v2.toArray();
  19695. return data;
  19696. }
  19697. fromJSON( json ) {
  19698. super.fromJSON( json );
  19699. this.v0.fromArray( json.v0 );
  19700. this.v1.fromArray( json.v1 );
  19701. this.v2.fromArray( json.v2 );
  19702. return this;
  19703. }
  19704. }
  19705. class QuadraticBezierCurve3 extends Curve {
  19706. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19707. super();
  19708. this.isQuadraticBezierCurve3 = true;
  19709. this.type = 'QuadraticBezierCurve3';
  19710. this.v0 = v0;
  19711. this.v1 = v1;
  19712. this.v2 = v2;
  19713. }
  19714. getPoint( t, optionalTarget = new Vector3() ) {
  19715. const point = optionalTarget;
  19716. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19717. point.set(
  19718. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19719. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19720. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19721. );
  19722. return point;
  19723. }
  19724. copy( source ) {
  19725. super.copy( source );
  19726. this.v0.copy( source.v0 );
  19727. this.v1.copy( source.v1 );
  19728. this.v2.copy( source.v2 );
  19729. return this;
  19730. }
  19731. toJSON() {
  19732. const data = super.toJSON();
  19733. data.v0 = this.v0.toArray();
  19734. data.v1 = this.v1.toArray();
  19735. data.v2 = this.v2.toArray();
  19736. return data;
  19737. }
  19738. fromJSON( json ) {
  19739. super.fromJSON( json );
  19740. this.v0.fromArray( json.v0 );
  19741. this.v1.fromArray( json.v1 );
  19742. this.v2.fromArray( json.v2 );
  19743. return this;
  19744. }
  19745. }
  19746. class SplineCurve extends Curve {
  19747. constructor( points = [] ) {
  19748. super();
  19749. this.isSplineCurve = true;
  19750. this.type = 'SplineCurve';
  19751. this.points = points;
  19752. }
  19753. getPoint( t, optionalTarget = new Vector2() ) {
  19754. const point = optionalTarget;
  19755. const points = this.points;
  19756. const p = ( points.length - 1 ) * t;
  19757. const intPoint = Math.floor( p );
  19758. const weight = p - intPoint;
  19759. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19760. const p1 = points[ intPoint ];
  19761. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19762. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19763. point.set(
  19764. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19765. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19766. );
  19767. return point;
  19768. }
  19769. copy( source ) {
  19770. super.copy( source );
  19771. this.points = [];
  19772. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19773. const point = source.points[ i ];
  19774. this.points.push( point.clone() );
  19775. }
  19776. return this;
  19777. }
  19778. toJSON() {
  19779. const data = super.toJSON();
  19780. data.points = [];
  19781. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19782. const point = this.points[ i ];
  19783. data.points.push( point.toArray() );
  19784. }
  19785. return data;
  19786. }
  19787. fromJSON( json ) {
  19788. super.fromJSON( json );
  19789. this.points = [];
  19790. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19791. const point = json.points[ i ];
  19792. this.points.push( new Vector2().fromArray( point ) );
  19793. }
  19794. return this;
  19795. }
  19796. }
  19797. var Curves = /*#__PURE__*/Object.freeze({
  19798. __proto__: null,
  19799. ArcCurve: ArcCurve,
  19800. CatmullRomCurve3: CatmullRomCurve3,
  19801. CubicBezierCurve: CubicBezierCurve,
  19802. CubicBezierCurve3: CubicBezierCurve3,
  19803. EllipseCurve: EllipseCurve,
  19804. LineCurve: LineCurve,
  19805. LineCurve3: LineCurve3,
  19806. QuadraticBezierCurve: QuadraticBezierCurve,
  19807. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19808. SplineCurve: SplineCurve
  19809. });
  19810. /**************************************************************
  19811. * Curved Path - a curve path is simply a array of connected
  19812. * curves, but retains the api of a curve
  19813. **************************************************************/
  19814. class CurvePath extends Curve {
  19815. constructor() {
  19816. super();
  19817. this.type = 'CurvePath';
  19818. this.curves = [];
  19819. this.autoClose = false; // Automatically closes the path
  19820. }
  19821. add( curve ) {
  19822. this.curves.push( curve );
  19823. }
  19824. closePath() {
  19825. // Add a line curve if start and end of lines are not connected
  19826. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19827. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19828. if ( ! startPoint.equals( endPoint ) ) {
  19829. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19830. }
  19831. }
  19832. // To get accurate point with reference to
  19833. // entire path distance at time t,
  19834. // following has to be done:
  19835. // 1. Length of each sub path have to be known
  19836. // 2. Locate and identify type of curve
  19837. // 3. Get t for the curve
  19838. // 4. Return curve.getPointAt(t')
  19839. getPoint( t, optionalTarget ) {
  19840. const d = t * this.getLength();
  19841. const curveLengths = this.getCurveLengths();
  19842. let i = 0;
  19843. // To think about boundaries points.
  19844. while ( i < curveLengths.length ) {
  19845. if ( curveLengths[ i ] >= d ) {
  19846. const diff = curveLengths[ i ] - d;
  19847. const curve = this.curves[ i ];
  19848. const segmentLength = curve.getLength();
  19849. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19850. return curve.getPointAt( u, optionalTarget );
  19851. }
  19852. i ++;
  19853. }
  19854. return null;
  19855. // loop where sum != 0, sum > d , sum+1 <d
  19856. }
  19857. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19858. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19859. // getPoint() depends on getLength
  19860. getLength() {
  19861. const lens = this.getCurveLengths();
  19862. return lens[ lens.length - 1 ];
  19863. }
  19864. // cacheLengths must be recalculated.
  19865. updateArcLengths() {
  19866. this.needsUpdate = true;
  19867. this.cacheLengths = null;
  19868. this.getCurveLengths();
  19869. }
  19870. // Compute lengths and cache them
  19871. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19872. getCurveLengths() {
  19873. // We use cache values if curves and cache array are same length
  19874. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19875. return this.cacheLengths;
  19876. }
  19877. // Get length of sub-curve
  19878. // Push sums into cached array
  19879. const lengths = [];
  19880. let sums = 0;
  19881. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19882. sums += this.curves[ i ].getLength();
  19883. lengths.push( sums );
  19884. }
  19885. this.cacheLengths = lengths;
  19886. return lengths;
  19887. }
  19888. getSpacedPoints( divisions = 40 ) {
  19889. const points = [];
  19890. for ( let i = 0; i <= divisions; i ++ ) {
  19891. points.push( this.getPoint( i / divisions ) );
  19892. }
  19893. if ( this.autoClose ) {
  19894. points.push( points[ 0 ] );
  19895. }
  19896. return points;
  19897. }
  19898. getPoints( divisions = 12 ) {
  19899. const points = [];
  19900. let last;
  19901. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19902. const curve = curves[ i ];
  19903. const resolution = curve.isEllipseCurve ? divisions * 2
  19904. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19905. : curve.isSplineCurve ? divisions * curve.points.length
  19906. : divisions;
  19907. const pts = curve.getPoints( resolution );
  19908. for ( let j = 0; j < pts.length; j ++ ) {
  19909. const point = pts[ j ];
  19910. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19911. points.push( point );
  19912. last = point;
  19913. }
  19914. }
  19915. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19916. points.push( points[ 0 ] );
  19917. }
  19918. return points;
  19919. }
  19920. copy( source ) {
  19921. super.copy( source );
  19922. this.curves = [];
  19923. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19924. const curve = source.curves[ i ];
  19925. this.curves.push( curve.clone() );
  19926. }
  19927. this.autoClose = source.autoClose;
  19928. return this;
  19929. }
  19930. toJSON() {
  19931. const data = super.toJSON();
  19932. data.autoClose = this.autoClose;
  19933. data.curves = [];
  19934. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19935. const curve = this.curves[ i ];
  19936. data.curves.push( curve.toJSON() );
  19937. }
  19938. return data;
  19939. }
  19940. fromJSON( json ) {
  19941. super.fromJSON( json );
  19942. this.autoClose = json.autoClose;
  19943. this.curves = [];
  19944. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19945. const curve = json.curves[ i ];
  19946. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19947. }
  19948. return this;
  19949. }
  19950. }
  19951. class Path extends CurvePath {
  19952. constructor( points ) {
  19953. super();
  19954. this.type = 'Path';
  19955. this.currentPoint = new Vector2();
  19956. if ( points ) {
  19957. this.setFromPoints( points );
  19958. }
  19959. }
  19960. setFromPoints( points ) {
  19961. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19962. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19963. this.lineTo( points[ i ].x, points[ i ].y );
  19964. }
  19965. return this;
  19966. }
  19967. moveTo( x, y ) {
  19968. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19969. return this;
  19970. }
  19971. lineTo( x, y ) {
  19972. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19973. this.curves.push( curve );
  19974. this.currentPoint.set( x, y );
  19975. return this;
  19976. }
  19977. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19978. const curve = new QuadraticBezierCurve(
  19979. this.currentPoint.clone(),
  19980. new Vector2( aCPx, aCPy ),
  19981. new Vector2( aX, aY )
  19982. );
  19983. this.curves.push( curve );
  19984. this.currentPoint.set( aX, aY );
  19985. return this;
  19986. }
  19987. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19988. const curve = new CubicBezierCurve(
  19989. this.currentPoint.clone(),
  19990. new Vector2( aCP1x, aCP1y ),
  19991. new Vector2( aCP2x, aCP2y ),
  19992. new Vector2( aX, aY )
  19993. );
  19994. this.curves.push( curve );
  19995. this.currentPoint.set( aX, aY );
  19996. return this;
  19997. }
  19998. splineThru( pts /*Array of Vector*/ ) {
  19999. const npts = [ this.currentPoint.clone() ].concat( pts );
  20000. const curve = new SplineCurve( npts );
  20001. this.curves.push( curve );
  20002. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20003. return this;
  20004. }
  20005. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20006. const x0 = this.currentPoint.x;
  20007. const y0 = this.currentPoint.y;
  20008. this.absarc( aX + x0, aY + y0, aRadius,
  20009. aStartAngle, aEndAngle, aClockwise );
  20010. return this;
  20011. }
  20012. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20013. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20014. return this;
  20015. }
  20016. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20017. const x0 = this.currentPoint.x;
  20018. const y0 = this.currentPoint.y;
  20019. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20020. return this;
  20021. }
  20022. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20023. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20024. if ( this.curves.length > 0 ) {
  20025. // if a previous curve is present, attempt to join
  20026. const firstPoint = curve.getPoint( 0 );
  20027. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20028. this.lineTo( firstPoint.x, firstPoint.y );
  20029. }
  20030. }
  20031. this.curves.push( curve );
  20032. const lastPoint = curve.getPoint( 1 );
  20033. this.currentPoint.copy( lastPoint );
  20034. return this;
  20035. }
  20036. copy( source ) {
  20037. super.copy( source );
  20038. this.currentPoint.copy( source.currentPoint );
  20039. return this;
  20040. }
  20041. toJSON() {
  20042. const data = super.toJSON();
  20043. data.currentPoint = this.currentPoint.toArray();
  20044. return data;
  20045. }
  20046. fromJSON( json ) {
  20047. super.fromJSON( json );
  20048. this.currentPoint.fromArray( json.currentPoint );
  20049. return this;
  20050. }
  20051. }
  20052. class LatheGeometry extends BufferGeometry {
  20053. constructor( points = [ new Vector2( 0, - 0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  20054. super();
  20055. this.type = 'LatheGeometry';
  20056. this.parameters = {
  20057. points: points,
  20058. segments: segments,
  20059. phiStart: phiStart,
  20060. phiLength: phiLength
  20061. };
  20062. segments = Math.floor( segments );
  20063. // clamp phiLength so it's in range of [ 0, 2PI ]
  20064. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  20065. // buffers
  20066. const indices = [];
  20067. const vertices = [];
  20068. const uvs = [];
  20069. const initNormals = [];
  20070. const normals = [];
  20071. // helper variables
  20072. const inverseSegments = 1.0 / segments;
  20073. const vertex = new Vector3();
  20074. const uv = new Vector2();
  20075. const normal = new Vector3();
  20076. const curNormal = new Vector3();
  20077. const prevNormal = new Vector3();
  20078. let dx = 0;
  20079. let dy = 0;
  20080. // pre-compute normals for initial "meridian"
  20081. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20082. switch ( j ) {
  20083. case 0: // special handling for 1st vertex on path
  20084. dx = points[ j + 1 ].x - points[ j ].x;
  20085. dy = points[ j + 1 ].y - points[ j ].y;
  20086. normal.x = dy * 1.0;
  20087. normal.y = - dx;
  20088. normal.z = dy * 0.0;
  20089. prevNormal.copy( normal );
  20090. normal.normalize();
  20091. initNormals.push( normal.x, normal.y, normal.z );
  20092. break;
  20093. case ( points.length - 1 ): // special handling for last Vertex on path
  20094. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  20095. break;
  20096. default: // default handling for all vertices in between
  20097. dx = points[ j + 1 ].x - points[ j ].x;
  20098. dy = points[ j + 1 ].y - points[ j ].y;
  20099. normal.x = dy * 1.0;
  20100. normal.y = - dx;
  20101. normal.z = dy * 0.0;
  20102. curNormal.copy( normal );
  20103. normal.x += prevNormal.x;
  20104. normal.y += prevNormal.y;
  20105. normal.z += prevNormal.z;
  20106. normal.normalize();
  20107. initNormals.push( normal.x, normal.y, normal.z );
  20108. prevNormal.copy( curNormal );
  20109. }
  20110. }
  20111. // generate vertices, uvs and normals
  20112. for ( let i = 0; i <= segments; i ++ ) {
  20113. const phi = phiStart + i * inverseSegments * phiLength;
  20114. const sin = Math.sin( phi );
  20115. const cos = Math.cos( phi );
  20116. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20117. // vertex
  20118. vertex.x = points[ j ].x * sin;
  20119. vertex.y = points[ j ].y;
  20120. vertex.z = points[ j ].x * cos;
  20121. vertices.push( vertex.x, vertex.y, vertex.z );
  20122. // uv
  20123. uv.x = i / segments;
  20124. uv.y = j / ( points.length - 1 );
  20125. uvs.push( uv.x, uv.y );
  20126. // normal
  20127. const x = initNormals[ 3 * j + 0 ] * sin;
  20128. const y = initNormals[ 3 * j + 1 ];
  20129. const z = initNormals[ 3 * j + 0 ] * cos;
  20130. normals.push( x, y, z );
  20131. }
  20132. }
  20133. // indices
  20134. for ( let i = 0; i < segments; i ++ ) {
  20135. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  20136. const base = j + i * points.length;
  20137. const a = base;
  20138. const b = base + points.length;
  20139. const c = base + points.length + 1;
  20140. const d = base + 1;
  20141. // faces
  20142. indices.push( a, b, d );
  20143. indices.push( c, d, b );
  20144. }
  20145. }
  20146. // build geometry
  20147. this.setIndex( indices );
  20148. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20149. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20150. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20151. }
  20152. copy( source ) {
  20153. super.copy( source );
  20154. this.parameters = Object.assign( {}, source.parameters );
  20155. return this;
  20156. }
  20157. static fromJSON( data ) {
  20158. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  20159. }
  20160. }
  20161. class CapsuleGeometry extends LatheGeometry {
  20162. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  20163. const path = new Path();
  20164. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  20165. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  20166. super( path.getPoints( capSegments ), radialSegments );
  20167. this.type = 'CapsuleGeometry';
  20168. this.parameters = {
  20169. radius: radius,
  20170. height: length,
  20171. capSegments: capSegments,
  20172. radialSegments: radialSegments,
  20173. };
  20174. }
  20175. static fromJSON( data ) {
  20176. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  20177. }
  20178. }
  20179. class CircleGeometry extends BufferGeometry {
  20180. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20181. super();
  20182. this.type = 'CircleGeometry';
  20183. this.parameters = {
  20184. radius: radius,
  20185. segments: segments,
  20186. thetaStart: thetaStart,
  20187. thetaLength: thetaLength
  20188. };
  20189. segments = Math.max( 3, segments );
  20190. // buffers
  20191. const indices = [];
  20192. const vertices = [];
  20193. const normals = [];
  20194. const uvs = [];
  20195. // helper variables
  20196. const vertex = new Vector3();
  20197. const uv = new Vector2();
  20198. // center point
  20199. vertices.push( 0, 0, 0 );
  20200. normals.push( 0, 0, 1 );
  20201. uvs.push( 0.5, 0.5 );
  20202. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  20203. const segment = thetaStart + s / segments * thetaLength;
  20204. // vertex
  20205. vertex.x = radius * Math.cos( segment );
  20206. vertex.y = radius * Math.sin( segment );
  20207. vertices.push( vertex.x, vertex.y, vertex.z );
  20208. // normal
  20209. normals.push( 0, 0, 1 );
  20210. // uvs
  20211. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  20212. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  20213. uvs.push( uv.x, uv.y );
  20214. }
  20215. // indices
  20216. for ( let i = 1; i <= segments; i ++ ) {
  20217. indices.push( i, i + 1, 0 );
  20218. }
  20219. // build geometry
  20220. this.setIndex( indices );
  20221. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20222. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20223. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20224. }
  20225. copy( source ) {
  20226. super.copy( source );
  20227. this.parameters = Object.assign( {}, source.parameters );
  20228. return this;
  20229. }
  20230. static fromJSON( data ) {
  20231. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  20232. }
  20233. }
  20234. class CylinderGeometry extends BufferGeometry {
  20235. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20236. super();
  20237. this.type = 'CylinderGeometry';
  20238. this.parameters = {
  20239. radiusTop: radiusTop,
  20240. radiusBottom: radiusBottom,
  20241. height: height,
  20242. radialSegments: radialSegments,
  20243. heightSegments: heightSegments,
  20244. openEnded: openEnded,
  20245. thetaStart: thetaStart,
  20246. thetaLength: thetaLength
  20247. };
  20248. const scope = this;
  20249. radialSegments = Math.floor( radialSegments );
  20250. heightSegments = Math.floor( heightSegments );
  20251. // buffers
  20252. const indices = [];
  20253. const vertices = [];
  20254. const normals = [];
  20255. const uvs = [];
  20256. // helper variables
  20257. let index = 0;
  20258. const indexArray = [];
  20259. const halfHeight = height / 2;
  20260. let groupStart = 0;
  20261. // generate geometry
  20262. generateTorso();
  20263. if ( openEnded === false ) {
  20264. if ( radiusTop > 0 ) generateCap( true );
  20265. if ( radiusBottom > 0 ) generateCap( false );
  20266. }
  20267. // build geometry
  20268. this.setIndex( indices );
  20269. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20270. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20271. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20272. function generateTorso() {
  20273. const normal = new Vector3();
  20274. const vertex = new Vector3();
  20275. let groupCount = 0;
  20276. // this will be used to calculate the normal
  20277. const slope = ( radiusBottom - radiusTop ) / height;
  20278. // generate vertices, normals and uvs
  20279. for ( let y = 0; y <= heightSegments; y ++ ) {
  20280. const indexRow = [];
  20281. const v = y / heightSegments;
  20282. // calculate the radius of the current row
  20283. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20284. for ( let x = 0; x <= radialSegments; x ++ ) {
  20285. const u = x / radialSegments;
  20286. const theta = u * thetaLength + thetaStart;
  20287. const sinTheta = Math.sin( theta );
  20288. const cosTheta = Math.cos( theta );
  20289. // vertex
  20290. vertex.x = radius * sinTheta;
  20291. vertex.y = - v * height + halfHeight;
  20292. vertex.z = radius * cosTheta;
  20293. vertices.push( vertex.x, vertex.y, vertex.z );
  20294. // normal
  20295. normal.set( sinTheta, slope, cosTheta ).normalize();
  20296. normals.push( normal.x, normal.y, normal.z );
  20297. // uv
  20298. uvs.push( u, 1 - v );
  20299. // save index of vertex in respective row
  20300. indexRow.push( index ++ );
  20301. }
  20302. // now save vertices of the row in our index array
  20303. indexArray.push( indexRow );
  20304. }
  20305. // generate indices
  20306. for ( let x = 0; x < radialSegments; x ++ ) {
  20307. for ( let y = 0; y < heightSegments; y ++ ) {
  20308. // we use the index array to access the correct indices
  20309. const a = indexArray[ y ][ x ];
  20310. const b = indexArray[ y + 1 ][ x ];
  20311. const c = indexArray[ y + 1 ][ x + 1 ];
  20312. const d = indexArray[ y ][ x + 1 ];
  20313. // faces
  20314. indices.push( a, b, d );
  20315. indices.push( b, c, d );
  20316. // update group counter
  20317. groupCount += 6;
  20318. }
  20319. }
  20320. // add a group to the geometry. this will ensure multi material support
  20321. scope.addGroup( groupStart, groupCount, 0 );
  20322. // calculate new start value for groups
  20323. groupStart += groupCount;
  20324. }
  20325. function generateCap( top ) {
  20326. // save the index of the first center vertex
  20327. const centerIndexStart = index;
  20328. const uv = new Vector2();
  20329. const vertex = new Vector3();
  20330. let groupCount = 0;
  20331. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20332. const sign = ( top === true ) ? 1 : - 1;
  20333. // first we generate the center vertex data of the cap.
  20334. // because the geometry needs one set of uvs per face,
  20335. // we must generate a center vertex per face/segment
  20336. for ( let x = 1; x <= radialSegments; x ++ ) {
  20337. // vertex
  20338. vertices.push( 0, halfHeight * sign, 0 );
  20339. // normal
  20340. normals.push( 0, sign, 0 );
  20341. // uv
  20342. uvs.push( 0.5, 0.5 );
  20343. // increase index
  20344. index ++;
  20345. }
  20346. // save the index of the last center vertex
  20347. const centerIndexEnd = index;
  20348. // now we generate the surrounding vertices, normals and uvs
  20349. for ( let x = 0; x <= radialSegments; x ++ ) {
  20350. const u = x / radialSegments;
  20351. const theta = u * thetaLength + thetaStart;
  20352. const cosTheta = Math.cos( theta );
  20353. const sinTheta = Math.sin( theta );
  20354. // vertex
  20355. vertex.x = radius * sinTheta;
  20356. vertex.y = halfHeight * sign;
  20357. vertex.z = radius * cosTheta;
  20358. vertices.push( vertex.x, vertex.y, vertex.z );
  20359. // normal
  20360. normals.push( 0, sign, 0 );
  20361. // uv
  20362. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20363. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20364. uvs.push( uv.x, uv.y );
  20365. // increase index
  20366. index ++;
  20367. }
  20368. // generate indices
  20369. for ( let x = 0; x < radialSegments; x ++ ) {
  20370. const c = centerIndexStart + x;
  20371. const i = centerIndexEnd + x;
  20372. if ( top === true ) {
  20373. // face top
  20374. indices.push( i, i + 1, c );
  20375. } else {
  20376. // face bottom
  20377. indices.push( i + 1, i, c );
  20378. }
  20379. groupCount += 3;
  20380. }
  20381. // add a group to the geometry. this will ensure multi material support
  20382. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20383. // calculate new start value for groups
  20384. groupStart += groupCount;
  20385. }
  20386. }
  20387. copy( source ) {
  20388. super.copy( source );
  20389. this.parameters = Object.assign( {}, source.parameters );
  20390. return this;
  20391. }
  20392. static fromJSON( data ) {
  20393. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20394. }
  20395. }
  20396. class ConeGeometry extends CylinderGeometry {
  20397. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20398. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20399. this.type = 'ConeGeometry';
  20400. this.parameters = {
  20401. radius: radius,
  20402. height: height,
  20403. radialSegments: radialSegments,
  20404. heightSegments: heightSegments,
  20405. openEnded: openEnded,
  20406. thetaStart: thetaStart,
  20407. thetaLength: thetaLength
  20408. };
  20409. }
  20410. static fromJSON( data ) {
  20411. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20412. }
  20413. }
  20414. class PolyhedronGeometry extends BufferGeometry {
  20415. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20416. super();
  20417. this.type = 'PolyhedronGeometry';
  20418. this.parameters = {
  20419. vertices: vertices,
  20420. indices: indices,
  20421. radius: radius,
  20422. detail: detail
  20423. };
  20424. // default buffer data
  20425. const vertexBuffer = [];
  20426. const uvBuffer = [];
  20427. // the subdivision creates the vertex buffer data
  20428. subdivide( detail );
  20429. // all vertices should lie on a conceptual sphere with a given radius
  20430. applyRadius( radius );
  20431. // finally, create the uv data
  20432. generateUVs();
  20433. // build non-indexed geometry
  20434. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20435. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20436. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20437. if ( detail === 0 ) {
  20438. this.computeVertexNormals(); // flat normals
  20439. } else {
  20440. this.normalizeNormals(); // smooth normals
  20441. }
  20442. // helper functions
  20443. function subdivide( detail ) {
  20444. const a = new Vector3();
  20445. const b = new Vector3();
  20446. const c = new Vector3();
  20447. // iterate over all faces and apply a subdivision with the given detail value
  20448. for ( let i = 0; i < indices.length; i += 3 ) {
  20449. // get the vertices of the face
  20450. getVertexByIndex( indices[ i + 0 ], a );
  20451. getVertexByIndex( indices[ i + 1 ], b );
  20452. getVertexByIndex( indices[ i + 2 ], c );
  20453. // perform subdivision
  20454. subdivideFace( a, b, c, detail );
  20455. }
  20456. }
  20457. function subdivideFace( a, b, c, detail ) {
  20458. const cols = detail + 1;
  20459. // we use this multidimensional array as a data structure for creating the subdivision
  20460. const v = [];
  20461. // construct all of the vertices for this subdivision
  20462. for ( let i = 0; i <= cols; i ++ ) {
  20463. v[ i ] = [];
  20464. const aj = a.clone().lerp( c, i / cols );
  20465. const bj = b.clone().lerp( c, i / cols );
  20466. const rows = cols - i;
  20467. for ( let j = 0; j <= rows; j ++ ) {
  20468. if ( j === 0 && i === cols ) {
  20469. v[ i ][ j ] = aj;
  20470. } else {
  20471. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20472. }
  20473. }
  20474. }
  20475. // construct all of the faces
  20476. for ( let i = 0; i < cols; i ++ ) {
  20477. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20478. const k = Math.floor( j / 2 );
  20479. if ( j % 2 === 0 ) {
  20480. pushVertex( v[ i ][ k + 1 ] );
  20481. pushVertex( v[ i + 1 ][ k ] );
  20482. pushVertex( v[ i ][ k ] );
  20483. } else {
  20484. pushVertex( v[ i ][ k + 1 ] );
  20485. pushVertex( v[ i + 1 ][ k + 1 ] );
  20486. pushVertex( v[ i + 1 ][ k ] );
  20487. }
  20488. }
  20489. }
  20490. }
  20491. function applyRadius( radius ) {
  20492. const vertex = new Vector3();
  20493. // iterate over the entire buffer and apply the radius to each vertex
  20494. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20495. vertex.x = vertexBuffer[ i + 0 ];
  20496. vertex.y = vertexBuffer[ i + 1 ];
  20497. vertex.z = vertexBuffer[ i + 2 ];
  20498. vertex.normalize().multiplyScalar( radius );
  20499. vertexBuffer[ i + 0 ] = vertex.x;
  20500. vertexBuffer[ i + 1 ] = vertex.y;
  20501. vertexBuffer[ i + 2 ] = vertex.z;
  20502. }
  20503. }
  20504. function generateUVs() {
  20505. const vertex = new Vector3();
  20506. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20507. vertex.x = vertexBuffer[ i + 0 ];
  20508. vertex.y = vertexBuffer[ i + 1 ];
  20509. vertex.z = vertexBuffer[ i + 2 ];
  20510. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20511. const v = inclination( vertex ) / Math.PI + 0.5;
  20512. uvBuffer.push( u, 1 - v );
  20513. }
  20514. correctUVs();
  20515. correctSeam();
  20516. }
  20517. function correctSeam() {
  20518. // handle case when face straddles the seam, see #3269
  20519. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20520. // uv data of a single face
  20521. const x0 = uvBuffer[ i + 0 ];
  20522. const x1 = uvBuffer[ i + 2 ];
  20523. const x2 = uvBuffer[ i + 4 ];
  20524. const max = Math.max( x0, x1, x2 );
  20525. const min = Math.min( x0, x1, x2 );
  20526. // 0.9 is somewhat arbitrary
  20527. if ( max > 0.9 && min < 0.1 ) {
  20528. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20529. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20530. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20531. }
  20532. }
  20533. }
  20534. function pushVertex( vertex ) {
  20535. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20536. }
  20537. function getVertexByIndex( index, vertex ) {
  20538. const stride = index * 3;
  20539. vertex.x = vertices[ stride + 0 ];
  20540. vertex.y = vertices[ stride + 1 ];
  20541. vertex.z = vertices[ stride + 2 ];
  20542. }
  20543. function correctUVs() {
  20544. const a = new Vector3();
  20545. const b = new Vector3();
  20546. const c = new Vector3();
  20547. const centroid = new Vector3();
  20548. const uvA = new Vector2();
  20549. const uvB = new Vector2();
  20550. const uvC = new Vector2();
  20551. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20552. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20553. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20554. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20555. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20556. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20557. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20558. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20559. const azi = azimuth( centroid );
  20560. correctUV( uvA, j + 0, a, azi );
  20561. correctUV( uvB, j + 2, b, azi );
  20562. correctUV( uvC, j + 4, c, azi );
  20563. }
  20564. }
  20565. function correctUV( uv, stride, vector, azimuth ) {
  20566. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20567. uvBuffer[ stride ] = uv.x - 1;
  20568. }
  20569. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20570. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20571. }
  20572. }
  20573. // Angle around the Y axis, counter-clockwise when looking from above.
  20574. function azimuth( vector ) {
  20575. return Math.atan2( vector.z, - vector.x );
  20576. }
  20577. // Angle above the XZ plane.
  20578. function inclination( vector ) {
  20579. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20580. }
  20581. }
  20582. copy( source ) {
  20583. super.copy( source );
  20584. this.parameters = Object.assign( {}, source.parameters );
  20585. return this;
  20586. }
  20587. static fromJSON( data ) {
  20588. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20589. }
  20590. }
  20591. class DodecahedronGeometry extends PolyhedronGeometry {
  20592. constructor( radius = 1, detail = 0 ) {
  20593. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20594. const r = 1 / t;
  20595. const vertices = [
  20596. // (±1, ±1, ±1)
  20597. - 1, - 1, - 1, - 1, - 1, 1,
  20598. - 1, 1, - 1, - 1, 1, 1,
  20599. 1, - 1, - 1, 1, - 1, 1,
  20600. 1, 1, - 1, 1, 1, 1,
  20601. // (0, ±1/φ, ±φ)
  20602. 0, - r, - t, 0, - r, t,
  20603. 0, r, - t, 0, r, t,
  20604. // (±1/φ, ±φ, 0)
  20605. - r, - t, 0, - r, t, 0,
  20606. r, - t, 0, r, t, 0,
  20607. // (±φ, 0, ±1/φ)
  20608. - t, 0, - r, t, 0, - r,
  20609. - t, 0, r, t, 0, r
  20610. ];
  20611. const indices = [
  20612. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20613. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20614. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20615. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20616. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20617. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20618. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20619. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20620. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20621. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20622. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20623. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20624. ];
  20625. super( vertices, indices, radius, detail );
  20626. this.type = 'DodecahedronGeometry';
  20627. this.parameters = {
  20628. radius: radius,
  20629. detail: detail
  20630. };
  20631. }
  20632. static fromJSON( data ) {
  20633. return new DodecahedronGeometry( data.radius, data.detail );
  20634. }
  20635. }
  20636. const _v0 = /*@__PURE__*/ new Vector3();
  20637. const _v1$1 = /*@__PURE__*/ new Vector3();
  20638. const _normal = /*@__PURE__*/ new Vector3();
  20639. const _triangle = /*@__PURE__*/ new Triangle();
  20640. class EdgesGeometry extends BufferGeometry {
  20641. constructor( geometry = null, thresholdAngle = 1 ) {
  20642. super();
  20643. this.type = 'EdgesGeometry';
  20644. this.parameters = {
  20645. geometry: geometry,
  20646. thresholdAngle: thresholdAngle
  20647. };
  20648. if ( geometry !== null ) {
  20649. const precisionPoints = 4;
  20650. const precision = Math.pow( 10, precisionPoints );
  20651. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20652. const indexAttr = geometry.getIndex();
  20653. const positionAttr = geometry.getAttribute( 'position' );
  20654. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20655. const indexArr = [ 0, 0, 0 ];
  20656. const vertKeys = [ 'a', 'b', 'c' ];
  20657. const hashes = new Array( 3 );
  20658. const edgeData = {};
  20659. const vertices = [];
  20660. for ( let i = 0; i < indexCount; i += 3 ) {
  20661. if ( indexAttr ) {
  20662. indexArr[ 0 ] = indexAttr.getX( i );
  20663. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20664. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20665. } else {
  20666. indexArr[ 0 ] = i;
  20667. indexArr[ 1 ] = i + 1;
  20668. indexArr[ 2 ] = i + 2;
  20669. }
  20670. const { a, b, c } = _triangle;
  20671. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20672. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20673. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20674. _triangle.getNormal( _normal );
  20675. // create hashes for the edge from the vertices
  20676. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20677. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20678. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20679. // skip degenerate triangles
  20680. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20681. continue;
  20682. }
  20683. // iterate over every edge
  20684. for ( let j = 0; j < 3; j ++ ) {
  20685. // get the first and next vertex making up the edge
  20686. const jNext = ( j + 1 ) % 3;
  20687. const vecHash0 = hashes[ j ];
  20688. const vecHash1 = hashes[ jNext ];
  20689. const v0 = _triangle[ vertKeys[ j ] ];
  20690. const v1 = _triangle[ vertKeys[ jNext ] ];
  20691. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20692. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20693. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20694. // if we found a sibling edge add it into the vertex array if
  20695. // it meets the angle threshold and delete the edge from the map.
  20696. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20697. vertices.push( v0.x, v0.y, v0.z );
  20698. vertices.push( v1.x, v1.y, v1.z );
  20699. }
  20700. edgeData[ reverseHash ] = null;
  20701. } else if ( ! ( hash in edgeData ) ) {
  20702. // if we've already got an edge here then skip adding a new one
  20703. edgeData[ hash ] = {
  20704. index0: indexArr[ j ],
  20705. index1: indexArr[ jNext ],
  20706. normal: _normal.clone(),
  20707. };
  20708. }
  20709. }
  20710. }
  20711. // iterate over all remaining, unmatched edges and add them to the vertex array
  20712. for ( const key in edgeData ) {
  20713. if ( edgeData[ key ] ) {
  20714. const { index0, index1 } = edgeData[ key ];
  20715. _v0.fromBufferAttribute( positionAttr, index0 );
  20716. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20717. vertices.push( _v0.x, _v0.y, _v0.z );
  20718. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20719. }
  20720. }
  20721. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20722. }
  20723. }
  20724. copy( source ) {
  20725. super.copy( source );
  20726. this.parameters = Object.assign( {}, source.parameters );
  20727. return this;
  20728. }
  20729. }
  20730. class Shape extends Path {
  20731. constructor( points ) {
  20732. super( points );
  20733. this.uuid = generateUUID();
  20734. this.type = 'Shape';
  20735. this.holes = [];
  20736. }
  20737. getPointsHoles( divisions ) {
  20738. const holesPts = [];
  20739. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20740. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20741. }
  20742. return holesPts;
  20743. }
  20744. // get points of shape and holes (keypoints based on segments parameter)
  20745. extractPoints( divisions ) {
  20746. return {
  20747. shape: this.getPoints( divisions ),
  20748. holes: this.getPointsHoles( divisions )
  20749. };
  20750. }
  20751. copy( source ) {
  20752. super.copy( source );
  20753. this.holes = [];
  20754. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20755. const hole = source.holes[ i ];
  20756. this.holes.push( hole.clone() );
  20757. }
  20758. return this;
  20759. }
  20760. toJSON() {
  20761. const data = super.toJSON();
  20762. data.uuid = this.uuid;
  20763. data.holes = [];
  20764. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20765. const hole = this.holes[ i ];
  20766. data.holes.push( hole.toJSON() );
  20767. }
  20768. return data;
  20769. }
  20770. fromJSON( json ) {
  20771. super.fromJSON( json );
  20772. this.uuid = json.uuid;
  20773. this.holes = [];
  20774. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20775. const hole = json.holes[ i ];
  20776. this.holes.push( new Path().fromJSON( hole ) );
  20777. }
  20778. return this;
  20779. }
  20780. }
  20781. /**
  20782. * Port from https://github.com/mapbox/earcut (v2.2.4)
  20783. */
  20784. const Earcut = {
  20785. triangulate: function ( data, holeIndices, dim = 2 ) {
  20786. const hasHoles = holeIndices && holeIndices.length;
  20787. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20788. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20789. const triangles = [];
  20790. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20791. let minX, minY, maxX, maxY, x, y, invSize;
  20792. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20793. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20794. if ( data.length > 80 * dim ) {
  20795. minX = maxX = data[ 0 ];
  20796. minY = maxY = data[ 1 ];
  20797. for ( let i = dim; i < outerLen; i += dim ) {
  20798. x = data[ i ];
  20799. y = data[ i + 1 ];
  20800. if ( x < minX ) minX = x;
  20801. if ( y < minY ) minY = y;
  20802. if ( x > maxX ) maxX = x;
  20803. if ( y > maxY ) maxY = y;
  20804. }
  20805. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20806. invSize = Math.max( maxX - minX, maxY - minY );
  20807. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20808. }
  20809. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  20810. return triangles;
  20811. }
  20812. };
  20813. // create a circular doubly linked list from polygon points in the specified winding order
  20814. function linkedList( data, start, end, dim, clockwise ) {
  20815. let i, last;
  20816. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20817. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20818. } else {
  20819. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20820. }
  20821. if ( last && equals( last, last.next ) ) {
  20822. removeNode( last );
  20823. last = last.next;
  20824. }
  20825. return last;
  20826. }
  20827. // eliminate colinear or duplicate points
  20828. function filterPoints( start, end ) {
  20829. if ( ! start ) return start;
  20830. if ( ! end ) end = start;
  20831. let p = start,
  20832. again;
  20833. do {
  20834. again = false;
  20835. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20836. removeNode( p );
  20837. p = end = p.prev;
  20838. if ( p === p.next ) break;
  20839. again = true;
  20840. } else {
  20841. p = p.next;
  20842. }
  20843. } while ( again || p !== end );
  20844. return end;
  20845. }
  20846. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20847. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20848. if ( ! ear ) return;
  20849. // interlink polygon nodes in z-order
  20850. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20851. let stop = ear,
  20852. prev, next;
  20853. // iterate through ears, slicing them one by one
  20854. while ( ear.prev !== ear.next ) {
  20855. prev = ear.prev;
  20856. next = ear.next;
  20857. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20858. // cut off the triangle
  20859. triangles.push( prev.i / dim | 0 );
  20860. triangles.push( ear.i / dim | 0 );
  20861. triangles.push( next.i / dim | 0 );
  20862. removeNode( ear );
  20863. // skipping the next vertex leads to less sliver triangles
  20864. ear = next.next;
  20865. stop = next.next;
  20866. continue;
  20867. }
  20868. ear = next;
  20869. // if we looped through the whole remaining polygon and can't find any more ears
  20870. if ( ear === stop ) {
  20871. // try filtering points and slicing again
  20872. if ( ! pass ) {
  20873. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20874. // if this didn't work, try curing all small self-intersections locally
  20875. } else if ( pass === 1 ) {
  20876. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20877. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20878. // as a last resort, try splitting the remaining polygon into two
  20879. } else if ( pass === 2 ) {
  20880. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20881. }
  20882. break;
  20883. }
  20884. }
  20885. }
  20886. // check whether a polygon node forms a valid ear with adjacent nodes
  20887. function isEar( ear ) {
  20888. const a = ear.prev,
  20889. b = ear,
  20890. c = ear.next;
  20891. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20892. // now make sure we don't have other points inside the potential ear
  20893. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20894. // triangle bbox; min & max are calculated like this for speed
  20895. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20896. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20897. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20898. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20899. let p = c.next;
  20900. while ( p !== a ) {
  20901. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  20902. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  20903. area( p.prev, p, p.next ) >= 0 ) return false;
  20904. p = p.next;
  20905. }
  20906. return true;
  20907. }
  20908. function isEarHashed( ear, minX, minY, invSize ) {
  20909. const a = ear.prev,
  20910. b = ear,
  20911. c = ear.next;
  20912. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20913. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20914. // triangle bbox; min & max are calculated like this for speed
  20915. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20916. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20917. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20918. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20919. // z-order range for the current triangle bbox;
  20920. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  20921. maxZ = zOrder( x1, y1, minX, minY, invSize );
  20922. let p = ear.prevZ,
  20923. n = ear.nextZ;
  20924. // look for points inside the triangle in both directions
  20925. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20926. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20927. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20928. p = p.prevZ;
  20929. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20930. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20931. n = n.nextZ;
  20932. }
  20933. // look for remaining points in decreasing z-order
  20934. while ( p && p.z >= minZ ) {
  20935. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20936. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20937. p = p.prevZ;
  20938. }
  20939. // look for remaining points in increasing z-order
  20940. while ( n && n.z <= maxZ ) {
  20941. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20942. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20943. n = n.nextZ;
  20944. }
  20945. return true;
  20946. }
  20947. // go through all polygon nodes and cure small local self-intersections
  20948. function cureLocalIntersections( start, triangles, dim ) {
  20949. let p = start;
  20950. do {
  20951. const a = p.prev,
  20952. b = p.next.next;
  20953. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20954. triangles.push( a.i / dim | 0 );
  20955. triangles.push( p.i / dim | 0 );
  20956. triangles.push( b.i / dim | 0 );
  20957. // remove two nodes involved
  20958. removeNode( p );
  20959. removeNode( p.next );
  20960. p = start = b;
  20961. }
  20962. p = p.next;
  20963. } while ( p !== start );
  20964. return filterPoints( p );
  20965. }
  20966. // try splitting polygon into two and triangulate them independently
  20967. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20968. // look for a valid diagonal that divides the polygon into two
  20969. let a = start;
  20970. do {
  20971. let b = a.next.next;
  20972. while ( b !== a.prev ) {
  20973. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20974. // split the polygon in two by the diagonal
  20975. let c = splitPolygon( a, b );
  20976. // filter colinear points around the cuts
  20977. a = filterPoints( a, a.next );
  20978. c = filterPoints( c, c.next );
  20979. // run earcut on each half
  20980. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  20981. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  20982. return;
  20983. }
  20984. b = b.next;
  20985. }
  20986. a = a.next;
  20987. } while ( a !== start );
  20988. }
  20989. // link every hole into the outer loop, producing a single-ring polygon without holes
  20990. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20991. const queue = [];
  20992. let i, len, start, end, list;
  20993. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20994. start = holeIndices[ i ] * dim;
  20995. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20996. list = linkedList( data, start, end, dim, false );
  20997. if ( list === list.next ) list.steiner = true;
  20998. queue.push( getLeftmost( list ) );
  20999. }
  21000. queue.sort( compareX );
  21001. // process holes from left to right
  21002. for ( i = 0; i < queue.length; i ++ ) {
  21003. outerNode = eliminateHole( queue[ i ], outerNode );
  21004. }
  21005. return outerNode;
  21006. }
  21007. function compareX( a, b ) {
  21008. return a.x - b.x;
  21009. }
  21010. // find a bridge between vertices that connects hole with an outer ring and link it
  21011. function eliminateHole( hole, outerNode ) {
  21012. const bridge = findHoleBridge( hole, outerNode );
  21013. if ( ! bridge ) {
  21014. return outerNode;
  21015. }
  21016. const bridgeReverse = splitPolygon( bridge, hole );
  21017. // filter collinear points around the cuts
  21018. filterPoints( bridgeReverse, bridgeReverse.next );
  21019. return filterPoints( bridge, bridge.next );
  21020. }
  21021. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  21022. function findHoleBridge( hole, outerNode ) {
  21023. let p = outerNode,
  21024. qx = - Infinity,
  21025. m;
  21026. const hx = hole.x, hy = hole.y;
  21027. // find a segment intersected by a ray from the hole's leftmost point to the left;
  21028. // segment's endpoint with lesser x will be potential connection point
  21029. do {
  21030. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  21031. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  21032. if ( x <= hx && x > qx ) {
  21033. qx = x;
  21034. m = p.x < p.next.x ? p : p.next;
  21035. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  21036. }
  21037. }
  21038. p = p.next;
  21039. } while ( p !== outerNode );
  21040. if ( ! m ) return null;
  21041. // look for points inside the triangle of hole point, segment intersection and endpoint;
  21042. // if there are no points found, we have a valid connection;
  21043. // otherwise choose the point of the minimum angle with the ray as connection point
  21044. const stop = m,
  21045. mx = m.x,
  21046. my = m.y;
  21047. let tanMin = Infinity, tan;
  21048. p = m;
  21049. do {
  21050. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  21051. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  21052. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  21053. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  21054. m = p;
  21055. tanMin = tan;
  21056. }
  21057. }
  21058. p = p.next;
  21059. } while ( p !== stop );
  21060. return m;
  21061. }
  21062. // whether sector in vertex m contains sector in vertex p in the same coordinates
  21063. function sectorContainsSector( m, p ) {
  21064. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  21065. }
  21066. // interlink polygon nodes in z-order
  21067. function indexCurve( start, minX, minY, invSize ) {
  21068. let p = start;
  21069. do {
  21070. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  21071. p.prevZ = p.prev;
  21072. p.nextZ = p.next;
  21073. p = p.next;
  21074. } while ( p !== start );
  21075. p.prevZ.nextZ = null;
  21076. p.prevZ = null;
  21077. sortLinked( p );
  21078. }
  21079. // Simon Tatham's linked list merge sort algorithm
  21080. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  21081. function sortLinked( list ) {
  21082. let i, p, q, e, tail, numMerges, pSize, qSize,
  21083. inSize = 1;
  21084. do {
  21085. p = list;
  21086. list = null;
  21087. tail = null;
  21088. numMerges = 0;
  21089. while ( p ) {
  21090. numMerges ++;
  21091. q = p;
  21092. pSize = 0;
  21093. for ( i = 0; i < inSize; i ++ ) {
  21094. pSize ++;
  21095. q = q.nextZ;
  21096. if ( ! q ) break;
  21097. }
  21098. qSize = inSize;
  21099. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  21100. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  21101. e = p;
  21102. p = p.nextZ;
  21103. pSize --;
  21104. } else {
  21105. e = q;
  21106. q = q.nextZ;
  21107. qSize --;
  21108. }
  21109. if ( tail ) tail.nextZ = e;
  21110. else list = e;
  21111. e.prevZ = tail;
  21112. tail = e;
  21113. }
  21114. p = q;
  21115. }
  21116. tail.nextZ = null;
  21117. inSize *= 2;
  21118. } while ( numMerges > 1 );
  21119. return list;
  21120. }
  21121. // z-order of a point given coords and inverse of the longer side of data bbox
  21122. function zOrder( x, y, minX, minY, invSize ) {
  21123. // coords are transformed into non-negative 15-bit integer range
  21124. x = ( x - minX ) * invSize | 0;
  21125. y = ( y - minY ) * invSize | 0;
  21126. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  21127. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  21128. x = ( x | ( x << 2 ) ) & 0x33333333;
  21129. x = ( x | ( x << 1 ) ) & 0x55555555;
  21130. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  21131. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  21132. y = ( y | ( y << 2 ) ) & 0x33333333;
  21133. y = ( y | ( y << 1 ) ) & 0x55555555;
  21134. return x | ( y << 1 );
  21135. }
  21136. // find the leftmost node of a polygon ring
  21137. function getLeftmost( start ) {
  21138. let p = start,
  21139. leftmost = start;
  21140. do {
  21141. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  21142. p = p.next;
  21143. } while ( p !== start );
  21144. return leftmost;
  21145. }
  21146. // check if a point lies within a convex triangle
  21147. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  21148. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  21149. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  21150. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  21151. }
  21152. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  21153. function isValidDiagonal( a, b ) {
  21154. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  21155. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  21156. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  21157. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  21158. }
  21159. // signed area of a triangle
  21160. function area( p, q, r ) {
  21161. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  21162. }
  21163. // check if two points are equal
  21164. function equals( p1, p2 ) {
  21165. return p1.x === p2.x && p1.y === p2.y;
  21166. }
  21167. // check if two segments intersect
  21168. function intersects( p1, q1, p2, q2 ) {
  21169. const o1 = sign( area( p1, q1, p2 ) );
  21170. const o2 = sign( area( p1, q1, q2 ) );
  21171. const o3 = sign( area( p2, q2, p1 ) );
  21172. const o4 = sign( area( p2, q2, q1 ) );
  21173. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  21174. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  21175. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  21176. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  21177. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  21178. return false;
  21179. }
  21180. // for collinear points p, q, r, check if point q lies on segment pr
  21181. function onSegment( p, q, r ) {
  21182. 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 );
  21183. }
  21184. function sign( num ) {
  21185. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  21186. }
  21187. // check if a polygon diagonal intersects any polygon segments
  21188. function intersectsPolygon( a, b ) {
  21189. let p = a;
  21190. do {
  21191. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  21192. intersects( p, p.next, a, b ) ) return true;
  21193. p = p.next;
  21194. } while ( p !== a );
  21195. return false;
  21196. }
  21197. // check if a polygon diagonal is locally inside the polygon
  21198. function locallyInside( a, b ) {
  21199. return area( a.prev, a, a.next ) < 0 ?
  21200. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  21201. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  21202. }
  21203. // check if the middle point of a polygon diagonal is inside the polygon
  21204. function middleInside( a, b ) {
  21205. let p = a,
  21206. inside = false;
  21207. const px = ( a.x + b.x ) / 2,
  21208. py = ( a.y + b.y ) / 2;
  21209. do {
  21210. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  21211. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  21212. inside = ! inside;
  21213. p = p.next;
  21214. } while ( p !== a );
  21215. return inside;
  21216. }
  21217. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  21218. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  21219. function splitPolygon( a, b ) {
  21220. const a2 = new Node( a.i, a.x, a.y ),
  21221. b2 = new Node( b.i, b.x, b.y ),
  21222. an = a.next,
  21223. bp = b.prev;
  21224. a.next = b;
  21225. b.prev = a;
  21226. a2.next = an;
  21227. an.prev = a2;
  21228. b2.next = a2;
  21229. a2.prev = b2;
  21230. bp.next = b2;
  21231. b2.prev = bp;
  21232. return b2;
  21233. }
  21234. // create a node and optionally link it with previous one (in a circular doubly linked list)
  21235. function insertNode( i, x, y, last ) {
  21236. const p = new Node( i, x, y );
  21237. if ( ! last ) {
  21238. p.prev = p;
  21239. p.next = p;
  21240. } else {
  21241. p.next = last.next;
  21242. p.prev = last;
  21243. last.next.prev = p;
  21244. last.next = p;
  21245. }
  21246. return p;
  21247. }
  21248. function removeNode( p ) {
  21249. p.next.prev = p.prev;
  21250. p.prev.next = p.next;
  21251. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  21252. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  21253. }
  21254. function Node( i, x, y ) {
  21255. // vertex index in coordinates array
  21256. this.i = i;
  21257. // vertex coordinates
  21258. this.x = x;
  21259. this.y = y;
  21260. // previous and next vertex nodes in a polygon ring
  21261. this.prev = null;
  21262. this.next = null;
  21263. // z-order curve value
  21264. this.z = 0;
  21265. // previous and next nodes in z-order
  21266. this.prevZ = null;
  21267. this.nextZ = null;
  21268. // indicates whether this is a steiner point
  21269. this.steiner = false;
  21270. }
  21271. function signedArea( data, start, end, dim ) {
  21272. let sum = 0;
  21273. for ( let i = start, j = end - dim; i < end; i += dim ) {
  21274. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  21275. j = i;
  21276. }
  21277. return sum;
  21278. }
  21279. class ShapeUtils {
  21280. // calculate area of the contour polygon
  21281. static area( contour ) {
  21282. const n = contour.length;
  21283. let a = 0.0;
  21284. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  21285. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  21286. }
  21287. return a * 0.5;
  21288. }
  21289. static isClockWise( pts ) {
  21290. return ShapeUtils.area( pts ) < 0;
  21291. }
  21292. static triangulateShape( contour, holes ) {
  21293. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  21294. const holeIndices = []; // array of hole indices
  21295. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  21296. removeDupEndPts( contour );
  21297. addContour( vertices, contour );
  21298. //
  21299. let holeIndex = contour.length;
  21300. holes.forEach( removeDupEndPts );
  21301. for ( let i = 0; i < holes.length; i ++ ) {
  21302. holeIndices.push( holeIndex );
  21303. holeIndex += holes[ i ].length;
  21304. addContour( vertices, holes[ i ] );
  21305. }
  21306. //
  21307. const triangles = Earcut.triangulate( vertices, holeIndices );
  21308. //
  21309. for ( let i = 0; i < triangles.length; i += 3 ) {
  21310. faces.push( triangles.slice( i, i + 3 ) );
  21311. }
  21312. return faces;
  21313. }
  21314. }
  21315. function removeDupEndPts( points ) {
  21316. const l = points.length;
  21317. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  21318. points.pop();
  21319. }
  21320. }
  21321. function addContour( vertices, contour ) {
  21322. for ( let i = 0; i < contour.length; i ++ ) {
  21323. vertices.push( contour[ i ].x );
  21324. vertices.push( contour[ i ].y );
  21325. }
  21326. }
  21327. /**
  21328. * Creates extruded geometry from a path shape.
  21329. *
  21330. * parameters = {
  21331. *
  21332. * curveSegments: <int>, // number of points on the curves
  21333. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21334. * depth: <float>, // Depth to extrude the shape
  21335. *
  21336. * bevelEnabled: <bool>, // turn on bevel
  21337. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21338. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21339. * bevelOffset: <float>, // how far from shape outline does bevel start
  21340. * bevelSegments: <int>, // number of bevel layers
  21341. *
  21342. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21343. *
  21344. * UVGenerator: <Object> // object that provides UV generator functions
  21345. *
  21346. * }
  21347. */
  21348. class ExtrudeGeometry extends BufferGeometry {
  21349. constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) {
  21350. super();
  21351. this.type = 'ExtrudeGeometry';
  21352. this.parameters = {
  21353. shapes: shapes,
  21354. options: options
  21355. };
  21356. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21357. const scope = this;
  21358. const verticesArray = [];
  21359. const uvArray = [];
  21360. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21361. const shape = shapes[ i ];
  21362. addShape( shape );
  21363. }
  21364. // build geometry
  21365. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21366. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21367. this.computeVertexNormals();
  21368. // functions
  21369. function addShape( shape ) {
  21370. const placeholder = [];
  21371. // options
  21372. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21373. const steps = options.steps !== undefined ? options.steps : 1;
  21374. const depth = options.depth !== undefined ? options.depth : 1;
  21375. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21376. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21377. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21378. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21379. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21380. const extrudePath = options.extrudePath;
  21381. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21382. //
  21383. let extrudePts, extrudeByPath = false;
  21384. let splineTube, binormal, normal, position2;
  21385. if ( extrudePath ) {
  21386. extrudePts = extrudePath.getSpacedPoints( steps );
  21387. extrudeByPath = true;
  21388. bevelEnabled = false; // bevels not supported for path extrusion
  21389. // SETUP TNB variables
  21390. // TODO1 - have a .isClosed in spline?
  21391. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21392. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21393. binormal = new Vector3();
  21394. normal = new Vector3();
  21395. position2 = new Vector3();
  21396. }
  21397. // Safeguards if bevels are not enabled
  21398. if ( ! bevelEnabled ) {
  21399. bevelSegments = 0;
  21400. bevelThickness = 0;
  21401. bevelSize = 0;
  21402. bevelOffset = 0;
  21403. }
  21404. // Variables initialization
  21405. const shapePoints = shape.extractPoints( curveSegments );
  21406. let vertices = shapePoints.shape;
  21407. const holes = shapePoints.holes;
  21408. const reverse = ! ShapeUtils.isClockWise( vertices );
  21409. if ( reverse ) {
  21410. vertices = vertices.reverse();
  21411. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21412. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21413. const ahole = holes[ h ];
  21414. if ( ShapeUtils.isClockWise( ahole ) ) {
  21415. holes[ h ] = ahole.reverse();
  21416. }
  21417. }
  21418. }
  21419. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21420. /* Vertices */
  21421. const contour = vertices; // vertices has all points but contour has only points of circumference
  21422. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21423. const ahole = holes[ h ];
  21424. vertices = vertices.concat( ahole );
  21425. }
  21426. function scalePt2( pt, vec, size ) {
  21427. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21428. return pt.clone().addScaledVector( vec, size );
  21429. }
  21430. const vlen = vertices.length, flen = faces.length;
  21431. // Find directions for point movement
  21432. function getBevelVec( inPt, inPrev, inNext ) {
  21433. // computes for inPt the corresponding point inPt' on a new contour
  21434. // shifted by 1 unit (length of normalized vector) to the left
  21435. // if we walk along contour clockwise, this new contour is outside the old one
  21436. //
  21437. // inPt' is the intersection of the two lines parallel to the two
  21438. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21439. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21440. // good reading for geometry algorithms (here: line-line intersection)
  21441. // http://geomalgorithms.com/a05-_intersect-1.html
  21442. const v_prev_x = inPt.x - inPrev.x,
  21443. v_prev_y = inPt.y - inPrev.y;
  21444. const v_next_x = inNext.x - inPt.x,
  21445. v_next_y = inNext.y - inPt.y;
  21446. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21447. // check for collinear edges
  21448. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21449. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21450. // not collinear
  21451. // length of vectors for normalizing
  21452. const v_prev_len = Math.sqrt( v_prev_lensq );
  21453. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21454. // shift adjacent points by unit vectors to the left
  21455. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21456. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21457. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21458. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21459. // scaling factor for v_prev to intersection point
  21460. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21461. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21462. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21463. // vector from inPt to intersection point
  21464. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21465. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21466. // Don't normalize!, otherwise sharp corners become ugly
  21467. // but prevent crazy spikes
  21468. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21469. if ( v_trans_lensq <= 2 ) {
  21470. return new Vector2( v_trans_x, v_trans_y );
  21471. } else {
  21472. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21473. }
  21474. } else {
  21475. // handle special case of collinear edges
  21476. let direction_eq = false; // assumes: opposite
  21477. if ( v_prev_x > Number.EPSILON ) {
  21478. if ( v_next_x > Number.EPSILON ) {
  21479. direction_eq = true;
  21480. }
  21481. } else {
  21482. if ( v_prev_x < - Number.EPSILON ) {
  21483. if ( v_next_x < - Number.EPSILON ) {
  21484. direction_eq = true;
  21485. }
  21486. } else {
  21487. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21488. direction_eq = true;
  21489. }
  21490. }
  21491. }
  21492. if ( direction_eq ) {
  21493. // console.log("Warning: lines are a straight sequence");
  21494. v_trans_x = - v_prev_y;
  21495. v_trans_y = v_prev_x;
  21496. shrink_by = Math.sqrt( v_prev_lensq );
  21497. } else {
  21498. // console.log("Warning: lines are a straight spike");
  21499. v_trans_x = v_prev_x;
  21500. v_trans_y = v_prev_y;
  21501. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21502. }
  21503. }
  21504. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21505. }
  21506. const contourMovements = [];
  21507. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21508. if ( j === il ) j = 0;
  21509. if ( k === il ) k = 0;
  21510. // (j)---(i)---(k)
  21511. // console.log('i,j,k', i, j , k)
  21512. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21513. }
  21514. const holesMovements = [];
  21515. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21516. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21517. const ahole = holes[ h ];
  21518. oneHoleMovements = [];
  21519. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21520. if ( j === il ) j = 0;
  21521. if ( k === il ) k = 0;
  21522. // (j)---(i)---(k)
  21523. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21524. }
  21525. holesMovements.push( oneHoleMovements );
  21526. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21527. }
  21528. // Loop bevelSegments, 1 for the front, 1 for the back
  21529. for ( let b = 0; b < bevelSegments; b ++ ) {
  21530. //for ( b = bevelSegments; b > 0; b -- ) {
  21531. const t = b / bevelSegments;
  21532. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21533. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21534. // contract shape
  21535. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21536. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21537. v( vert.x, vert.y, - z );
  21538. }
  21539. // expand holes
  21540. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21541. const ahole = holes[ h ];
  21542. oneHoleMovements = holesMovements[ h ];
  21543. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21544. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21545. v( vert.x, vert.y, - z );
  21546. }
  21547. }
  21548. }
  21549. const bs = bevelSize + bevelOffset;
  21550. // Back facing vertices
  21551. for ( let i = 0; i < vlen; i ++ ) {
  21552. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21553. if ( ! extrudeByPath ) {
  21554. v( vert.x, vert.y, 0 );
  21555. } else {
  21556. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21557. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21558. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21559. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21560. v( position2.x, position2.y, position2.z );
  21561. }
  21562. }
  21563. // Add stepped vertices...
  21564. // Including front facing vertices
  21565. for ( let s = 1; s <= steps; s ++ ) {
  21566. for ( let i = 0; i < vlen; i ++ ) {
  21567. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21568. if ( ! extrudeByPath ) {
  21569. v( vert.x, vert.y, depth / steps * s );
  21570. } else {
  21571. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21572. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21573. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21574. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21575. v( position2.x, position2.y, position2.z );
  21576. }
  21577. }
  21578. }
  21579. // Add bevel segments planes
  21580. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21581. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21582. const t = b / bevelSegments;
  21583. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21584. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21585. // contract shape
  21586. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21587. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21588. v( vert.x, vert.y, depth + z );
  21589. }
  21590. // expand holes
  21591. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21592. const ahole = holes[ h ];
  21593. oneHoleMovements = holesMovements[ h ];
  21594. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21595. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21596. if ( ! extrudeByPath ) {
  21597. v( vert.x, vert.y, depth + z );
  21598. } else {
  21599. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21600. }
  21601. }
  21602. }
  21603. }
  21604. /* Faces */
  21605. // Top and bottom faces
  21606. buildLidFaces();
  21607. // Sides faces
  21608. buildSideFaces();
  21609. ///// Internal functions
  21610. function buildLidFaces() {
  21611. const start = verticesArray.length / 3;
  21612. if ( bevelEnabled ) {
  21613. let layer = 0; // steps + 1
  21614. let offset = vlen * layer;
  21615. // Bottom faces
  21616. for ( let i = 0; i < flen; i ++ ) {
  21617. const face = faces[ i ];
  21618. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21619. }
  21620. layer = steps + bevelSegments * 2;
  21621. offset = vlen * layer;
  21622. // Top faces
  21623. for ( let i = 0; i < flen; i ++ ) {
  21624. const face = faces[ i ];
  21625. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21626. }
  21627. } else {
  21628. // Bottom faces
  21629. for ( let i = 0; i < flen; i ++ ) {
  21630. const face = faces[ i ];
  21631. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21632. }
  21633. // Top faces
  21634. for ( let i = 0; i < flen; i ++ ) {
  21635. const face = faces[ i ];
  21636. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21637. }
  21638. }
  21639. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21640. }
  21641. // Create faces for the z-sides of the shape
  21642. function buildSideFaces() {
  21643. const start = verticesArray.length / 3;
  21644. let layeroffset = 0;
  21645. sidewalls( contour, layeroffset );
  21646. layeroffset += contour.length;
  21647. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21648. const ahole = holes[ h ];
  21649. sidewalls( ahole, layeroffset );
  21650. //, true
  21651. layeroffset += ahole.length;
  21652. }
  21653. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21654. }
  21655. function sidewalls( contour, layeroffset ) {
  21656. let i = contour.length;
  21657. while ( -- i >= 0 ) {
  21658. const j = i;
  21659. let k = i - 1;
  21660. if ( k < 0 ) k = contour.length - 1;
  21661. //console.log('b', i,j, i-1, k,vertices.length);
  21662. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21663. const slen1 = vlen * s;
  21664. const slen2 = vlen * ( s + 1 );
  21665. const a = layeroffset + j + slen1,
  21666. b = layeroffset + k + slen1,
  21667. c = layeroffset + k + slen2,
  21668. d = layeroffset + j + slen2;
  21669. f4( a, b, c, d );
  21670. }
  21671. }
  21672. }
  21673. function v( x, y, z ) {
  21674. placeholder.push( x );
  21675. placeholder.push( y );
  21676. placeholder.push( z );
  21677. }
  21678. function f3( a, b, c ) {
  21679. addVertex( a );
  21680. addVertex( b );
  21681. addVertex( c );
  21682. const nextIndex = verticesArray.length / 3;
  21683. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21684. addUV( uvs[ 0 ] );
  21685. addUV( uvs[ 1 ] );
  21686. addUV( uvs[ 2 ] );
  21687. }
  21688. function f4( a, b, c, d ) {
  21689. addVertex( a );
  21690. addVertex( b );
  21691. addVertex( d );
  21692. addVertex( b );
  21693. addVertex( c );
  21694. addVertex( d );
  21695. const nextIndex = verticesArray.length / 3;
  21696. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21697. addUV( uvs[ 0 ] );
  21698. addUV( uvs[ 1 ] );
  21699. addUV( uvs[ 3 ] );
  21700. addUV( uvs[ 1 ] );
  21701. addUV( uvs[ 2 ] );
  21702. addUV( uvs[ 3 ] );
  21703. }
  21704. function addVertex( index ) {
  21705. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21706. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21707. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21708. }
  21709. function addUV( vector2 ) {
  21710. uvArray.push( vector2.x );
  21711. uvArray.push( vector2.y );
  21712. }
  21713. }
  21714. }
  21715. copy( source ) {
  21716. super.copy( source );
  21717. this.parameters = Object.assign( {}, source.parameters );
  21718. return this;
  21719. }
  21720. toJSON() {
  21721. const data = super.toJSON();
  21722. const shapes = this.parameters.shapes;
  21723. const options = this.parameters.options;
  21724. return toJSON$1( shapes, options, data );
  21725. }
  21726. static fromJSON( data, shapes ) {
  21727. const geometryShapes = [];
  21728. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21729. const shape = shapes[ data.shapes[ j ] ];
  21730. geometryShapes.push( shape );
  21731. }
  21732. const extrudePath = data.options.extrudePath;
  21733. if ( extrudePath !== undefined ) {
  21734. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21735. }
  21736. return new ExtrudeGeometry( geometryShapes, data.options );
  21737. }
  21738. }
  21739. const WorldUVGenerator = {
  21740. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21741. const a_x = vertices[ indexA * 3 ];
  21742. const a_y = vertices[ indexA * 3 + 1 ];
  21743. const b_x = vertices[ indexB * 3 ];
  21744. const b_y = vertices[ indexB * 3 + 1 ];
  21745. const c_x = vertices[ indexC * 3 ];
  21746. const c_y = vertices[ indexC * 3 + 1 ];
  21747. return [
  21748. new Vector2( a_x, a_y ),
  21749. new Vector2( b_x, b_y ),
  21750. new Vector2( c_x, c_y )
  21751. ];
  21752. },
  21753. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21754. const a_x = vertices[ indexA * 3 ];
  21755. const a_y = vertices[ indexA * 3 + 1 ];
  21756. const a_z = vertices[ indexA * 3 + 2 ];
  21757. const b_x = vertices[ indexB * 3 ];
  21758. const b_y = vertices[ indexB * 3 + 1 ];
  21759. const b_z = vertices[ indexB * 3 + 2 ];
  21760. const c_x = vertices[ indexC * 3 ];
  21761. const c_y = vertices[ indexC * 3 + 1 ];
  21762. const c_z = vertices[ indexC * 3 + 2 ];
  21763. const d_x = vertices[ indexD * 3 ];
  21764. const d_y = vertices[ indexD * 3 + 1 ];
  21765. const d_z = vertices[ indexD * 3 + 2 ];
  21766. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21767. return [
  21768. new Vector2( a_x, 1 - a_z ),
  21769. new Vector2( b_x, 1 - b_z ),
  21770. new Vector2( c_x, 1 - c_z ),
  21771. new Vector2( d_x, 1 - d_z )
  21772. ];
  21773. } else {
  21774. return [
  21775. new Vector2( a_y, 1 - a_z ),
  21776. new Vector2( b_y, 1 - b_z ),
  21777. new Vector2( c_y, 1 - c_z ),
  21778. new Vector2( d_y, 1 - d_z )
  21779. ];
  21780. }
  21781. }
  21782. };
  21783. function toJSON$1( shapes, options, data ) {
  21784. data.shapes = [];
  21785. if ( Array.isArray( shapes ) ) {
  21786. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21787. const shape = shapes[ i ];
  21788. data.shapes.push( shape.uuid );
  21789. }
  21790. } else {
  21791. data.shapes.push( shapes.uuid );
  21792. }
  21793. data.options = Object.assign( {}, options );
  21794. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21795. return data;
  21796. }
  21797. class IcosahedronGeometry extends PolyhedronGeometry {
  21798. constructor( radius = 1, detail = 0 ) {
  21799. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21800. const vertices = [
  21801. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21802. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21803. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21804. ];
  21805. const indices = [
  21806. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21807. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21808. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21809. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21810. ];
  21811. super( vertices, indices, radius, detail );
  21812. this.type = 'IcosahedronGeometry';
  21813. this.parameters = {
  21814. radius: radius,
  21815. detail: detail
  21816. };
  21817. }
  21818. static fromJSON( data ) {
  21819. return new IcosahedronGeometry( data.radius, data.detail );
  21820. }
  21821. }
  21822. class OctahedronGeometry extends PolyhedronGeometry {
  21823. constructor( radius = 1, detail = 0 ) {
  21824. const vertices = [
  21825. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21826. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21827. ];
  21828. const indices = [
  21829. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21830. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21831. 1, 3, 4, 1, 4, 2
  21832. ];
  21833. super( vertices, indices, radius, detail );
  21834. this.type = 'OctahedronGeometry';
  21835. this.parameters = {
  21836. radius: radius,
  21837. detail: detail
  21838. };
  21839. }
  21840. static fromJSON( data ) {
  21841. return new OctahedronGeometry( data.radius, data.detail );
  21842. }
  21843. }
  21844. class RingGeometry extends BufferGeometry {
  21845. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21846. super();
  21847. this.type = 'RingGeometry';
  21848. this.parameters = {
  21849. innerRadius: innerRadius,
  21850. outerRadius: outerRadius,
  21851. thetaSegments: thetaSegments,
  21852. phiSegments: phiSegments,
  21853. thetaStart: thetaStart,
  21854. thetaLength: thetaLength
  21855. };
  21856. thetaSegments = Math.max( 3, thetaSegments );
  21857. phiSegments = Math.max( 1, phiSegments );
  21858. // buffers
  21859. const indices = [];
  21860. const vertices = [];
  21861. const normals = [];
  21862. const uvs = [];
  21863. // some helper variables
  21864. let radius = innerRadius;
  21865. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21866. const vertex = new Vector3();
  21867. const uv = new Vector2();
  21868. // generate vertices, normals and uvs
  21869. for ( let j = 0; j <= phiSegments; j ++ ) {
  21870. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21871. // values are generate from the inside of the ring to the outside
  21872. const segment = thetaStart + i / thetaSegments * thetaLength;
  21873. // vertex
  21874. vertex.x = radius * Math.cos( segment );
  21875. vertex.y = radius * Math.sin( segment );
  21876. vertices.push( vertex.x, vertex.y, vertex.z );
  21877. // normal
  21878. normals.push( 0, 0, 1 );
  21879. // uv
  21880. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21881. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21882. uvs.push( uv.x, uv.y );
  21883. }
  21884. // increase the radius for next row of vertices
  21885. radius += radiusStep;
  21886. }
  21887. // indices
  21888. for ( let j = 0; j < phiSegments; j ++ ) {
  21889. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21890. for ( let i = 0; i < thetaSegments; i ++ ) {
  21891. const segment = i + thetaSegmentLevel;
  21892. const a = segment;
  21893. const b = segment + thetaSegments + 1;
  21894. const c = segment + thetaSegments + 2;
  21895. const d = segment + 1;
  21896. // faces
  21897. indices.push( a, b, d );
  21898. indices.push( b, c, d );
  21899. }
  21900. }
  21901. // build geometry
  21902. this.setIndex( indices );
  21903. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21904. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21905. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21906. }
  21907. copy( source ) {
  21908. super.copy( source );
  21909. this.parameters = Object.assign( {}, source.parameters );
  21910. return this;
  21911. }
  21912. static fromJSON( data ) {
  21913. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21914. }
  21915. }
  21916. class ShapeGeometry extends BufferGeometry {
  21917. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  21918. super();
  21919. this.type = 'ShapeGeometry';
  21920. this.parameters = {
  21921. shapes: shapes,
  21922. curveSegments: curveSegments
  21923. };
  21924. // buffers
  21925. const indices = [];
  21926. const vertices = [];
  21927. const normals = [];
  21928. const uvs = [];
  21929. // helper variables
  21930. let groupStart = 0;
  21931. let groupCount = 0;
  21932. // allow single and array values for "shapes" parameter
  21933. if ( Array.isArray( shapes ) === false ) {
  21934. addShape( shapes );
  21935. } else {
  21936. for ( let i = 0; i < shapes.length; i ++ ) {
  21937. addShape( shapes[ i ] );
  21938. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21939. groupStart += groupCount;
  21940. groupCount = 0;
  21941. }
  21942. }
  21943. // build geometry
  21944. this.setIndex( indices );
  21945. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21946. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21947. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21948. // helper functions
  21949. function addShape( shape ) {
  21950. const indexOffset = vertices.length / 3;
  21951. const points = shape.extractPoints( curveSegments );
  21952. let shapeVertices = points.shape;
  21953. const shapeHoles = points.holes;
  21954. // check direction of vertices
  21955. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21956. shapeVertices = shapeVertices.reverse();
  21957. }
  21958. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21959. const shapeHole = shapeHoles[ i ];
  21960. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21961. shapeHoles[ i ] = shapeHole.reverse();
  21962. }
  21963. }
  21964. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21965. // join vertices of inner and outer paths to a single array
  21966. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21967. const shapeHole = shapeHoles[ i ];
  21968. shapeVertices = shapeVertices.concat( shapeHole );
  21969. }
  21970. // vertices, normals, uvs
  21971. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21972. const vertex = shapeVertices[ i ];
  21973. vertices.push( vertex.x, vertex.y, 0 );
  21974. normals.push( 0, 0, 1 );
  21975. uvs.push( vertex.x, vertex.y ); // world uvs
  21976. }
  21977. // indices
  21978. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21979. const face = faces[ i ];
  21980. const a = face[ 0 ] + indexOffset;
  21981. const b = face[ 1 ] + indexOffset;
  21982. const c = face[ 2 ] + indexOffset;
  21983. indices.push( a, b, c );
  21984. groupCount += 3;
  21985. }
  21986. }
  21987. }
  21988. copy( source ) {
  21989. super.copy( source );
  21990. this.parameters = Object.assign( {}, source.parameters );
  21991. return this;
  21992. }
  21993. toJSON() {
  21994. const data = super.toJSON();
  21995. const shapes = this.parameters.shapes;
  21996. return toJSON( shapes, data );
  21997. }
  21998. static fromJSON( data, shapes ) {
  21999. const geometryShapes = [];
  22000. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  22001. const shape = shapes[ data.shapes[ j ] ];
  22002. geometryShapes.push( shape );
  22003. }
  22004. return new ShapeGeometry( geometryShapes, data.curveSegments );
  22005. }
  22006. }
  22007. function toJSON( shapes, data ) {
  22008. data.shapes = [];
  22009. if ( Array.isArray( shapes ) ) {
  22010. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22011. const shape = shapes[ i ];
  22012. data.shapes.push( shape.uuid );
  22013. }
  22014. } else {
  22015. data.shapes.push( shapes.uuid );
  22016. }
  22017. return data;
  22018. }
  22019. class SphereGeometry extends BufferGeometry {
  22020. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  22021. super();
  22022. this.type = 'SphereGeometry';
  22023. this.parameters = {
  22024. radius: radius,
  22025. widthSegments: widthSegments,
  22026. heightSegments: heightSegments,
  22027. phiStart: phiStart,
  22028. phiLength: phiLength,
  22029. thetaStart: thetaStart,
  22030. thetaLength: thetaLength
  22031. };
  22032. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  22033. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  22034. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  22035. let index = 0;
  22036. const grid = [];
  22037. const vertex = new Vector3();
  22038. const normal = new Vector3();
  22039. // buffers
  22040. const indices = [];
  22041. const vertices = [];
  22042. const normals = [];
  22043. const uvs = [];
  22044. // generate vertices, normals and uvs
  22045. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  22046. const verticesRow = [];
  22047. const v = iy / heightSegments;
  22048. // special case for the poles
  22049. let uOffset = 0;
  22050. if ( iy === 0 && thetaStart === 0 ) {
  22051. uOffset = 0.5 / widthSegments;
  22052. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  22053. uOffset = - 0.5 / widthSegments;
  22054. }
  22055. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  22056. const u = ix / widthSegments;
  22057. // vertex
  22058. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22059. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22060. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22061. vertices.push( vertex.x, vertex.y, vertex.z );
  22062. // normal
  22063. normal.copy( vertex ).normalize();
  22064. normals.push( normal.x, normal.y, normal.z );
  22065. // uv
  22066. uvs.push( u + uOffset, 1 - v );
  22067. verticesRow.push( index ++ );
  22068. }
  22069. grid.push( verticesRow );
  22070. }
  22071. // indices
  22072. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  22073. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  22074. const a = grid[ iy ][ ix + 1 ];
  22075. const b = grid[ iy ][ ix ];
  22076. const c = grid[ iy + 1 ][ ix ];
  22077. const d = grid[ iy + 1 ][ ix + 1 ];
  22078. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22079. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  22080. }
  22081. }
  22082. // build geometry
  22083. this.setIndex( indices );
  22084. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22085. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22086. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22087. }
  22088. copy( source ) {
  22089. super.copy( source );
  22090. this.parameters = Object.assign( {}, source.parameters );
  22091. return this;
  22092. }
  22093. static fromJSON( data ) {
  22094. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  22095. }
  22096. }
  22097. class TetrahedronGeometry extends PolyhedronGeometry {
  22098. constructor( radius = 1, detail = 0 ) {
  22099. const vertices = [
  22100. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22101. ];
  22102. const indices = [
  22103. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22104. ];
  22105. super( vertices, indices, radius, detail );
  22106. this.type = 'TetrahedronGeometry';
  22107. this.parameters = {
  22108. radius: radius,
  22109. detail: detail
  22110. };
  22111. }
  22112. static fromJSON( data ) {
  22113. return new TetrahedronGeometry( data.radius, data.detail );
  22114. }
  22115. }
  22116. class TorusGeometry extends BufferGeometry {
  22117. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  22118. super();
  22119. this.type = 'TorusGeometry';
  22120. this.parameters = {
  22121. radius: radius,
  22122. tube: tube,
  22123. radialSegments: radialSegments,
  22124. tubularSegments: tubularSegments,
  22125. arc: arc
  22126. };
  22127. radialSegments = Math.floor( radialSegments );
  22128. tubularSegments = Math.floor( tubularSegments );
  22129. // buffers
  22130. const indices = [];
  22131. const vertices = [];
  22132. const normals = [];
  22133. const uvs = [];
  22134. // helper variables
  22135. const center = new Vector3();
  22136. const vertex = new Vector3();
  22137. const normal = new Vector3();
  22138. // generate vertices, normals and uvs
  22139. for ( let j = 0; j <= radialSegments; j ++ ) {
  22140. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22141. const u = i / tubularSegments * arc;
  22142. const v = j / radialSegments * Math.PI * 2;
  22143. // vertex
  22144. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22145. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22146. vertex.z = tube * Math.sin( v );
  22147. vertices.push( vertex.x, vertex.y, vertex.z );
  22148. // normal
  22149. center.x = radius * Math.cos( u );
  22150. center.y = radius * Math.sin( u );
  22151. normal.subVectors( vertex, center ).normalize();
  22152. normals.push( normal.x, normal.y, normal.z );
  22153. // uv
  22154. uvs.push( i / tubularSegments );
  22155. uvs.push( j / radialSegments );
  22156. }
  22157. }
  22158. // generate indices
  22159. for ( let j = 1; j <= radialSegments; j ++ ) {
  22160. for ( let i = 1; i <= tubularSegments; i ++ ) {
  22161. // indices
  22162. const a = ( tubularSegments + 1 ) * j + i - 1;
  22163. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22164. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22165. const d = ( tubularSegments + 1 ) * j + i;
  22166. // faces
  22167. indices.push( a, b, d );
  22168. indices.push( b, c, d );
  22169. }
  22170. }
  22171. // build geometry
  22172. this.setIndex( indices );
  22173. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22174. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22175. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22176. }
  22177. copy( source ) {
  22178. super.copy( source );
  22179. this.parameters = Object.assign( {}, source.parameters );
  22180. return this;
  22181. }
  22182. static fromJSON( data ) {
  22183. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  22184. }
  22185. }
  22186. class TorusKnotGeometry extends BufferGeometry {
  22187. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  22188. super();
  22189. this.type = 'TorusKnotGeometry';
  22190. this.parameters = {
  22191. radius: radius,
  22192. tube: tube,
  22193. tubularSegments: tubularSegments,
  22194. radialSegments: radialSegments,
  22195. p: p,
  22196. q: q
  22197. };
  22198. tubularSegments = Math.floor( tubularSegments );
  22199. radialSegments = Math.floor( radialSegments );
  22200. // buffers
  22201. const indices = [];
  22202. const vertices = [];
  22203. const normals = [];
  22204. const uvs = [];
  22205. // helper variables
  22206. const vertex = new Vector3();
  22207. const normal = new Vector3();
  22208. const P1 = new Vector3();
  22209. const P2 = new Vector3();
  22210. const B = new Vector3();
  22211. const T = new Vector3();
  22212. const N = new Vector3();
  22213. // generate vertices, normals and uvs
  22214. for ( let i = 0; i <= tubularSegments; ++ i ) {
  22215. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  22216. const u = i / tubularSegments * p * Math.PI * 2;
  22217. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22218. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22219. calculatePositionOnCurve( u, p, q, radius, P1 );
  22220. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  22221. // calculate orthonormal basis
  22222. T.subVectors( P2, P1 );
  22223. N.addVectors( P2, P1 );
  22224. B.crossVectors( T, N );
  22225. N.crossVectors( B, T );
  22226. // normalize B, N. T can be ignored, we don't use it
  22227. B.normalize();
  22228. N.normalize();
  22229. for ( let j = 0; j <= radialSegments; ++ j ) {
  22230. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22231. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22232. const v = j / radialSegments * Math.PI * 2;
  22233. const cx = - tube * Math.cos( v );
  22234. const cy = tube * Math.sin( v );
  22235. // now calculate the final vertex position.
  22236. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  22237. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  22238. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  22239. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  22240. vertices.push( vertex.x, vertex.y, vertex.z );
  22241. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22242. normal.subVectors( vertex, P1 ).normalize();
  22243. normals.push( normal.x, normal.y, normal.z );
  22244. // uv
  22245. uvs.push( i / tubularSegments );
  22246. uvs.push( j / radialSegments );
  22247. }
  22248. }
  22249. // generate indices
  22250. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22251. for ( let i = 1; i <= radialSegments; i ++ ) {
  22252. // indices
  22253. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22254. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22255. const c = ( radialSegments + 1 ) * j + i;
  22256. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22257. // faces
  22258. indices.push( a, b, d );
  22259. indices.push( b, c, d );
  22260. }
  22261. }
  22262. // build geometry
  22263. this.setIndex( indices );
  22264. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22265. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22266. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22267. // this function calculates the current position on the torus curve
  22268. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22269. const cu = Math.cos( u );
  22270. const su = Math.sin( u );
  22271. const quOverP = q / p * u;
  22272. const cs = Math.cos( quOverP );
  22273. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22274. position.y = radius * ( 2 + cs ) * su * 0.5;
  22275. position.z = radius * Math.sin( quOverP ) * 0.5;
  22276. }
  22277. }
  22278. copy( source ) {
  22279. super.copy( source );
  22280. this.parameters = Object.assign( {}, source.parameters );
  22281. return this;
  22282. }
  22283. static fromJSON( data ) {
  22284. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  22285. }
  22286. }
  22287. class TubeGeometry extends BufferGeometry {
  22288. constructor( path = new QuadraticBezierCurve3( new Vector3( - 1, - 1, 0 ), new Vector3( - 1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  22289. super();
  22290. this.type = 'TubeGeometry';
  22291. this.parameters = {
  22292. path: path,
  22293. tubularSegments: tubularSegments,
  22294. radius: radius,
  22295. radialSegments: radialSegments,
  22296. closed: closed
  22297. };
  22298. const frames = path.computeFrenetFrames( tubularSegments, closed );
  22299. // expose internals
  22300. this.tangents = frames.tangents;
  22301. this.normals = frames.normals;
  22302. this.binormals = frames.binormals;
  22303. // helper variables
  22304. const vertex = new Vector3();
  22305. const normal = new Vector3();
  22306. const uv = new Vector2();
  22307. let P = new Vector3();
  22308. // buffer
  22309. const vertices = [];
  22310. const normals = [];
  22311. const uvs = [];
  22312. const indices = [];
  22313. // create buffer data
  22314. generateBufferData();
  22315. // build geometry
  22316. this.setIndex( indices );
  22317. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22318. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22319. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22320. // functions
  22321. function generateBufferData() {
  22322. for ( let i = 0; i < tubularSegments; i ++ ) {
  22323. generateSegment( i );
  22324. }
  22325. // if the geometry is not closed, generate the last row of vertices and normals
  22326. // at the regular position on the given path
  22327. //
  22328. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22329. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22330. // uvs are generated in a separate function.
  22331. // this makes it easy compute correct values for closed geometries
  22332. generateUVs();
  22333. // finally create faces
  22334. generateIndices();
  22335. }
  22336. function generateSegment( i ) {
  22337. // we use getPointAt to sample evenly distributed points from the given path
  22338. P = path.getPointAt( i / tubularSegments, P );
  22339. // retrieve corresponding normal and binormal
  22340. const N = frames.normals[ i ];
  22341. const B = frames.binormals[ i ];
  22342. // generate normals and vertices for the current segment
  22343. for ( let j = 0; j <= radialSegments; j ++ ) {
  22344. const v = j / radialSegments * Math.PI * 2;
  22345. const sin = Math.sin( v );
  22346. const cos = - Math.cos( v );
  22347. // normal
  22348. normal.x = ( cos * N.x + sin * B.x );
  22349. normal.y = ( cos * N.y + sin * B.y );
  22350. normal.z = ( cos * N.z + sin * B.z );
  22351. normal.normalize();
  22352. normals.push( normal.x, normal.y, normal.z );
  22353. // vertex
  22354. vertex.x = P.x + radius * normal.x;
  22355. vertex.y = P.y + radius * normal.y;
  22356. vertex.z = P.z + radius * normal.z;
  22357. vertices.push( vertex.x, vertex.y, vertex.z );
  22358. }
  22359. }
  22360. function generateIndices() {
  22361. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22362. for ( let i = 1; i <= radialSegments; i ++ ) {
  22363. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22364. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22365. const c = ( radialSegments + 1 ) * j + i;
  22366. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22367. // faces
  22368. indices.push( a, b, d );
  22369. indices.push( b, c, d );
  22370. }
  22371. }
  22372. }
  22373. function generateUVs() {
  22374. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22375. for ( let j = 0; j <= radialSegments; j ++ ) {
  22376. uv.x = i / tubularSegments;
  22377. uv.y = j / radialSegments;
  22378. uvs.push( uv.x, uv.y );
  22379. }
  22380. }
  22381. }
  22382. }
  22383. copy( source ) {
  22384. super.copy( source );
  22385. this.parameters = Object.assign( {}, source.parameters );
  22386. return this;
  22387. }
  22388. toJSON() {
  22389. const data = super.toJSON();
  22390. data.path = this.parameters.path.toJSON();
  22391. return data;
  22392. }
  22393. static fromJSON( data ) {
  22394. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22395. // User defined curves or instances of CurvePath will not be deserialized.
  22396. return new TubeGeometry(
  22397. new Curves[ data.path.type ]().fromJSON( data.path ),
  22398. data.tubularSegments,
  22399. data.radius,
  22400. data.radialSegments,
  22401. data.closed
  22402. );
  22403. }
  22404. }
  22405. class WireframeGeometry extends BufferGeometry {
  22406. constructor( geometry = null ) {
  22407. super();
  22408. this.type = 'WireframeGeometry';
  22409. this.parameters = {
  22410. geometry: geometry
  22411. };
  22412. if ( geometry !== null ) {
  22413. // buffer
  22414. const vertices = [];
  22415. const edges = new Set();
  22416. // helper variables
  22417. const start = new Vector3();
  22418. const end = new Vector3();
  22419. if ( geometry.index !== null ) {
  22420. // indexed BufferGeometry
  22421. const position = geometry.attributes.position;
  22422. const indices = geometry.index;
  22423. let groups = geometry.groups;
  22424. if ( groups.length === 0 ) {
  22425. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22426. }
  22427. // create a data structure that contains all edges without duplicates
  22428. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22429. const group = groups[ o ];
  22430. const groupStart = group.start;
  22431. const groupCount = group.count;
  22432. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22433. for ( let j = 0; j < 3; j ++ ) {
  22434. const index1 = indices.getX( i + j );
  22435. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22436. start.fromBufferAttribute( position, index1 );
  22437. end.fromBufferAttribute( position, index2 );
  22438. if ( isUniqueEdge( start, end, edges ) === true ) {
  22439. vertices.push( start.x, start.y, start.z );
  22440. vertices.push( end.x, end.y, end.z );
  22441. }
  22442. }
  22443. }
  22444. }
  22445. } else {
  22446. // non-indexed BufferGeometry
  22447. const position = geometry.attributes.position;
  22448. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22449. for ( let j = 0; j < 3; j ++ ) {
  22450. // three edges per triangle, an edge is represented as (index1, index2)
  22451. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22452. const index1 = 3 * i + j;
  22453. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22454. start.fromBufferAttribute( position, index1 );
  22455. end.fromBufferAttribute( position, index2 );
  22456. if ( isUniqueEdge( start, end, edges ) === true ) {
  22457. vertices.push( start.x, start.y, start.z );
  22458. vertices.push( end.x, end.y, end.z );
  22459. }
  22460. }
  22461. }
  22462. }
  22463. // build geometry
  22464. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22465. }
  22466. }
  22467. copy( source ) {
  22468. super.copy( source );
  22469. this.parameters = Object.assign( {}, source.parameters );
  22470. return this;
  22471. }
  22472. }
  22473. function isUniqueEdge( start, end, edges ) {
  22474. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22475. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22476. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22477. return false;
  22478. } else {
  22479. edges.add( hash1 );
  22480. edges.add( hash2 );
  22481. return true;
  22482. }
  22483. }
  22484. var Geometries = /*#__PURE__*/Object.freeze({
  22485. __proto__: null,
  22486. BoxGeometry: BoxGeometry,
  22487. CapsuleGeometry: CapsuleGeometry,
  22488. CircleGeometry: CircleGeometry,
  22489. ConeGeometry: ConeGeometry,
  22490. CylinderGeometry: CylinderGeometry,
  22491. DodecahedronGeometry: DodecahedronGeometry,
  22492. EdgesGeometry: EdgesGeometry,
  22493. ExtrudeGeometry: ExtrudeGeometry,
  22494. IcosahedronGeometry: IcosahedronGeometry,
  22495. LatheGeometry: LatheGeometry,
  22496. OctahedronGeometry: OctahedronGeometry,
  22497. PlaneGeometry: PlaneGeometry,
  22498. PolyhedronGeometry: PolyhedronGeometry,
  22499. RingGeometry: RingGeometry,
  22500. ShapeGeometry: ShapeGeometry,
  22501. SphereGeometry: SphereGeometry,
  22502. TetrahedronGeometry: TetrahedronGeometry,
  22503. TorusGeometry: TorusGeometry,
  22504. TorusKnotGeometry: TorusKnotGeometry,
  22505. TubeGeometry: TubeGeometry,
  22506. WireframeGeometry: WireframeGeometry
  22507. });
  22508. class ShadowMaterial extends Material {
  22509. constructor( parameters ) {
  22510. super();
  22511. this.isShadowMaterial = true;
  22512. this.type = 'ShadowMaterial';
  22513. this.color = new Color( 0x000000 );
  22514. this.transparent = true;
  22515. this.fog = true;
  22516. this.setValues( parameters );
  22517. }
  22518. copy( source ) {
  22519. super.copy( source );
  22520. this.color.copy( source.color );
  22521. this.fog = source.fog;
  22522. return this;
  22523. }
  22524. }
  22525. class RawShaderMaterial extends ShaderMaterial {
  22526. constructor( parameters ) {
  22527. super( parameters );
  22528. this.isRawShaderMaterial = true;
  22529. this.type = 'RawShaderMaterial';
  22530. }
  22531. }
  22532. class MeshStandardMaterial extends Material {
  22533. constructor( parameters ) {
  22534. super();
  22535. this.isMeshStandardMaterial = true;
  22536. this.defines = { 'STANDARD': '' };
  22537. this.type = 'MeshStandardMaterial';
  22538. this.color = new Color( 0xffffff ); // diffuse
  22539. this.roughness = 1.0;
  22540. this.metalness = 0.0;
  22541. this.map = null;
  22542. this.lightMap = null;
  22543. this.lightMapIntensity = 1.0;
  22544. this.aoMap = null;
  22545. this.aoMapIntensity = 1.0;
  22546. this.emissive = new Color( 0x000000 );
  22547. this.emissiveIntensity = 1.0;
  22548. this.emissiveMap = null;
  22549. this.bumpMap = null;
  22550. this.bumpScale = 1;
  22551. this.normalMap = null;
  22552. this.normalMapType = TangentSpaceNormalMap;
  22553. this.normalScale = new Vector2( 1, 1 );
  22554. this.displacementMap = null;
  22555. this.displacementScale = 1;
  22556. this.displacementBias = 0;
  22557. this.roughnessMap = null;
  22558. this.metalnessMap = null;
  22559. this.alphaMap = null;
  22560. this.envMap = null;
  22561. this.envMapIntensity = 1.0;
  22562. this.wireframe = false;
  22563. this.wireframeLinewidth = 1;
  22564. this.wireframeLinecap = 'round';
  22565. this.wireframeLinejoin = 'round';
  22566. this.flatShading = false;
  22567. this.fog = true;
  22568. this.setValues( parameters );
  22569. }
  22570. copy( source ) {
  22571. super.copy( source );
  22572. this.defines = { 'STANDARD': '' };
  22573. this.color.copy( source.color );
  22574. this.roughness = source.roughness;
  22575. this.metalness = source.metalness;
  22576. this.map = source.map;
  22577. this.lightMap = source.lightMap;
  22578. this.lightMapIntensity = source.lightMapIntensity;
  22579. this.aoMap = source.aoMap;
  22580. this.aoMapIntensity = source.aoMapIntensity;
  22581. this.emissive.copy( source.emissive );
  22582. this.emissiveMap = source.emissiveMap;
  22583. this.emissiveIntensity = source.emissiveIntensity;
  22584. this.bumpMap = source.bumpMap;
  22585. this.bumpScale = source.bumpScale;
  22586. this.normalMap = source.normalMap;
  22587. this.normalMapType = source.normalMapType;
  22588. this.normalScale.copy( source.normalScale );
  22589. this.displacementMap = source.displacementMap;
  22590. this.displacementScale = source.displacementScale;
  22591. this.displacementBias = source.displacementBias;
  22592. this.roughnessMap = source.roughnessMap;
  22593. this.metalnessMap = source.metalnessMap;
  22594. this.alphaMap = source.alphaMap;
  22595. this.envMap = source.envMap;
  22596. this.envMapIntensity = source.envMapIntensity;
  22597. this.wireframe = source.wireframe;
  22598. this.wireframeLinewidth = source.wireframeLinewidth;
  22599. this.wireframeLinecap = source.wireframeLinecap;
  22600. this.wireframeLinejoin = source.wireframeLinejoin;
  22601. this.flatShading = source.flatShading;
  22602. this.fog = source.fog;
  22603. return this;
  22604. }
  22605. }
  22606. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22607. constructor( parameters ) {
  22608. super();
  22609. this.isMeshPhysicalMaterial = true;
  22610. this.defines = {
  22611. 'STANDARD': '',
  22612. 'PHYSICAL': ''
  22613. };
  22614. this.type = 'MeshPhysicalMaterial';
  22615. this.clearcoatMap = null;
  22616. this.clearcoatRoughness = 0.0;
  22617. this.clearcoatRoughnessMap = null;
  22618. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22619. this.clearcoatNormalMap = null;
  22620. this.ior = 1.5;
  22621. Object.defineProperty( this, 'reflectivity', {
  22622. get: function () {
  22623. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22624. },
  22625. set: function ( reflectivity ) {
  22626. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22627. }
  22628. } );
  22629. this.iridescenceMap = null;
  22630. this.iridescenceIOR = 1.3;
  22631. this.iridescenceThicknessRange = [ 100, 400 ];
  22632. this.iridescenceThicknessMap = null;
  22633. this.sheenColor = new Color( 0x000000 );
  22634. this.sheenColorMap = null;
  22635. this.sheenRoughness = 1.0;
  22636. this.sheenRoughnessMap = null;
  22637. this.transmissionMap = null;
  22638. this.thickness = 0;
  22639. this.thicknessMap = null;
  22640. this.attenuationDistance = Infinity;
  22641. this.attenuationColor = new Color( 1, 1, 1 );
  22642. this.specularIntensity = 1.0;
  22643. this.specularIntensityMap = null;
  22644. this.specularColor = new Color( 1, 1, 1 );
  22645. this.specularColorMap = null;
  22646. this._sheen = 0.0;
  22647. this._clearcoat = 0;
  22648. this._iridescence = 0;
  22649. this._transmission = 0;
  22650. this.setValues( parameters );
  22651. }
  22652. get sheen() {
  22653. return this._sheen;
  22654. }
  22655. set sheen( value ) {
  22656. if ( this._sheen > 0 !== value > 0 ) {
  22657. this.version ++;
  22658. }
  22659. this._sheen = value;
  22660. }
  22661. get clearcoat() {
  22662. return this._clearcoat;
  22663. }
  22664. set clearcoat( value ) {
  22665. if ( this._clearcoat > 0 !== value > 0 ) {
  22666. this.version ++;
  22667. }
  22668. this._clearcoat = value;
  22669. }
  22670. get iridescence() {
  22671. return this._iridescence;
  22672. }
  22673. set iridescence( value ) {
  22674. if ( this._iridescence > 0 !== value > 0 ) {
  22675. this.version ++;
  22676. }
  22677. this._iridescence = value;
  22678. }
  22679. get transmission() {
  22680. return this._transmission;
  22681. }
  22682. set transmission( value ) {
  22683. if ( this._transmission > 0 !== value > 0 ) {
  22684. this.version ++;
  22685. }
  22686. this._transmission = value;
  22687. }
  22688. copy( source ) {
  22689. super.copy( source );
  22690. this.defines = {
  22691. 'STANDARD': '',
  22692. 'PHYSICAL': ''
  22693. };
  22694. this.clearcoat = source.clearcoat;
  22695. this.clearcoatMap = source.clearcoatMap;
  22696. this.clearcoatRoughness = source.clearcoatRoughness;
  22697. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22698. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22699. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22700. this.ior = source.ior;
  22701. this.iridescence = source.iridescence;
  22702. this.iridescenceMap = source.iridescenceMap;
  22703. this.iridescenceIOR = source.iridescenceIOR;
  22704. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22705. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22706. this.sheen = source.sheen;
  22707. this.sheenColor.copy( source.sheenColor );
  22708. this.sheenColorMap = source.sheenColorMap;
  22709. this.sheenRoughness = source.sheenRoughness;
  22710. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22711. this.transmission = source.transmission;
  22712. this.transmissionMap = source.transmissionMap;
  22713. this.thickness = source.thickness;
  22714. this.thicknessMap = source.thicknessMap;
  22715. this.attenuationDistance = source.attenuationDistance;
  22716. this.attenuationColor.copy( source.attenuationColor );
  22717. this.specularIntensity = source.specularIntensity;
  22718. this.specularIntensityMap = source.specularIntensityMap;
  22719. this.specularColor.copy( source.specularColor );
  22720. this.specularColorMap = source.specularColorMap;
  22721. return this;
  22722. }
  22723. }
  22724. class MeshPhongMaterial extends Material {
  22725. constructor( parameters ) {
  22726. super();
  22727. this.isMeshPhongMaterial = true;
  22728. this.type = 'MeshPhongMaterial';
  22729. this.color = new Color( 0xffffff ); // diffuse
  22730. this.specular = new Color( 0x111111 );
  22731. this.shininess = 30;
  22732. this.map = null;
  22733. this.lightMap = null;
  22734. this.lightMapIntensity = 1.0;
  22735. this.aoMap = null;
  22736. this.aoMapIntensity = 1.0;
  22737. this.emissive = new Color( 0x000000 );
  22738. this.emissiveIntensity = 1.0;
  22739. this.emissiveMap = null;
  22740. this.bumpMap = null;
  22741. this.bumpScale = 1;
  22742. this.normalMap = null;
  22743. this.normalMapType = TangentSpaceNormalMap;
  22744. this.normalScale = new Vector2( 1, 1 );
  22745. this.displacementMap = null;
  22746. this.displacementScale = 1;
  22747. this.displacementBias = 0;
  22748. this.specularMap = null;
  22749. this.alphaMap = null;
  22750. this.envMap = null;
  22751. this.combine = MultiplyOperation;
  22752. this.reflectivity = 1;
  22753. this.refractionRatio = 0.98;
  22754. this.wireframe = false;
  22755. this.wireframeLinewidth = 1;
  22756. this.wireframeLinecap = 'round';
  22757. this.wireframeLinejoin = 'round';
  22758. this.flatShading = false;
  22759. this.fog = true;
  22760. this.setValues( parameters );
  22761. }
  22762. copy( source ) {
  22763. super.copy( source );
  22764. this.color.copy( source.color );
  22765. this.specular.copy( source.specular );
  22766. this.shininess = source.shininess;
  22767. this.map = source.map;
  22768. this.lightMap = source.lightMap;
  22769. this.lightMapIntensity = source.lightMapIntensity;
  22770. this.aoMap = source.aoMap;
  22771. this.aoMapIntensity = source.aoMapIntensity;
  22772. this.emissive.copy( source.emissive );
  22773. this.emissiveMap = source.emissiveMap;
  22774. this.emissiveIntensity = source.emissiveIntensity;
  22775. this.bumpMap = source.bumpMap;
  22776. this.bumpScale = source.bumpScale;
  22777. this.normalMap = source.normalMap;
  22778. this.normalMapType = source.normalMapType;
  22779. this.normalScale.copy( source.normalScale );
  22780. this.displacementMap = source.displacementMap;
  22781. this.displacementScale = source.displacementScale;
  22782. this.displacementBias = source.displacementBias;
  22783. this.specularMap = source.specularMap;
  22784. this.alphaMap = source.alphaMap;
  22785. this.envMap = source.envMap;
  22786. this.combine = source.combine;
  22787. this.reflectivity = source.reflectivity;
  22788. this.refractionRatio = source.refractionRatio;
  22789. this.wireframe = source.wireframe;
  22790. this.wireframeLinewidth = source.wireframeLinewidth;
  22791. this.wireframeLinecap = source.wireframeLinecap;
  22792. this.wireframeLinejoin = source.wireframeLinejoin;
  22793. this.flatShading = source.flatShading;
  22794. this.fog = source.fog;
  22795. return this;
  22796. }
  22797. }
  22798. class MeshToonMaterial extends Material {
  22799. constructor( parameters ) {
  22800. super();
  22801. this.isMeshToonMaterial = true;
  22802. this.defines = { 'TOON': '' };
  22803. this.type = 'MeshToonMaterial';
  22804. this.color = new Color( 0xffffff );
  22805. this.map = null;
  22806. this.gradientMap = null;
  22807. this.lightMap = null;
  22808. this.lightMapIntensity = 1.0;
  22809. this.aoMap = null;
  22810. this.aoMapIntensity = 1.0;
  22811. this.emissive = new Color( 0x000000 );
  22812. this.emissiveIntensity = 1.0;
  22813. this.emissiveMap = null;
  22814. this.bumpMap = null;
  22815. this.bumpScale = 1;
  22816. this.normalMap = null;
  22817. this.normalMapType = TangentSpaceNormalMap;
  22818. this.normalScale = new Vector2( 1, 1 );
  22819. this.displacementMap = null;
  22820. this.displacementScale = 1;
  22821. this.displacementBias = 0;
  22822. this.alphaMap = null;
  22823. this.wireframe = false;
  22824. this.wireframeLinewidth = 1;
  22825. this.wireframeLinecap = 'round';
  22826. this.wireframeLinejoin = 'round';
  22827. this.fog = true;
  22828. this.setValues( parameters );
  22829. }
  22830. copy( source ) {
  22831. super.copy( source );
  22832. this.color.copy( source.color );
  22833. this.map = source.map;
  22834. this.gradientMap = source.gradientMap;
  22835. this.lightMap = source.lightMap;
  22836. this.lightMapIntensity = source.lightMapIntensity;
  22837. this.aoMap = source.aoMap;
  22838. this.aoMapIntensity = source.aoMapIntensity;
  22839. this.emissive.copy( source.emissive );
  22840. this.emissiveMap = source.emissiveMap;
  22841. this.emissiveIntensity = source.emissiveIntensity;
  22842. this.bumpMap = source.bumpMap;
  22843. this.bumpScale = source.bumpScale;
  22844. this.normalMap = source.normalMap;
  22845. this.normalMapType = source.normalMapType;
  22846. this.normalScale.copy( source.normalScale );
  22847. this.displacementMap = source.displacementMap;
  22848. this.displacementScale = source.displacementScale;
  22849. this.displacementBias = source.displacementBias;
  22850. this.alphaMap = source.alphaMap;
  22851. this.wireframe = source.wireframe;
  22852. this.wireframeLinewidth = source.wireframeLinewidth;
  22853. this.wireframeLinecap = source.wireframeLinecap;
  22854. this.wireframeLinejoin = source.wireframeLinejoin;
  22855. this.fog = source.fog;
  22856. return this;
  22857. }
  22858. }
  22859. class MeshNormalMaterial extends Material {
  22860. constructor( parameters ) {
  22861. super();
  22862. this.isMeshNormalMaterial = true;
  22863. this.type = 'MeshNormalMaterial';
  22864. this.bumpMap = null;
  22865. this.bumpScale = 1;
  22866. this.normalMap = null;
  22867. this.normalMapType = TangentSpaceNormalMap;
  22868. this.normalScale = new Vector2( 1, 1 );
  22869. this.displacementMap = null;
  22870. this.displacementScale = 1;
  22871. this.displacementBias = 0;
  22872. this.wireframe = false;
  22873. this.wireframeLinewidth = 1;
  22874. this.flatShading = false;
  22875. this.setValues( parameters );
  22876. }
  22877. copy( source ) {
  22878. super.copy( source );
  22879. this.bumpMap = source.bumpMap;
  22880. this.bumpScale = source.bumpScale;
  22881. this.normalMap = source.normalMap;
  22882. this.normalMapType = source.normalMapType;
  22883. this.normalScale.copy( source.normalScale );
  22884. this.displacementMap = source.displacementMap;
  22885. this.displacementScale = source.displacementScale;
  22886. this.displacementBias = source.displacementBias;
  22887. this.wireframe = source.wireframe;
  22888. this.wireframeLinewidth = source.wireframeLinewidth;
  22889. this.flatShading = source.flatShading;
  22890. return this;
  22891. }
  22892. }
  22893. class MeshLambertMaterial extends Material {
  22894. constructor( parameters ) {
  22895. super();
  22896. this.isMeshLambertMaterial = true;
  22897. this.type = 'MeshLambertMaterial';
  22898. this.color = new Color( 0xffffff ); // diffuse
  22899. this.map = null;
  22900. this.lightMap = null;
  22901. this.lightMapIntensity = 1.0;
  22902. this.aoMap = null;
  22903. this.aoMapIntensity = 1.0;
  22904. this.emissive = new Color( 0x000000 );
  22905. this.emissiveIntensity = 1.0;
  22906. this.emissiveMap = null;
  22907. this.bumpMap = null;
  22908. this.bumpScale = 1;
  22909. this.normalMap = null;
  22910. this.normalMapType = TangentSpaceNormalMap;
  22911. this.normalScale = new Vector2( 1, 1 );
  22912. this.displacementMap = null;
  22913. this.displacementScale = 1;
  22914. this.displacementBias = 0;
  22915. this.specularMap = null;
  22916. this.alphaMap = null;
  22917. this.envMap = null;
  22918. this.combine = MultiplyOperation;
  22919. this.reflectivity = 1;
  22920. this.refractionRatio = 0.98;
  22921. this.wireframe = false;
  22922. this.wireframeLinewidth = 1;
  22923. this.wireframeLinecap = 'round';
  22924. this.wireframeLinejoin = 'round';
  22925. this.flatShading = false;
  22926. this.fog = true;
  22927. this.setValues( parameters );
  22928. }
  22929. copy( source ) {
  22930. super.copy( source );
  22931. this.color.copy( source.color );
  22932. this.map = source.map;
  22933. this.lightMap = source.lightMap;
  22934. this.lightMapIntensity = source.lightMapIntensity;
  22935. this.aoMap = source.aoMap;
  22936. this.aoMapIntensity = source.aoMapIntensity;
  22937. this.emissive.copy( source.emissive );
  22938. this.emissiveMap = source.emissiveMap;
  22939. this.emissiveIntensity = source.emissiveIntensity;
  22940. this.bumpMap = source.bumpMap;
  22941. this.bumpScale = source.bumpScale;
  22942. this.normalMap = source.normalMap;
  22943. this.normalMapType = source.normalMapType;
  22944. this.normalScale.copy( source.normalScale );
  22945. this.displacementMap = source.displacementMap;
  22946. this.displacementScale = source.displacementScale;
  22947. this.displacementBias = source.displacementBias;
  22948. this.specularMap = source.specularMap;
  22949. this.alphaMap = source.alphaMap;
  22950. this.envMap = source.envMap;
  22951. this.combine = source.combine;
  22952. this.reflectivity = source.reflectivity;
  22953. this.refractionRatio = source.refractionRatio;
  22954. this.wireframe = source.wireframe;
  22955. this.wireframeLinewidth = source.wireframeLinewidth;
  22956. this.wireframeLinecap = source.wireframeLinecap;
  22957. this.wireframeLinejoin = source.wireframeLinejoin;
  22958. this.flatShading = source.flatShading;
  22959. this.fog = source.fog;
  22960. return this;
  22961. }
  22962. }
  22963. class MeshMatcapMaterial extends Material {
  22964. constructor( parameters ) {
  22965. super();
  22966. this.isMeshMatcapMaterial = true;
  22967. this.defines = { 'MATCAP': '' };
  22968. this.type = 'MeshMatcapMaterial';
  22969. this.color = new Color( 0xffffff ); // diffuse
  22970. this.matcap = null;
  22971. this.map = null;
  22972. this.bumpMap = null;
  22973. this.bumpScale = 1;
  22974. this.normalMap = null;
  22975. this.normalMapType = TangentSpaceNormalMap;
  22976. this.normalScale = new Vector2( 1, 1 );
  22977. this.displacementMap = null;
  22978. this.displacementScale = 1;
  22979. this.displacementBias = 0;
  22980. this.alphaMap = null;
  22981. this.flatShading = false;
  22982. this.fog = true;
  22983. this.setValues( parameters );
  22984. }
  22985. copy( source ) {
  22986. super.copy( source );
  22987. this.defines = { 'MATCAP': '' };
  22988. this.color.copy( source.color );
  22989. this.matcap = source.matcap;
  22990. this.map = source.map;
  22991. this.bumpMap = source.bumpMap;
  22992. this.bumpScale = source.bumpScale;
  22993. this.normalMap = source.normalMap;
  22994. this.normalMapType = source.normalMapType;
  22995. this.normalScale.copy( source.normalScale );
  22996. this.displacementMap = source.displacementMap;
  22997. this.displacementScale = source.displacementScale;
  22998. this.displacementBias = source.displacementBias;
  22999. this.alphaMap = source.alphaMap;
  23000. this.flatShading = source.flatShading;
  23001. this.fog = source.fog;
  23002. return this;
  23003. }
  23004. }
  23005. class LineDashedMaterial extends LineBasicMaterial {
  23006. constructor( parameters ) {
  23007. super();
  23008. this.isLineDashedMaterial = true;
  23009. this.type = 'LineDashedMaterial';
  23010. this.scale = 1;
  23011. this.dashSize = 3;
  23012. this.gapSize = 1;
  23013. this.setValues( parameters );
  23014. }
  23015. copy( source ) {
  23016. super.copy( source );
  23017. this.scale = source.scale;
  23018. this.dashSize = source.dashSize;
  23019. this.gapSize = source.gapSize;
  23020. return this;
  23021. }
  23022. }
  23023. // same as Array.prototype.slice, but also works on typed arrays
  23024. function arraySlice( array, from, to ) {
  23025. if ( isTypedArray( array ) ) {
  23026. // in ios9 array.subarray(from, undefined) will return empty array
  23027. // but array.subarray(from) or array.subarray(from, len) is correct
  23028. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  23029. }
  23030. return array.slice( from, to );
  23031. }
  23032. // converts an array to a specific type
  23033. function convertArray( array, type, forceClone ) {
  23034. if ( ! array || // let 'undefined' and 'null' pass
  23035. ! forceClone && array.constructor === type ) return array;
  23036. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  23037. return new type( array ); // create typed array
  23038. }
  23039. return Array.prototype.slice.call( array ); // create Array
  23040. }
  23041. function isTypedArray( object ) {
  23042. return ArrayBuffer.isView( object ) &&
  23043. ! ( object instanceof DataView );
  23044. }
  23045. // returns an array by which times and values can be sorted
  23046. function getKeyframeOrder( times ) {
  23047. function compareTime( i, j ) {
  23048. return times[ i ] - times[ j ];
  23049. }
  23050. const n = times.length;
  23051. const result = new Array( n );
  23052. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  23053. result.sort( compareTime );
  23054. return result;
  23055. }
  23056. // uses the array previously returned by 'getKeyframeOrder' to sort data
  23057. function sortedArray( values, stride, order ) {
  23058. const nValues = values.length;
  23059. const result = new values.constructor( nValues );
  23060. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  23061. const srcOffset = order[ i ] * stride;
  23062. for ( let j = 0; j !== stride; ++ j ) {
  23063. result[ dstOffset ++ ] = values[ srcOffset + j ];
  23064. }
  23065. }
  23066. return result;
  23067. }
  23068. // function for parsing AOS keyframe formats
  23069. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  23070. let i = 1, key = jsonKeys[ 0 ];
  23071. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  23072. key = jsonKeys[ i ++ ];
  23073. }
  23074. if ( key === undefined ) return; // no data
  23075. let value = key[ valuePropertyName ];
  23076. if ( value === undefined ) return; // no data
  23077. if ( Array.isArray( value ) ) {
  23078. do {
  23079. value = key[ valuePropertyName ];
  23080. if ( value !== undefined ) {
  23081. times.push( key.time );
  23082. values.push.apply( values, value ); // push all elements
  23083. }
  23084. key = jsonKeys[ i ++ ];
  23085. } while ( key !== undefined );
  23086. } else if ( value.toArray !== undefined ) {
  23087. // ...assume THREE.Math-ish
  23088. do {
  23089. value = key[ valuePropertyName ];
  23090. if ( value !== undefined ) {
  23091. times.push( key.time );
  23092. value.toArray( values, values.length );
  23093. }
  23094. key = jsonKeys[ i ++ ];
  23095. } while ( key !== undefined );
  23096. } else {
  23097. // otherwise push as-is
  23098. do {
  23099. value = key[ valuePropertyName ];
  23100. if ( value !== undefined ) {
  23101. times.push( key.time );
  23102. values.push( value );
  23103. }
  23104. key = jsonKeys[ i ++ ];
  23105. } while ( key !== undefined );
  23106. }
  23107. }
  23108. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  23109. const clip = sourceClip.clone();
  23110. clip.name = name;
  23111. const tracks = [];
  23112. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23113. const track = clip.tracks[ i ];
  23114. const valueSize = track.getValueSize();
  23115. const times = [];
  23116. const values = [];
  23117. for ( let j = 0; j < track.times.length; ++ j ) {
  23118. const frame = track.times[ j ] * fps;
  23119. if ( frame < startFrame || frame >= endFrame ) continue;
  23120. times.push( track.times[ j ] );
  23121. for ( let k = 0; k < valueSize; ++ k ) {
  23122. values.push( track.values[ j * valueSize + k ] );
  23123. }
  23124. }
  23125. if ( times.length === 0 ) continue;
  23126. track.times = convertArray( times, track.times.constructor );
  23127. track.values = convertArray( values, track.values.constructor );
  23128. tracks.push( track );
  23129. }
  23130. clip.tracks = tracks;
  23131. // find minimum .times value across all tracks in the trimmed clip
  23132. let minStartTime = Infinity;
  23133. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23134. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  23135. minStartTime = clip.tracks[ i ].times[ 0 ];
  23136. }
  23137. }
  23138. // shift all tracks such that clip begins at t=0
  23139. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23140. clip.tracks[ i ].shift( - 1 * minStartTime );
  23141. }
  23142. clip.resetDuration();
  23143. return clip;
  23144. }
  23145. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  23146. if ( fps <= 0 ) fps = 30;
  23147. const numTracks = referenceClip.tracks.length;
  23148. const referenceTime = referenceFrame / fps;
  23149. // Make each track's values relative to the values at the reference frame
  23150. for ( let i = 0; i < numTracks; ++ i ) {
  23151. const referenceTrack = referenceClip.tracks[ i ];
  23152. const referenceTrackType = referenceTrack.ValueTypeName;
  23153. // Skip this track if it's non-numeric
  23154. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  23155. // Find the track in the target clip whose name and type matches the reference track
  23156. const targetTrack = targetClip.tracks.find( function ( track ) {
  23157. return track.name === referenceTrack.name
  23158. && track.ValueTypeName === referenceTrackType;
  23159. } );
  23160. if ( targetTrack === undefined ) continue;
  23161. let referenceOffset = 0;
  23162. const referenceValueSize = referenceTrack.getValueSize();
  23163. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23164. referenceOffset = referenceValueSize / 3;
  23165. }
  23166. let targetOffset = 0;
  23167. const targetValueSize = targetTrack.getValueSize();
  23168. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23169. targetOffset = targetValueSize / 3;
  23170. }
  23171. const lastIndex = referenceTrack.times.length - 1;
  23172. let referenceValue;
  23173. // Find the value to subtract out of the track
  23174. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  23175. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23176. const startIndex = referenceOffset;
  23177. const endIndex = referenceValueSize - referenceOffset;
  23178. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23179. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  23180. // Reference frame is after the last keyframe, so just use the last keyframe
  23181. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23182. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23183. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23184. } else {
  23185. // Interpolate to the reference value
  23186. const interpolant = referenceTrack.createInterpolant();
  23187. const startIndex = referenceOffset;
  23188. const endIndex = referenceValueSize - referenceOffset;
  23189. interpolant.evaluate( referenceTime );
  23190. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  23191. }
  23192. // Conjugate the quaternion
  23193. if ( referenceTrackType === 'quaternion' ) {
  23194. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  23195. referenceQuat.toArray( referenceValue );
  23196. }
  23197. // Subtract the reference value from all of the track values
  23198. const numTimes = targetTrack.times.length;
  23199. for ( let j = 0; j < numTimes; ++ j ) {
  23200. const valueStart = j * targetValueSize + targetOffset;
  23201. if ( referenceTrackType === 'quaternion' ) {
  23202. // Multiply the conjugate for quaternion track types
  23203. Quaternion.multiplyQuaternionsFlat(
  23204. targetTrack.values,
  23205. valueStart,
  23206. referenceValue,
  23207. 0,
  23208. targetTrack.values,
  23209. valueStart
  23210. );
  23211. } else {
  23212. const valueEnd = targetValueSize - targetOffset * 2;
  23213. // Subtract each value for all other numeric track types
  23214. for ( let k = 0; k < valueEnd; ++ k ) {
  23215. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  23216. }
  23217. }
  23218. }
  23219. }
  23220. targetClip.blendMode = AdditiveAnimationBlendMode;
  23221. return targetClip;
  23222. }
  23223. const AnimationUtils = {
  23224. arraySlice: arraySlice,
  23225. convertArray: convertArray,
  23226. isTypedArray: isTypedArray,
  23227. getKeyframeOrder: getKeyframeOrder,
  23228. sortedArray: sortedArray,
  23229. flattenJSON: flattenJSON,
  23230. subclip: subclip,
  23231. makeClipAdditive: makeClipAdditive
  23232. };
  23233. /**
  23234. * Abstract base class of interpolants over parametric samples.
  23235. *
  23236. * The parameter domain is one dimensional, typically the time or a path
  23237. * along a curve defined by the data.
  23238. *
  23239. * The sample values can have any dimensionality and derived classes may
  23240. * apply special interpretations to the data.
  23241. *
  23242. * This class provides the interval seek in a Template Method, deferring
  23243. * the actual interpolation to derived classes.
  23244. *
  23245. * Time complexity is O(1) for linear access crossing at most two points
  23246. * and O(log N) for random access, where N is the number of positions.
  23247. *
  23248. * References:
  23249. *
  23250. * http://www.oodesign.com/template-method-pattern.html
  23251. *
  23252. */
  23253. class Interpolant {
  23254. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23255. this.parameterPositions = parameterPositions;
  23256. this._cachedIndex = 0;
  23257. this.resultBuffer = resultBuffer !== undefined ?
  23258. resultBuffer : new sampleValues.constructor( sampleSize );
  23259. this.sampleValues = sampleValues;
  23260. this.valueSize = sampleSize;
  23261. this.settings = null;
  23262. this.DefaultSettings_ = {};
  23263. }
  23264. evaluate( t ) {
  23265. const pp = this.parameterPositions;
  23266. let i1 = this._cachedIndex,
  23267. t1 = pp[ i1 ],
  23268. t0 = pp[ i1 - 1 ];
  23269. validate_interval: {
  23270. seek: {
  23271. let right;
  23272. linear_scan: {
  23273. //- See http://jsperf.com/comparison-to-undefined/3
  23274. //- slower code:
  23275. //-
  23276. //- if ( t >= t1 || t1 === undefined ) {
  23277. forward_scan: if ( ! ( t < t1 ) ) {
  23278. for ( let giveUpAt = i1 + 2; ; ) {
  23279. if ( t1 === undefined ) {
  23280. if ( t < t0 ) break forward_scan;
  23281. // after end
  23282. i1 = pp.length;
  23283. this._cachedIndex = i1;
  23284. return this.copySampleValue_( i1 - 1 );
  23285. }
  23286. if ( i1 === giveUpAt ) break; // this loop
  23287. t0 = t1;
  23288. t1 = pp[ ++ i1 ];
  23289. if ( t < t1 ) {
  23290. // we have arrived at the sought interval
  23291. break seek;
  23292. }
  23293. }
  23294. // prepare binary search on the right side of the index
  23295. right = pp.length;
  23296. break linear_scan;
  23297. }
  23298. //- slower code:
  23299. //- if ( t < t0 || t0 === undefined ) {
  23300. if ( ! ( t >= t0 ) ) {
  23301. // looping?
  23302. const t1global = pp[ 1 ];
  23303. if ( t < t1global ) {
  23304. i1 = 2; // + 1, using the scan for the details
  23305. t0 = t1global;
  23306. }
  23307. // linear reverse scan
  23308. for ( let giveUpAt = i1 - 2; ; ) {
  23309. if ( t0 === undefined ) {
  23310. // before start
  23311. this._cachedIndex = 0;
  23312. return this.copySampleValue_( 0 );
  23313. }
  23314. if ( i1 === giveUpAt ) break; // this loop
  23315. t1 = t0;
  23316. t0 = pp[ -- i1 - 1 ];
  23317. if ( t >= t0 ) {
  23318. // we have arrived at the sought interval
  23319. break seek;
  23320. }
  23321. }
  23322. // prepare binary search on the left side of the index
  23323. right = i1;
  23324. i1 = 0;
  23325. break linear_scan;
  23326. }
  23327. // the interval is valid
  23328. break validate_interval;
  23329. } // linear scan
  23330. // binary search
  23331. while ( i1 < right ) {
  23332. const mid = ( i1 + right ) >>> 1;
  23333. if ( t < pp[ mid ] ) {
  23334. right = mid;
  23335. } else {
  23336. i1 = mid + 1;
  23337. }
  23338. }
  23339. t1 = pp[ i1 ];
  23340. t0 = pp[ i1 - 1 ];
  23341. // check boundary cases, again
  23342. if ( t0 === undefined ) {
  23343. this._cachedIndex = 0;
  23344. return this.copySampleValue_( 0 );
  23345. }
  23346. if ( t1 === undefined ) {
  23347. i1 = pp.length;
  23348. this._cachedIndex = i1;
  23349. return this.copySampleValue_( i1 - 1 );
  23350. }
  23351. } // seek
  23352. this._cachedIndex = i1;
  23353. this.intervalChanged_( i1, t0, t1 );
  23354. } // validate_interval
  23355. return this.interpolate_( i1, t0, t, t1 );
  23356. }
  23357. getSettings_() {
  23358. return this.settings || this.DefaultSettings_;
  23359. }
  23360. copySampleValue_( index ) {
  23361. // copies a sample value to the result buffer
  23362. const result = this.resultBuffer,
  23363. values = this.sampleValues,
  23364. stride = this.valueSize,
  23365. offset = index * stride;
  23366. for ( let i = 0; i !== stride; ++ i ) {
  23367. result[ i ] = values[ offset + i ];
  23368. }
  23369. return result;
  23370. }
  23371. // Template methods for derived classes:
  23372. interpolate_( /* i1, t0, t, t1 */ ) {
  23373. throw new Error( 'call to abstract method' );
  23374. // implementations shall return this.resultBuffer
  23375. }
  23376. intervalChanged_( /* i1, t0, t1 */ ) {
  23377. // empty
  23378. }
  23379. }
  23380. /**
  23381. * Fast and simple cubic spline interpolant.
  23382. *
  23383. * It was derived from a Hermitian construction setting the first derivative
  23384. * at each sample position to the linear slope between neighboring positions
  23385. * over their parameter interval.
  23386. */
  23387. class CubicInterpolant extends Interpolant {
  23388. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23389. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23390. this._weightPrev = - 0;
  23391. this._offsetPrev = - 0;
  23392. this._weightNext = - 0;
  23393. this._offsetNext = - 0;
  23394. this.DefaultSettings_ = {
  23395. endingStart: ZeroCurvatureEnding,
  23396. endingEnd: ZeroCurvatureEnding
  23397. };
  23398. }
  23399. intervalChanged_( i1, t0, t1 ) {
  23400. const pp = this.parameterPositions;
  23401. let iPrev = i1 - 2,
  23402. iNext = i1 + 1,
  23403. tPrev = pp[ iPrev ],
  23404. tNext = pp[ iNext ];
  23405. if ( tPrev === undefined ) {
  23406. switch ( this.getSettings_().endingStart ) {
  23407. case ZeroSlopeEnding:
  23408. // f'(t0) = 0
  23409. iPrev = i1;
  23410. tPrev = 2 * t0 - t1;
  23411. break;
  23412. case WrapAroundEnding:
  23413. // use the other end of the curve
  23414. iPrev = pp.length - 2;
  23415. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23416. break;
  23417. default: // ZeroCurvatureEnding
  23418. // f''(t0) = 0 a.k.a. Natural Spline
  23419. iPrev = i1;
  23420. tPrev = t1;
  23421. }
  23422. }
  23423. if ( tNext === undefined ) {
  23424. switch ( this.getSettings_().endingEnd ) {
  23425. case ZeroSlopeEnding:
  23426. // f'(tN) = 0
  23427. iNext = i1;
  23428. tNext = 2 * t1 - t0;
  23429. break;
  23430. case WrapAroundEnding:
  23431. // use the other end of the curve
  23432. iNext = 1;
  23433. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23434. break;
  23435. default: // ZeroCurvatureEnding
  23436. // f''(tN) = 0, a.k.a. Natural Spline
  23437. iNext = i1 - 1;
  23438. tNext = t0;
  23439. }
  23440. }
  23441. const halfDt = ( t1 - t0 ) * 0.5,
  23442. stride = this.valueSize;
  23443. this._weightPrev = halfDt / ( t0 - tPrev );
  23444. this._weightNext = halfDt / ( tNext - t1 );
  23445. this._offsetPrev = iPrev * stride;
  23446. this._offsetNext = iNext * stride;
  23447. }
  23448. interpolate_( i1, t0, t, t1 ) {
  23449. const result = this.resultBuffer,
  23450. values = this.sampleValues,
  23451. stride = this.valueSize,
  23452. o1 = i1 * stride, o0 = o1 - stride,
  23453. oP = this._offsetPrev, oN = this._offsetNext,
  23454. wP = this._weightPrev, wN = this._weightNext,
  23455. p = ( t - t0 ) / ( t1 - t0 ),
  23456. pp = p * p,
  23457. ppp = pp * p;
  23458. // evaluate polynomials
  23459. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23460. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23461. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23462. const sN = wN * ppp - wN * pp;
  23463. // combine data linearly
  23464. for ( let i = 0; i !== stride; ++ i ) {
  23465. result[ i ] =
  23466. sP * values[ oP + i ] +
  23467. s0 * values[ o0 + i ] +
  23468. s1 * values[ o1 + i ] +
  23469. sN * values[ oN + i ];
  23470. }
  23471. return result;
  23472. }
  23473. }
  23474. class LinearInterpolant extends Interpolant {
  23475. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23476. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23477. }
  23478. interpolate_( i1, t0, t, t1 ) {
  23479. const result = this.resultBuffer,
  23480. values = this.sampleValues,
  23481. stride = this.valueSize,
  23482. offset1 = i1 * stride,
  23483. offset0 = offset1 - stride,
  23484. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23485. weight0 = 1 - weight1;
  23486. for ( let i = 0; i !== stride; ++ i ) {
  23487. result[ i ] =
  23488. values[ offset0 + i ] * weight0 +
  23489. values[ offset1 + i ] * weight1;
  23490. }
  23491. return result;
  23492. }
  23493. }
  23494. /**
  23495. *
  23496. * Interpolant that evaluates to the sample value at the position preceding
  23497. * the parameter.
  23498. */
  23499. class DiscreteInterpolant extends Interpolant {
  23500. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23501. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23502. }
  23503. interpolate_( i1 /*, t0, t, t1 */ ) {
  23504. return this.copySampleValue_( i1 - 1 );
  23505. }
  23506. }
  23507. class KeyframeTrack {
  23508. constructor( name, times, values, interpolation ) {
  23509. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23510. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23511. this.name = name;
  23512. this.times = convertArray( times, this.TimeBufferType );
  23513. this.values = convertArray( values, this.ValueBufferType );
  23514. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23515. }
  23516. // Serialization (in static context, because of constructor invocation
  23517. // and automatic invocation of .toJSON):
  23518. static toJSON( track ) {
  23519. const trackType = track.constructor;
  23520. let json;
  23521. // derived classes can define a static toJSON method
  23522. if ( trackType.toJSON !== this.toJSON ) {
  23523. json = trackType.toJSON( track );
  23524. } else {
  23525. // by default, we assume the data can be serialized as-is
  23526. json = {
  23527. 'name': track.name,
  23528. 'times': convertArray( track.times, Array ),
  23529. 'values': convertArray( track.values, Array )
  23530. };
  23531. const interpolation = track.getInterpolation();
  23532. if ( interpolation !== track.DefaultInterpolation ) {
  23533. json.interpolation = interpolation;
  23534. }
  23535. }
  23536. json.type = track.ValueTypeName; // mandatory
  23537. return json;
  23538. }
  23539. InterpolantFactoryMethodDiscrete( result ) {
  23540. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23541. }
  23542. InterpolantFactoryMethodLinear( result ) {
  23543. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23544. }
  23545. InterpolantFactoryMethodSmooth( result ) {
  23546. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23547. }
  23548. setInterpolation( interpolation ) {
  23549. let factoryMethod;
  23550. switch ( interpolation ) {
  23551. case InterpolateDiscrete:
  23552. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23553. break;
  23554. case InterpolateLinear:
  23555. factoryMethod = this.InterpolantFactoryMethodLinear;
  23556. break;
  23557. case InterpolateSmooth:
  23558. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23559. break;
  23560. }
  23561. if ( factoryMethod === undefined ) {
  23562. const message = 'unsupported interpolation for ' +
  23563. this.ValueTypeName + ' keyframe track named ' + this.name;
  23564. if ( this.createInterpolant === undefined ) {
  23565. // fall back to default, unless the default itself is messed up
  23566. if ( interpolation !== this.DefaultInterpolation ) {
  23567. this.setInterpolation( this.DefaultInterpolation );
  23568. } else {
  23569. throw new Error( message ); // fatal, in this case
  23570. }
  23571. }
  23572. console.warn( 'THREE.KeyframeTrack:', message );
  23573. return this;
  23574. }
  23575. this.createInterpolant = factoryMethod;
  23576. return this;
  23577. }
  23578. getInterpolation() {
  23579. switch ( this.createInterpolant ) {
  23580. case this.InterpolantFactoryMethodDiscrete:
  23581. return InterpolateDiscrete;
  23582. case this.InterpolantFactoryMethodLinear:
  23583. return InterpolateLinear;
  23584. case this.InterpolantFactoryMethodSmooth:
  23585. return InterpolateSmooth;
  23586. }
  23587. }
  23588. getValueSize() {
  23589. return this.values.length / this.times.length;
  23590. }
  23591. // move all keyframes either forwards or backwards in time
  23592. shift( timeOffset ) {
  23593. if ( timeOffset !== 0.0 ) {
  23594. const times = this.times;
  23595. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23596. times[ i ] += timeOffset;
  23597. }
  23598. }
  23599. return this;
  23600. }
  23601. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23602. scale( timeScale ) {
  23603. if ( timeScale !== 1.0 ) {
  23604. const times = this.times;
  23605. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23606. times[ i ] *= timeScale;
  23607. }
  23608. }
  23609. return this;
  23610. }
  23611. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23612. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23613. trim( startTime, endTime ) {
  23614. const times = this.times,
  23615. nKeys = times.length;
  23616. let from = 0,
  23617. to = nKeys - 1;
  23618. while ( from !== nKeys && times[ from ] < startTime ) {
  23619. ++ from;
  23620. }
  23621. while ( to !== - 1 && times[ to ] > endTime ) {
  23622. -- to;
  23623. }
  23624. ++ to; // inclusive -> exclusive bound
  23625. if ( from !== 0 || to !== nKeys ) {
  23626. // empty tracks are forbidden, so keep at least one keyframe
  23627. if ( from >= to ) {
  23628. to = Math.max( to, 1 );
  23629. from = to - 1;
  23630. }
  23631. const stride = this.getValueSize();
  23632. this.times = arraySlice( times, from, to );
  23633. this.values = arraySlice( this.values, from * stride, to * stride );
  23634. }
  23635. return this;
  23636. }
  23637. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23638. validate() {
  23639. let valid = true;
  23640. const valueSize = this.getValueSize();
  23641. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23642. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23643. valid = false;
  23644. }
  23645. const times = this.times,
  23646. values = this.values,
  23647. nKeys = times.length;
  23648. if ( nKeys === 0 ) {
  23649. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23650. valid = false;
  23651. }
  23652. let prevTime = null;
  23653. for ( let i = 0; i !== nKeys; i ++ ) {
  23654. const currTime = times[ i ];
  23655. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23656. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23657. valid = false;
  23658. break;
  23659. }
  23660. if ( prevTime !== null && prevTime > currTime ) {
  23661. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23662. valid = false;
  23663. break;
  23664. }
  23665. prevTime = currTime;
  23666. }
  23667. if ( values !== undefined ) {
  23668. if ( isTypedArray( values ) ) {
  23669. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23670. const value = values[ i ];
  23671. if ( isNaN( value ) ) {
  23672. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23673. valid = false;
  23674. break;
  23675. }
  23676. }
  23677. }
  23678. }
  23679. return valid;
  23680. }
  23681. // removes equivalent sequential keys as common in morph target sequences
  23682. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23683. optimize() {
  23684. // times or values may be shared with other tracks, so overwriting is unsafe
  23685. const times = arraySlice( this.times ),
  23686. values = arraySlice( this.values ),
  23687. stride = this.getValueSize(),
  23688. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23689. lastIndex = times.length - 1;
  23690. let writeIndex = 1;
  23691. for ( let i = 1; i < lastIndex; ++ i ) {
  23692. let keep = false;
  23693. const time = times[ i ];
  23694. const timeNext = times[ i + 1 ];
  23695. // remove adjacent keyframes scheduled at the same time
  23696. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23697. if ( ! smoothInterpolation ) {
  23698. // remove unnecessary keyframes same as their neighbors
  23699. const offset = i * stride,
  23700. offsetP = offset - stride,
  23701. offsetN = offset + stride;
  23702. for ( let j = 0; j !== stride; ++ j ) {
  23703. const value = values[ offset + j ];
  23704. if ( value !== values[ offsetP + j ] ||
  23705. value !== values[ offsetN + j ] ) {
  23706. keep = true;
  23707. break;
  23708. }
  23709. }
  23710. } else {
  23711. keep = true;
  23712. }
  23713. }
  23714. // in-place compaction
  23715. if ( keep ) {
  23716. if ( i !== writeIndex ) {
  23717. times[ writeIndex ] = times[ i ];
  23718. const readOffset = i * stride,
  23719. writeOffset = writeIndex * stride;
  23720. for ( let j = 0; j !== stride; ++ j ) {
  23721. values[ writeOffset + j ] = values[ readOffset + j ];
  23722. }
  23723. }
  23724. ++ writeIndex;
  23725. }
  23726. }
  23727. // flush last keyframe (compaction looks ahead)
  23728. if ( lastIndex > 0 ) {
  23729. times[ writeIndex ] = times[ lastIndex ];
  23730. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23731. values[ writeOffset + j ] = values[ readOffset + j ];
  23732. }
  23733. ++ writeIndex;
  23734. }
  23735. if ( writeIndex !== times.length ) {
  23736. this.times = arraySlice( times, 0, writeIndex );
  23737. this.values = arraySlice( values, 0, writeIndex * stride );
  23738. } else {
  23739. this.times = times;
  23740. this.values = values;
  23741. }
  23742. return this;
  23743. }
  23744. clone() {
  23745. const times = arraySlice( this.times, 0 );
  23746. const values = arraySlice( this.values, 0 );
  23747. const TypedKeyframeTrack = this.constructor;
  23748. const track = new TypedKeyframeTrack( this.name, times, values );
  23749. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23750. track.createInterpolant = this.createInterpolant;
  23751. return track;
  23752. }
  23753. }
  23754. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23755. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23756. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23757. /**
  23758. * A Track of Boolean keyframe values.
  23759. */
  23760. class BooleanKeyframeTrack extends KeyframeTrack {}
  23761. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23762. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23763. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23764. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23765. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23766. /**
  23767. * A Track of keyframe values that represent color.
  23768. */
  23769. class ColorKeyframeTrack extends KeyframeTrack {}
  23770. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23771. /**
  23772. * A Track of numeric keyframe values.
  23773. */
  23774. class NumberKeyframeTrack extends KeyframeTrack {}
  23775. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23776. /**
  23777. * Spherical linear unit quaternion interpolant.
  23778. */
  23779. class QuaternionLinearInterpolant extends Interpolant {
  23780. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23781. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23782. }
  23783. interpolate_( i1, t0, t, t1 ) {
  23784. const result = this.resultBuffer,
  23785. values = this.sampleValues,
  23786. stride = this.valueSize,
  23787. alpha = ( t - t0 ) / ( t1 - t0 );
  23788. let offset = i1 * stride;
  23789. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23790. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23791. }
  23792. return result;
  23793. }
  23794. }
  23795. /**
  23796. * A Track of quaternion keyframe values.
  23797. */
  23798. class QuaternionKeyframeTrack extends KeyframeTrack {
  23799. InterpolantFactoryMethodLinear( result ) {
  23800. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23801. }
  23802. }
  23803. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23804. // ValueBufferType is inherited
  23805. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23806. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23807. /**
  23808. * A Track that interpolates Strings
  23809. */
  23810. class StringKeyframeTrack extends KeyframeTrack {}
  23811. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23812. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23813. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23814. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23815. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23816. /**
  23817. * A Track of vectored keyframe values.
  23818. */
  23819. class VectorKeyframeTrack extends KeyframeTrack {}
  23820. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23821. class AnimationClip {
  23822. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23823. this.name = name;
  23824. this.tracks = tracks;
  23825. this.duration = duration;
  23826. this.blendMode = blendMode;
  23827. this.uuid = generateUUID();
  23828. // this means it should figure out its duration by scanning the tracks
  23829. if ( this.duration < 0 ) {
  23830. this.resetDuration();
  23831. }
  23832. }
  23833. static parse( json ) {
  23834. const tracks = [],
  23835. jsonTracks = json.tracks,
  23836. frameTime = 1.0 / ( json.fps || 1.0 );
  23837. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23838. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23839. }
  23840. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23841. clip.uuid = json.uuid;
  23842. return clip;
  23843. }
  23844. static toJSON( clip ) {
  23845. const tracks = [],
  23846. clipTracks = clip.tracks;
  23847. const json = {
  23848. 'name': clip.name,
  23849. 'duration': clip.duration,
  23850. 'tracks': tracks,
  23851. 'uuid': clip.uuid,
  23852. 'blendMode': clip.blendMode
  23853. };
  23854. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23855. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23856. }
  23857. return json;
  23858. }
  23859. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23860. const numMorphTargets = morphTargetSequence.length;
  23861. const tracks = [];
  23862. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23863. let times = [];
  23864. let values = [];
  23865. times.push(
  23866. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23867. i,
  23868. ( i + 1 ) % numMorphTargets );
  23869. values.push( 0, 1, 0 );
  23870. const order = getKeyframeOrder( times );
  23871. times = sortedArray( times, 1, order );
  23872. values = sortedArray( values, 1, order );
  23873. // if there is a key at the first frame, duplicate it as the
  23874. // last frame as well for perfect loop.
  23875. if ( ! noLoop && times[ 0 ] === 0 ) {
  23876. times.push( numMorphTargets );
  23877. values.push( values[ 0 ] );
  23878. }
  23879. tracks.push(
  23880. new NumberKeyframeTrack(
  23881. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23882. times, values
  23883. ).scale( 1.0 / fps ) );
  23884. }
  23885. return new this( name, - 1, tracks );
  23886. }
  23887. static findByName( objectOrClipArray, name ) {
  23888. let clipArray = objectOrClipArray;
  23889. if ( ! Array.isArray( objectOrClipArray ) ) {
  23890. const o = objectOrClipArray;
  23891. clipArray = o.geometry && o.geometry.animations || o.animations;
  23892. }
  23893. for ( let i = 0; i < clipArray.length; i ++ ) {
  23894. if ( clipArray[ i ].name === name ) {
  23895. return clipArray[ i ];
  23896. }
  23897. }
  23898. return null;
  23899. }
  23900. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23901. const animationToMorphTargets = {};
  23902. // tested with https://regex101.com/ on trick sequences
  23903. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23904. const pattern = /^([\w-]*?)([\d]+)$/;
  23905. // sort morph target names into animation groups based
  23906. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23907. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23908. const morphTarget = morphTargets[ i ];
  23909. const parts = morphTarget.name.match( pattern );
  23910. if ( parts && parts.length > 1 ) {
  23911. const name = parts[ 1 ];
  23912. let animationMorphTargets = animationToMorphTargets[ name ];
  23913. if ( ! animationMorphTargets ) {
  23914. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23915. }
  23916. animationMorphTargets.push( morphTarget );
  23917. }
  23918. }
  23919. const clips = [];
  23920. for ( const name in animationToMorphTargets ) {
  23921. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23922. }
  23923. return clips;
  23924. }
  23925. // parse the animation.hierarchy format
  23926. static parseAnimation( animation, bones ) {
  23927. if ( ! animation ) {
  23928. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23929. return null;
  23930. }
  23931. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23932. // only return track if there are actually keys.
  23933. if ( animationKeys.length !== 0 ) {
  23934. const times = [];
  23935. const values = [];
  23936. flattenJSON( animationKeys, times, values, propertyName );
  23937. // empty keys are filtered out, so check again
  23938. if ( times.length !== 0 ) {
  23939. destTracks.push( new trackType( trackName, times, values ) );
  23940. }
  23941. }
  23942. };
  23943. const tracks = [];
  23944. const clipName = animation.name || 'default';
  23945. const fps = animation.fps || 30;
  23946. const blendMode = animation.blendMode;
  23947. // automatic length determination in AnimationClip.
  23948. let duration = animation.length || - 1;
  23949. const hierarchyTracks = animation.hierarchy || [];
  23950. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23951. const animationKeys = hierarchyTracks[ h ].keys;
  23952. // skip empty tracks
  23953. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23954. // process morph targets
  23955. if ( animationKeys[ 0 ].morphTargets ) {
  23956. // figure out all morph targets used in this track
  23957. const morphTargetNames = {};
  23958. let k;
  23959. for ( k = 0; k < animationKeys.length; k ++ ) {
  23960. if ( animationKeys[ k ].morphTargets ) {
  23961. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23962. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23963. }
  23964. }
  23965. }
  23966. // create a track for each morph target with all zero
  23967. // morphTargetInfluences except for the keys in which
  23968. // the morphTarget is named.
  23969. for ( const morphTargetName in morphTargetNames ) {
  23970. const times = [];
  23971. const values = [];
  23972. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23973. const animationKey = animationKeys[ k ];
  23974. times.push( animationKey.time );
  23975. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23976. }
  23977. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23978. }
  23979. duration = morphTargetNames.length * fps;
  23980. } else {
  23981. // ...assume skeletal animation
  23982. const boneName = '.bones[' + bones[ h ].name + ']';
  23983. addNonemptyTrack(
  23984. VectorKeyframeTrack, boneName + '.position',
  23985. animationKeys, 'pos', tracks );
  23986. addNonemptyTrack(
  23987. QuaternionKeyframeTrack, boneName + '.quaternion',
  23988. animationKeys, 'rot', tracks );
  23989. addNonemptyTrack(
  23990. VectorKeyframeTrack, boneName + '.scale',
  23991. animationKeys, 'scl', tracks );
  23992. }
  23993. }
  23994. if ( tracks.length === 0 ) {
  23995. return null;
  23996. }
  23997. const clip = new this( clipName, duration, tracks, blendMode );
  23998. return clip;
  23999. }
  24000. resetDuration() {
  24001. const tracks = this.tracks;
  24002. let duration = 0;
  24003. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  24004. const track = this.tracks[ i ];
  24005. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  24006. }
  24007. this.duration = duration;
  24008. return this;
  24009. }
  24010. trim() {
  24011. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24012. this.tracks[ i ].trim( 0, this.duration );
  24013. }
  24014. return this;
  24015. }
  24016. validate() {
  24017. let valid = true;
  24018. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24019. valid = valid && this.tracks[ i ].validate();
  24020. }
  24021. return valid;
  24022. }
  24023. optimize() {
  24024. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24025. this.tracks[ i ].optimize();
  24026. }
  24027. return this;
  24028. }
  24029. clone() {
  24030. const tracks = [];
  24031. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24032. tracks.push( this.tracks[ i ].clone() );
  24033. }
  24034. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  24035. }
  24036. toJSON() {
  24037. return this.constructor.toJSON( this );
  24038. }
  24039. }
  24040. function getTrackTypeForValueTypeName( typeName ) {
  24041. switch ( typeName.toLowerCase() ) {
  24042. case 'scalar':
  24043. case 'double':
  24044. case 'float':
  24045. case 'number':
  24046. case 'integer':
  24047. return NumberKeyframeTrack;
  24048. case 'vector':
  24049. case 'vector2':
  24050. case 'vector3':
  24051. case 'vector4':
  24052. return VectorKeyframeTrack;
  24053. case 'color':
  24054. return ColorKeyframeTrack;
  24055. case 'quaternion':
  24056. return QuaternionKeyframeTrack;
  24057. case 'bool':
  24058. case 'boolean':
  24059. return BooleanKeyframeTrack;
  24060. case 'string':
  24061. return StringKeyframeTrack;
  24062. }
  24063. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  24064. }
  24065. function parseKeyframeTrack( json ) {
  24066. if ( json.type === undefined ) {
  24067. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  24068. }
  24069. const trackType = getTrackTypeForValueTypeName( json.type );
  24070. if ( json.times === undefined ) {
  24071. const times = [], values = [];
  24072. flattenJSON( json.keys, times, values, 'value' );
  24073. json.times = times;
  24074. json.values = values;
  24075. }
  24076. // derived classes can define a static parse method
  24077. if ( trackType.parse !== undefined ) {
  24078. return trackType.parse( json );
  24079. } else {
  24080. // by default, we assume a constructor compatible with the base
  24081. return new trackType( json.name, json.times, json.values, json.interpolation );
  24082. }
  24083. }
  24084. const Cache = {
  24085. enabled: false,
  24086. files: {},
  24087. add: function ( key, file ) {
  24088. if ( this.enabled === false ) return;
  24089. // console.log( 'THREE.Cache', 'Adding key:', key );
  24090. this.files[ key ] = file;
  24091. },
  24092. get: function ( key ) {
  24093. if ( this.enabled === false ) return;
  24094. // console.log( 'THREE.Cache', 'Checking key:', key );
  24095. return this.files[ key ];
  24096. },
  24097. remove: function ( key ) {
  24098. delete this.files[ key ];
  24099. },
  24100. clear: function () {
  24101. this.files = {};
  24102. }
  24103. };
  24104. class LoadingManager {
  24105. constructor( onLoad, onProgress, onError ) {
  24106. const scope = this;
  24107. let isLoading = false;
  24108. let itemsLoaded = 0;
  24109. let itemsTotal = 0;
  24110. let urlModifier = undefined;
  24111. const handlers = [];
  24112. // Refer to #5689 for the reason why we don't set .onStart
  24113. // in the constructor
  24114. this.onStart = undefined;
  24115. this.onLoad = onLoad;
  24116. this.onProgress = onProgress;
  24117. this.onError = onError;
  24118. this.itemStart = function ( url ) {
  24119. itemsTotal ++;
  24120. if ( isLoading === false ) {
  24121. if ( scope.onStart !== undefined ) {
  24122. scope.onStart( url, itemsLoaded, itemsTotal );
  24123. }
  24124. }
  24125. isLoading = true;
  24126. };
  24127. this.itemEnd = function ( url ) {
  24128. itemsLoaded ++;
  24129. if ( scope.onProgress !== undefined ) {
  24130. scope.onProgress( url, itemsLoaded, itemsTotal );
  24131. }
  24132. if ( itemsLoaded === itemsTotal ) {
  24133. isLoading = false;
  24134. if ( scope.onLoad !== undefined ) {
  24135. scope.onLoad();
  24136. }
  24137. }
  24138. };
  24139. this.itemError = function ( url ) {
  24140. if ( scope.onError !== undefined ) {
  24141. scope.onError( url );
  24142. }
  24143. };
  24144. this.resolveURL = function ( url ) {
  24145. if ( urlModifier ) {
  24146. return urlModifier( url );
  24147. }
  24148. return url;
  24149. };
  24150. this.setURLModifier = function ( transform ) {
  24151. urlModifier = transform;
  24152. return this;
  24153. };
  24154. this.addHandler = function ( regex, loader ) {
  24155. handlers.push( regex, loader );
  24156. return this;
  24157. };
  24158. this.removeHandler = function ( regex ) {
  24159. const index = handlers.indexOf( regex );
  24160. if ( index !== - 1 ) {
  24161. handlers.splice( index, 2 );
  24162. }
  24163. return this;
  24164. };
  24165. this.getHandler = function ( file ) {
  24166. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  24167. const regex = handlers[ i ];
  24168. const loader = handlers[ i + 1 ];
  24169. if ( regex.global ) regex.lastIndex = 0; // see #17920
  24170. if ( regex.test( file ) ) {
  24171. return loader;
  24172. }
  24173. }
  24174. return null;
  24175. };
  24176. }
  24177. }
  24178. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  24179. class Loader {
  24180. constructor( manager ) {
  24181. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24182. this.crossOrigin = 'anonymous';
  24183. this.withCredentials = false;
  24184. this.path = '';
  24185. this.resourcePath = '';
  24186. this.requestHeader = {};
  24187. }
  24188. load( /* url, onLoad, onProgress, onError */ ) {}
  24189. loadAsync( url, onProgress ) {
  24190. const scope = this;
  24191. return new Promise( function ( resolve, reject ) {
  24192. scope.load( url, resolve, onProgress, reject );
  24193. } );
  24194. }
  24195. parse( /* data */ ) {}
  24196. setCrossOrigin( crossOrigin ) {
  24197. this.crossOrigin = crossOrigin;
  24198. return this;
  24199. }
  24200. setWithCredentials( value ) {
  24201. this.withCredentials = value;
  24202. return this;
  24203. }
  24204. setPath( path ) {
  24205. this.path = path;
  24206. return this;
  24207. }
  24208. setResourcePath( resourcePath ) {
  24209. this.resourcePath = resourcePath;
  24210. return this;
  24211. }
  24212. setRequestHeader( requestHeader ) {
  24213. this.requestHeader = requestHeader;
  24214. return this;
  24215. }
  24216. }
  24217. const loading = {};
  24218. class HttpError extends Error {
  24219. constructor( message, response ) {
  24220. super( message );
  24221. this.response = response;
  24222. }
  24223. }
  24224. class FileLoader extends Loader {
  24225. constructor( manager ) {
  24226. super( manager );
  24227. }
  24228. load( url, onLoad, onProgress, onError ) {
  24229. if ( url === undefined ) url = '';
  24230. if ( this.path !== undefined ) url = this.path + url;
  24231. url = this.manager.resolveURL( url );
  24232. const cached = Cache.get( url );
  24233. if ( cached !== undefined ) {
  24234. this.manager.itemStart( url );
  24235. setTimeout( () => {
  24236. if ( onLoad ) onLoad( cached );
  24237. this.manager.itemEnd( url );
  24238. }, 0 );
  24239. return cached;
  24240. }
  24241. // Check if request is duplicate
  24242. if ( loading[ url ] !== undefined ) {
  24243. loading[ url ].push( {
  24244. onLoad: onLoad,
  24245. onProgress: onProgress,
  24246. onError: onError
  24247. } );
  24248. return;
  24249. }
  24250. // Initialise array for duplicate requests
  24251. loading[ url ] = [];
  24252. loading[ url ].push( {
  24253. onLoad: onLoad,
  24254. onProgress: onProgress,
  24255. onError: onError,
  24256. } );
  24257. // create request
  24258. const req = new Request( url, {
  24259. headers: new Headers( this.requestHeader ),
  24260. credentials: this.withCredentials ? 'include' : 'same-origin',
  24261. // An abort controller could be added within a future PR
  24262. } );
  24263. // record states ( avoid data race )
  24264. const mimeType = this.mimeType;
  24265. const responseType = this.responseType;
  24266. // start the fetch
  24267. fetch( req )
  24268. .then( response => {
  24269. if ( response.status === 200 || response.status === 0 ) {
  24270. // Some browsers return HTTP Status 0 when using non-http protocol
  24271. // e.g. 'file://' or 'data://'. Handle as success.
  24272. if ( response.status === 0 ) {
  24273. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24274. }
  24275. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24276. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  24277. return response;
  24278. }
  24279. const callbacks = loading[ url ];
  24280. const reader = response.body.getReader();
  24281. // Nginx needs X-File-Size check
  24282. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24283. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  24284. const total = contentLength ? parseInt( contentLength ) : 0;
  24285. const lengthComputable = total !== 0;
  24286. let loaded = 0;
  24287. // periodically read data into the new stream tracking while download progress
  24288. const stream = new ReadableStream( {
  24289. start( controller ) {
  24290. readData();
  24291. function readData() {
  24292. reader.read().then( ( { done, value } ) => {
  24293. if ( done ) {
  24294. controller.close();
  24295. } else {
  24296. loaded += value.byteLength;
  24297. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  24298. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24299. const callback = callbacks[ i ];
  24300. if ( callback.onProgress ) callback.onProgress( event );
  24301. }
  24302. controller.enqueue( value );
  24303. readData();
  24304. }
  24305. } );
  24306. }
  24307. }
  24308. } );
  24309. return new Response( stream );
  24310. } else {
  24311. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  24312. }
  24313. } )
  24314. .then( response => {
  24315. switch ( responseType ) {
  24316. case 'arraybuffer':
  24317. return response.arrayBuffer();
  24318. case 'blob':
  24319. return response.blob();
  24320. case 'document':
  24321. return response.text()
  24322. .then( text => {
  24323. const parser = new DOMParser();
  24324. return parser.parseFromString( text, mimeType );
  24325. } );
  24326. case 'json':
  24327. return response.json();
  24328. default:
  24329. if ( mimeType === undefined ) {
  24330. return response.text();
  24331. } else {
  24332. // sniff encoding
  24333. const re = /charset="?([^;"\s]*)"?/i;
  24334. const exec = re.exec( mimeType );
  24335. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  24336. const decoder = new TextDecoder( label );
  24337. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  24338. }
  24339. }
  24340. } )
  24341. .then( data => {
  24342. // Add to cache only on HTTP success, so that we do not cache
  24343. // error response bodies as proper responses to requests.
  24344. Cache.add( url, data );
  24345. const callbacks = loading[ url ];
  24346. delete loading[ url ];
  24347. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24348. const callback = callbacks[ i ];
  24349. if ( callback.onLoad ) callback.onLoad( data );
  24350. }
  24351. } )
  24352. .catch( err => {
  24353. // Abort errors and other errors are handled the same
  24354. const callbacks = loading[ url ];
  24355. if ( callbacks === undefined ) {
  24356. // When onLoad was called and url was deleted in `loading`
  24357. this.manager.itemError( url );
  24358. throw err;
  24359. }
  24360. delete loading[ url ];
  24361. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24362. const callback = callbacks[ i ];
  24363. if ( callback.onError ) callback.onError( err );
  24364. }
  24365. this.manager.itemError( url );
  24366. } )
  24367. .finally( () => {
  24368. this.manager.itemEnd( url );
  24369. } );
  24370. this.manager.itemStart( url );
  24371. }
  24372. setResponseType( value ) {
  24373. this.responseType = value;
  24374. return this;
  24375. }
  24376. setMimeType( value ) {
  24377. this.mimeType = value;
  24378. return this;
  24379. }
  24380. }
  24381. class AnimationLoader extends Loader {
  24382. constructor( manager ) {
  24383. super( manager );
  24384. }
  24385. load( url, onLoad, onProgress, onError ) {
  24386. const scope = this;
  24387. const loader = new FileLoader( this.manager );
  24388. loader.setPath( this.path );
  24389. loader.setRequestHeader( this.requestHeader );
  24390. loader.setWithCredentials( this.withCredentials );
  24391. loader.load( url, function ( text ) {
  24392. try {
  24393. onLoad( scope.parse( JSON.parse( text ) ) );
  24394. } catch ( e ) {
  24395. if ( onError ) {
  24396. onError( e );
  24397. } else {
  24398. console.error( e );
  24399. }
  24400. scope.manager.itemError( url );
  24401. }
  24402. }, onProgress, onError );
  24403. }
  24404. parse( json ) {
  24405. const animations = [];
  24406. for ( let i = 0; i < json.length; i ++ ) {
  24407. const clip = AnimationClip.parse( json[ i ] );
  24408. animations.push( clip );
  24409. }
  24410. return animations;
  24411. }
  24412. }
  24413. /**
  24414. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24415. *
  24416. * Sub classes have to implement the parse() method which will be used in load().
  24417. */
  24418. class CompressedTextureLoader extends Loader {
  24419. constructor( manager ) {
  24420. super( manager );
  24421. }
  24422. load( url, onLoad, onProgress, onError ) {
  24423. const scope = this;
  24424. const images = [];
  24425. const texture = new CompressedTexture();
  24426. const loader = new FileLoader( this.manager );
  24427. loader.setPath( this.path );
  24428. loader.setResponseType( 'arraybuffer' );
  24429. loader.setRequestHeader( this.requestHeader );
  24430. loader.setWithCredentials( scope.withCredentials );
  24431. let loaded = 0;
  24432. function loadTexture( i ) {
  24433. loader.load( url[ i ], function ( buffer ) {
  24434. const texDatas = scope.parse( buffer, true );
  24435. images[ i ] = {
  24436. width: texDatas.width,
  24437. height: texDatas.height,
  24438. format: texDatas.format,
  24439. mipmaps: texDatas.mipmaps
  24440. };
  24441. loaded += 1;
  24442. if ( loaded === 6 ) {
  24443. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24444. texture.image = images;
  24445. texture.format = texDatas.format;
  24446. texture.needsUpdate = true;
  24447. if ( onLoad ) onLoad( texture );
  24448. }
  24449. }, onProgress, onError );
  24450. }
  24451. if ( Array.isArray( url ) ) {
  24452. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24453. loadTexture( i );
  24454. }
  24455. } else {
  24456. // compressed cubemap texture stored in a single DDS file
  24457. loader.load( url, function ( buffer ) {
  24458. const texDatas = scope.parse( buffer, true );
  24459. if ( texDatas.isCubemap ) {
  24460. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24461. for ( let f = 0; f < faces; f ++ ) {
  24462. images[ f ] = { mipmaps: [] };
  24463. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24464. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24465. images[ f ].format = texDatas.format;
  24466. images[ f ].width = texDatas.width;
  24467. images[ f ].height = texDatas.height;
  24468. }
  24469. }
  24470. texture.image = images;
  24471. } else {
  24472. texture.image.width = texDatas.width;
  24473. texture.image.height = texDatas.height;
  24474. texture.mipmaps = texDatas.mipmaps;
  24475. }
  24476. if ( texDatas.mipmapCount === 1 ) {
  24477. texture.minFilter = LinearFilter;
  24478. }
  24479. texture.format = texDatas.format;
  24480. texture.needsUpdate = true;
  24481. if ( onLoad ) onLoad( texture );
  24482. }, onProgress, onError );
  24483. }
  24484. return texture;
  24485. }
  24486. }
  24487. class ImageLoader extends Loader {
  24488. constructor( manager ) {
  24489. super( manager );
  24490. }
  24491. load( url, onLoad, onProgress, onError ) {
  24492. if ( this.path !== undefined ) url = this.path + url;
  24493. url = this.manager.resolveURL( url );
  24494. const scope = this;
  24495. const cached = Cache.get( url );
  24496. if ( cached !== undefined ) {
  24497. scope.manager.itemStart( url );
  24498. setTimeout( function () {
  24499. if ( onLoad ) onLoad( cached );
  24500. scope.manager.itemEnd( url );
  24501. }, 0 );
  24502. return cached;
  24503. }
  24504. const image = createElementNS( 'img' );
  24505. function onImageLoad() {
  24506. removeEventListeners();
  24507. Cache.add( url, this );
  24508. if ( onLoad ) onLoad( this );
  24509. scope.manager.itemEnd( url );
  24510. }
  24511. function onImageError( event ) {
  24512. removeEventListeners();
  24513. if ( onError ) onError( event );
  24514. scope.manager.itemError( url );
  24515. scope.manager.itemEnd( url );
  24516. }
  24517. function removeEventListeners() {
  24518. image.removeEventListener( 'load', onImageLoad, false );
  24519. image.removeEventListener( 'error', onImageError, false );
  24520. }
  24521. image.addEventListener( 'load', onImageLoad, false );
  24522. image.addEventListener( 'error', onImageError, false );
  24523. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24524. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24525. }
  24526. scope.manager.itemStart( url );
  24527. image.src = url;
  24528. return image;
  24529. }
  24530. }
  24531. class CubeTextureLoader extends Loader {
  24532. constructor( manager ) {
  24533. super( manager );
  24534. }
  24535. load( urls, onLoad, onProgress, onError ) {
  24536. const texture = new CubeTexture();
  24537. const loader = new ImageLoader( this.manager );
  24538. loader.setCrossOrigin( this.crossOrigin );
  24539. loader.setPath( this.path );
  24540. let loaded = 0;
  24541. function loadTexture( i ) {
  24542. loader.load( urls[ i ], function ( image ) {
  24543. texture.images[ i ] = image;
  24544. loaded ++;
  24545. if ( loaded === 6 ) {
  24546. texture.needsUpdate = true;
  24547. if ( onLoad ) onLoad( texture );
  24548. }
  24549. }, undefined, onError );
  24550. }
  24551. for ( let i = 0; i < urls.length; ++ i ) {
  24552. loadTexture( i );
  24553. }
  24554. return texture;
  24555. }
  24556. }
  24557. /**
  24558. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24559. *
  24560. * Sub classes have to implement the parse() method which will be used in load().
  24561. */
  24562. class DataTextureLoader extends Loader {
  24563. constructor( manager ) {
  24564. super( manager );
  24565. }
  24566. load( url, onLoad, onProgress, onError ) {
  24567. const scope = this;
  24568. const texture = new DataTexture();
  24569. const loader = new FileLoader( this.manager );
  24570. loader.setResponseType( 'arraybuffer' );
  24571. loader.setRequestHeader( this.requestHeader );
  24572. loader.setPath( this.path );
  24573. loader.setWithCredentials( scope.withCredentials );
  24574. loader.load( url, function ( buffer ) {
  24575. const texData = scope.parse( buffer );
  24576. if ( ! texData ) return;
  24577. if ( texData.image !== undefined ) {
  24578. texture.image = texData.image;
  24579. } else if ( texData.data !== undefined ) {
  24580. texture.image.width = texData.width;
  24581. texture.image.height = texData.height;
  24582. texture.image.data = texData.data;
  24583. }
  24584. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24585. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24586. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24587. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24588. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24589. if ( texData.encoding !== undefined ) {
  24590. texture.encoding = texData.encoding;
  24591. }
  24592. if ( texData.flipY !== undefined ) {
  24593. texture.flipY = texData.flipY;
  24594. }
  24595. if ( texData.format !== undefined ) {
  24596. texture.format = texData.format;
  24597. }
  24598. if ( texData.type !== undefined ) {
  24599. texture.type = texData.type;
  24600. }
  24601. if ( texData.mipmaps !== undefined ) {
  24602. texture.mipmaps = texData.mipmaps;
  24603. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24604. }
  24605. if ( texData.mipmapCount === 1 ) {
  24606. texture.minFilter = LinearFilter;
  24607. }
  24608. if ( texData.generateMipmaps !== undefined ) {
  24609. texture.generateMipmaps = texData.generateMipmaps;
  24610. }
  24611. texture.needsUpdate = true;
  24612. if ( onLoad ) onLoad( texture, texData );
  24613. }, onProgress, onError );
  24614. return texture;
  24615. }
  24616. }
  24617. class TextureLoader extends Loader {
  24618. constructor( manager ) {
  24619. super( manager );
  24620. }
  24621. load( url, onLoad, onProgress, onError ) {
  24622. const texture = new Texture();
  24623. const loader = new ImageLoader( this.manager );
  24624. loader.setCrossOrigin( this.crossOrigin );
  24625. loader.setPath( this.path );
  24626. loader.load( url, function ( image ) {
  24627. texture.image = image;
  24628. texture.needsUpdate = true;
  24629. if ( onLoad !== undefined ) {
  24630. onLoad( texture );
  24631. }
  24632. }, onProgress, onError );
  24633. return texture;
  24634. }
  24635. }
  24636. class Light extends Object3D {
  24637. constructor( color, intensity = 1 ) {
  24638. super();
  24639. this.isLight = true;
  24640. this.type = 'Light';
  24641. this.color = new Color( color );
  24642. this.intensity = intensity;
  24643. }
  24644. dispose() {
  24645. // Empty here in base class; some subclasses override.
  24646. }
  24647. copy( source, recursive ) {
  24648. super.copy( source, recursive );
  24649. this.color.copy( source.color );
  24650. this.intensity = source.intensity;
  24651. return this;
  24652. }
  24653. toJSON( meta ) {
  24654. const data = super.toJSON( meta );
  24655. data.object.color = this.color.getHex();
  24656. data.object.intensity = this.intensity;
  24657. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24658. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24659. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24660. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24661. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24662. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24663. return data;
  24664. }
  24665. }
  24666. class HemisphereLight extends Light {
  24667. constructor( skyColor, groundColor, intensity ) {
  24668. super( skyColor, intensity );
  24669. this.isHemisphereLight = true;
  24670. this.type = 'HemisphereLight';
  24671. this.position.copy( Object3D.DEFAULT_UP );
  24672. this.updateMatrix();
  24673. this.groundColor = new Color( groundColor );
  24674. }
  24675. copy( source, recursive ) {
  24676. super.copy( source, recursive );
  24677. this.groundColor.copy( source.groundColor );
  24678. return this;
  24679. }
  24680. }
  24681. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24682. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24683. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24684. class LightShadow {
  24685. constructor( camera ) {
  24686. this.camera = camera;
  24687. this.bias = 0;
  24688. this.normalBias = 0;
  24689. this.radius = 1;
  24690. this.blurSamples = 8;
  24691. this.mapSize = new Vector2( 512, 512 );
  24692. this.map = null;
  24693. this.mapPass = null;
  24694. this.matrix = new Matrix4();
  24695. this.autoUpdate = true;
  24696. this.needsUpdate = false;
  24697. this._frustum = new Frustum();
  24698. this._frameExtents = new Vector2( 1, 1 );
  24699. this._viewportCount = 1;
  24700. this._viewports = [
  24701. new Vector4( 0, 0, 1, 1 )
  24702. ];
  24703. }
  24704. getViewportCount() {
  24705. return this._viewportCount;
  24706. }
  24707. getFrustum() {
  24708. return this._frustum;
  24709. }
  24710. updateMatrices( light ) {
  24711. const shadowCamera = this.camera;
  24712. const shadowMatrix = this.matrix;
  24713. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24714. shadowCamera.position.copy( _lightPositionWorld$1 );
  24715. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24716. shadowCamera.lookAt( _lookTarget$1 );
  24717. shadowCamera.updateMatrixWorld();
  24718. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24719. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24720. shadowMatrix.set(
  24721. 0.5, 0.0, 0.0, 0.5,
  24722. 0.0, 0.5, 0.0, 0.5,
  24723. 0.0, 0.0, 0.5, 0.5,
  24724. 0.0, 0.0, 0.0, 1.0
  24725. );
  24726. shadowMatrix.multiply( _projScreenMatrix$1 );
  24727. }
  24728. getViewport( viewportIndex ) {
  24729. return this._viewports[ viewportIndex ];
  24730. }
  24731. getFrameExtents() {
  24732. return this._frameExtents;
  24733. }
  24734. dispose() {
  24735. if ( this.map ) {
  24736. this.map.dispose();
  24737. }
  24738. if ( this.mapPass ) {
  24739. this.mapPass.dispose();
  24740. }
  24741. }
  24742. copy( source ) {
  24743. this.camera = source.camera.clone();
  24744. this.bias = source.bias;
  24745. this.radius = source.radius;
  24746. this.mapSize.copy( source.mapSize );
  24747. return this;
  24748. }
  24749. clone() {
  24750. return new this.constructor().copy( this );
  24751. }
  24752. toJSON() {
  24753. const object = {};
  24754. if ( this.bias !== 0 ) object.bias = this.bias;
  24755. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24756. if ( this.radius !== 1 ) object.radius = this.radius;
  24757. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24758. object.camera = this.camera.toJSON( false ).object;
  24759. delete object.camera.matrix;
  24760. return object;
  24761. }
  24762. }
  24763. class SpotLightShadow extends LightShadow {
  24764. constructor() {
  24765. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24766. this.isSpotLightShadow = true;
  24767. this.focus = 1;
  24768. }
  24769. updateMatrices( light ) {
  24770. const camera = this.camera;
  24771. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24772. const aspect = this.mapSize.width / this.mapSize.height;
  24773. const far = light.distance || camera.far;
  24774. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24775. camera.fov = fov;
  24776. camera.aspect = aspect;
  24777. camera.far = far;
  24778. camera.updateProjectionMatrix();
  24779. }
  24780. super.updateMatrices( light );
  24781. }
  24782. copy( source ) {
  24783. super.copy( source );
  24784. this.focus = source.focus;
  24785. return this;
  24786. }
  24787. }
  24788. class SpotLight extends Light {
  24789. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  24790. super( color, intensity );
  24791. this.isSpotLight = true;
  24792. this.type = 'SpotLight';
  24793. this.position.copy( Object3D.DEFAULT_UP );
  24794. this.updateMatrix();
  24795. this.target = new Object3D();
  24796. this.distance = distance;
  24797. this.angle = angle;
  24798. this.penumbra = penumbra;
  24799. this.decay = decay;
  24800. this.map = null;
  24801. this.shadow = new SpotLightShadow();
  24802. }
  24803. get power() {
  24804. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24805. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24806. return this.intensity * Math.PI;
  24807. }
  24808. set power( power ) {
  24809. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24810. this.intensity = power / Math.PI;
  24811. }
  24812. dispose() {
  24813. this.shadow.dispose();
  24814. }
  24815. copy( source, recursive ) {
  24816. super.copy( source, recursive );
  24817. this.distance = source.distance;
  24818. this.angle = source.angle;
  24819. this.penumbra = source.penumbra;
  24820. this.decay = source.decay;
  24821. this.target = source.target.clone();
  24822. this.shadow = source.shadow.clone();
  24823. return this;
  24824. }
  24825. }
  24826. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24827. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24828. const _lookTarget = /*@__PURE__*/ new Vector3();
  24829. class PointLightShadow extends LightShadow {
  24830. constructor() {
  24831. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24832. this.isPointLightShadow = true;
  24833. this._frameExtents = new Vector2( 4, 2 );
  24834. this._viewportCount = 6;
  24835. this._viewports = [
  24836. // These viewports map a cube-map onto a 2D texture with the
  24837. // following orientation:
  24838. //
  24839. // xzXZ
  24840. // y Y
  24841. //
  24842. // X - Positive x direction
  24843. // x - Negative x direction
  24844. // Y - Positive y direction
  24845. // y - Negative y direction
  24846. // Z - Positive z direction
  24847. // z - Negative z direction
  24848. // positive X
  24849. new Vector4( 2, 1, 1, 1 ),
  24850. // negative X
  24851. new Vector4( 0, 1, 1, 1 ),
  24852. // positive Z
  24853. new Vector4( 3, 1, 1, 1 ),
  24854. // negative Z
  24855. new Vector4( 1, 1, 1, 1 ),
  24856. // positive Y
  24857. new Vector4( 3, 0, 1, 1 ),
  24858. // negative Y
  24859. new Vector4( 1, 0, 1, 1 )
  24860. ];
  24861. this._cubeDirections = [
  24862. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24863. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24864. ];
  24865. this._cubeUps = [
  24866. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24867. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24868. ];
  24869. }
  24870. updateMatrices( light, viewportIndex = 0 ) {
  24871. const camera = this.camera;
  24872. const shadowMatrix = this.matrix;
  24873. const far = light.distance || camera.far;
  24874. if ( far !== camera.far ) {
  24875. camera.far = far;
  24876. camera.updateProjectionMatrix();
  24877. }
  24878. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24879. camera.position.copy( _lightPositionWorld );
  24880. _lookTarget.copy( camera.position );
  24881. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24882. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24883. camera.lookAt( _lookTarget );
  24884. camera.updateMatrixWorld();
  24885. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24886. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24887. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24888. }
  24889. }
  24890. class PointLight extends Light {
  24891. constructor( color, intensity, distance = 0, decay = 2 ) {
  24892. super( color, intensity );
  24893. this.isPointLight = true;
  24894. this.type = 'PointLight';
  24895. this.distance = distance;
  24896. this.decay = decay;
  24897. this.shadow = new PointLightShadow();
  24898. }
  24899. get power() {
  24900. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24901. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24902. return this.intensity * 4 * Math.PI;
  24903. }
  24904. set power( power ) {
  24905. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24906. this.intensity = power / ( 4 * Math.PI );
  24907. }
  24908. dispose() {
  24909. this.shadow.dispose();
  24910. }
  24911. copy( source, recursive ) {
  24912. super.copy( source, recursive );
  24913. this.distance = source.distance;
  24914. this.decay = source.decay;
  24915. this.shadow = source.shadow.clone();
  24916. return this;
  24917. }
  24918. }
  24919. class DirectionalLightShadow extends LightShadow {
  24920. constructor() {
  24921. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24922. this.isDirectionalLightShadow = true;
  24923. }
  24924. }
  24925. class DirectionalLight extends Light {
  24926. constructor( color, intensity ) {
  24927. super( color, intensity );
  24928. this.isDirectionalLight = true;
  24929. this.type = 'DirectionalLight';
  24930. this.position.copy( Object3D.DEFAULT_UP );
  24931. this.updateMatrix();
  24932. this.target = new Object3D();
  24933. this.shadow = new DirectionalLightShadow();
  24934. }
  24935. dispose() {
  24936. this.shadow.dispose();
  24937. }
  24938. copy( source ) {
  24939. super.copy( source );
  24940. this.target = source.target.clone();
  24941. this.shadow = source.shadow.clone();
  24942. return this;
  24943. }
  24944. }
  24945. class AmbientLight extends Light {
  24946. constructor( color, intensity ) {
  24947. super( color, intensity );
  24948. this.isAmbientLight = true;
  24949. this.type = 'AmbientLight';
  24950. }
  24951. }
  24952. class RectAreaLight extends Light {
  24953. constructor( color, intensity, width = 10, height = 10 ) {
  24954. super( color, intensity );
  24955. this.isRectAreaLight = true;
  24956. this.type = 'RectAreaLight';
  24957. this.width = width;
  24958. this.height = height;
  24959. }
  24960. get power() {
  24961. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24962. return this.intensity * this.width * this.height * Math.PI;
  24963. }
  24964. set power( power ) {
  24965. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24966. this.intensity = power / ( this.width * this.height * Math.PI );
  24967. }
  24968. copy( source ) {
  24969. super.copy( source );
  24970. this.width = source.width;
  24971. this.height = source.height;
  24972. return this;
  24973. }
  24974. toJSON( meta ) {
  24975. const data = super.toJSON( meta );
  24976. data.object.width = this.width;
  24977. data.object.height = this.height;
  24978. return data;
  24979. }
  24980. }
  24981. /**
  24982. * Primary reference:
  24983. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24984. *
  24985. * Secondary reference:
  24986. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24987. */
  24988. // 3-band SH defined by 9 coefficients
  24989. class SphericalHarmonics3 {
  24990. constructor() {
  24991. this.isSphericalHarmonics3 = true;
  24992. this.coefficients = [];
  24993. for ( let i = 0; i < 9; i ++ ) {
  24994. this.coefficients.push( new Vector3() );
  24995. }
  24996. }
  24997. set( coefficients ) {
  24998. for ( let i = 0; i < 9; i ++ ) {
  24999. this.coefficients[ i ].copy( coefficients[ i ] );
  25000. }
  25001. return this;
  25002. }
  25003. zero() {
  25004. for ( let i = 0; i < 9; i ++ ) {
  25005. this.coefficients[ i ].set( 0, 0, 0 );
  25006. }
  25007. return this;
  25008. }
  25009. // get the radiance in the direction of the normal
  25010. // target is a Vector3
  25011. getAt( normal, target ) {
  25012. // normal is assumed to be unit length
  25013. const x = normal.x, y = normal.y, z = normal.z;
  25014. const coeff = this.coefficients;
  25015. // band 0
  25016. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  25017. // band 1
  25018. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  25019. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  25020. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  25021. // band 2
  25022. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  25023. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  25024. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  25025. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  25026. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  25027. return target;
  25028. }
  25029. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25030. // target is a Vector3
  25031. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25032. getIrradianceAt( normal, target ) {
  25033. // normal is assumed to be unit length
  25034. const x = normal.x, y = normal.y, z = normal.z;
  25035. const coeff = this.coefficients;
  25036. // band 0
  25037. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  25038. // band 1
  25039. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  25040. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  25041. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  25042. // band 2
  25043. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  25044. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  25045. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  25046. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  25047. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  25048. return target;
  25049. }
  25050. add( sh ) {
  25051. for ( let i = 0; i < 9; i ++ ) {
  25052. this.coefficients[ i ].add( sh.coefficients[ i ] );
  25053. }
  25054. return this;
  25055. }
  25056. addScaledSH( sh, s ) {
  25057. for ( let i = 0; i < 9; i ++ ) {
  25058. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  25059. }
  25060. return this;
  25061. }
  25062. scale( s ) {
  25063. for ( let i = 0; i < 9; i ++ ) {
  25064. this.coefficients[ i ].multiplyScalar( s );
  25065. }
  25066. return this;
  25067. }
  25068. lerp( sh, alpha ) {
  25069. for ( let i = 0; i < 9; i ++ ) {
  25070. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  25071. }
  25072. return this;
  25073. }
  25074. equals( sh ) {
  25075. for ( let i = 0; i < 9; i ++ ) {
  25076. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  25077. return false;
  25078. }
  25079. }
  25080. return true;
  25081. }
  25082. copy( sh ) {
  25083. return this.set( sh.coefficients );
  25084. }
  25085. clone() {
  25086. return new this.constructor().copy( this );
  25087. }
  25088. fromArray( array, offset = 0 ) {
  25089. const coefficients = this.coefficients;
  25090. for ( let i = 0; i < 9; i ++ ) {
  25091. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  25092. }
  25093. return this;
  25094. }
  25095. toArray( array = [], offset = 0 ) {
  25096. const coefficients = this.coefficients;
  25097. for ( let i = 0; i < 9; i ++ ) {
  25098. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  25099. }
  25100. return array;
  25101. }
  25102. // evaluate the basis functions
  25103. // shBasis is an Array[ 9 ]
  25104. static getBasisAt( normal, shBasis ) {
  25105. // normal is assumed to be unit length
  25106. const x = normal.x, y = normal.y, z = normal.z;
  25107. // band 0
  25108. shBasis[ 0 ] = 0.282095;
  25109. // band 1
  25110. shBasis[ 1 ] = 0.488603 * y;
  25111. shBasis[ 2 ] = 0.488603 * z;
  25112. shBasis[ 3 ] = 0.488603 * x;
  25113. // band 2
  25114. shBasis[ 4 ] = 1.092548 * x * y;
  25115. shBasis[ 5 ] = 1.092548 * y * z;
  25116. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  25117. shBasis[ 7 ] = 1.092548 * x * z;
  25118. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  25119. }
  25120. }
  25121. class LightProbe extends Light {
  25122. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  25123. super( undefined, intensity );
  25124. this.isLightProbe = true;
  25125. this.sh = sh;
  25126. }
  25127. copy( source ) {
  25128. super.copy( source );
  25129. this.sh.copy( source.sh );
  25130. return this;
  25131. }
  25132. fromJSON( json ) {
  25133. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  25134. this.sh.fromArray( json.sh );
  25135. return this;
  25136. }
  25137. toJSON( meta ) {
  25138. const data = super.toJSON( meta );
  25139. data.object.sh = this.sh.toArray();
  25140. return data;
  25141. }
  25142. }
  25143. class MaterialLoader extends Loader {
  25144. constructor( manager ) {
  25145. super( manager );
  25146. this.textures = {};
  25147. }
  25148. load( url, onLoad, onProgress, onError ) {
  25149. const scope = this;
  25150. const loader = new FileLoader( scope.manager );
  25151. loader.setPath( scope.path );
  25152. loader.setRequestHeader( scope.requestHeader );
  25153. loader.setWithCredentials( scope.withCredentials );
  25154. loader.load( url, function ( text ) {
  25155. try {
  25156. onLoad( scope.parse( JSON.parse( text ) ) );
  25157. } catch ( e ) {
  25158. if ( onError ) {
  25159. onError( e );
  25160. } else {
  25161. console.error( e );
  25162. }
  25163. scope.manager.itemError( url );
  25164. }
  25165. }, onProgress, onError );
  25166. }
  25167. parse( json ) {
  25168. const textures = this.textures;
  25169. function getTexture( name ) {
  25170. if ( textures[ name ] === undefined ) {
  25171. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25172. }
  25173. return textures[ name ];
  25174. }
  25175. const material = MaterialLoader.createMaterialFromType( json.type );
  25176. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25177. if ( json.name !== undefined ) material.name = json.name;
  25178. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  25179. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25180. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25181. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  25182. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  25183. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  25184. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25185. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  25186. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  25187. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  25188. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25189. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  25190. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  25191. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  25192. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  25193. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  25194. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  25195. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  25196. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  25197. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  25198. if ( json.fog !== undefined ) material.fog = json.fog;
  25199. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25200. if ( json.blending !== undefined ) material.blending = json.blending;
  25201. if ( json.combine !== undefined ) material.combine = json.combine;
  25202. if ( json.side !== undefined ) material.side = json.side;
  25203. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  25204. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25205. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25206. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25207. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25208. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25209. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25210. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  25211. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  25212. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  25213. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  25214. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  25215. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  25216. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  25217. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  25218. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25219. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25220. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25221. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25222. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25223. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25224. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25225. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25226. if ( json.scale !== undefined ) material.scale = json.scale;
  25227. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25228. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25229. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25230. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25231. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  25232. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  25233. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  25234. if ( json.visible !== undefined ) material.visible = json.visible;
  25235. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  25236. if ( json.userData !== undefined ) material.userData = json.userData;
  25237. if ( json.vertexColors !== undefined ) {
  25238. if ( typeof json.vertexColors === 'number' ) {
  25239. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  25240. } else {
  25241. material.vertexColors = json.vertexColors;
  25242. }
  25243. }
  25244. // Shader Material
  25245. if ( json.uniforms !== undefined ) {
  25246. for ( const name in json.uniforms ) {
  25247. const uniform = json.uniforms[ name ];
  25248. material.uniforms[ name ] = {};
  25249. switch ( uniform.type ) {
  25250. case 't':
  25251. material.uniforms[ name ].value = getTexture( uniform.value );
  25252. break;
  25253. case 'c':
  25254. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  25255. break;
  25256. case 'v2':
  25257. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  25258. break;
  25259. case 'v3':
  25260. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  25261. break;
  25262. case 'v4':
  25263. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  25264. break;
  25265. case 'm3':
  25266. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  25267. break;
  25268. case 'm4':
  25269. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  25270. break;
  25271. default:
  25272. material.uniforms[ name ].value = uniform.value;
  25273. }
  25274. }
  25275. }
  25276. if ( json.defines !== undefined ) material.defines = json.defines;
  25277. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25278. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25279. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  25280. if ( json.extensions !== undefined ) {
  25281. for ( const key in json.extensions ) {
  25282. material.extensions[ key ] = json.extensions[ key ];
  25283. }
  25284. }
  25285. // for PointsMaterial
  25286. if ( json.size !== undefined ) material.size = json.size;
  25287. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25288. // maps
  25289. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25290. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  25291. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  25292. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25293. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25294. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25295. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25296. if ( json.normalScale !== undefined ) {
  25297. let normalScale = json.normalScale;
  25298. if ( Array.isArray( normalScale ) === false ) {
  25299. // Blender exporter used to export a scalar. See #7459
  25300. normalScale = [ normalScale, normalScale ];
  25301. }
  25302. material.normalScale = new Vector2().fromArray( normalScale );
  25303. }
  25304. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25305. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25306. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25307. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25308. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25309. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25310. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25311. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25312. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  25313. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  25314. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25315. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  25316. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25317. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  25318. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25319. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25320. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25321. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25322. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25323. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  25324. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  25325. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  25326. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  25327. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  25328. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  25329. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  25330. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  25331. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  25332. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  25333. return material;
  25334. }
  25335. setTextures( value ) {
  25336. this.textures = value;
  25337. return this;
  25338. }
  25339. static createMaterialFromType( type ) {
  25340. const materialLib = {
  25341. ShadowMaterial,
  25342. SpriteMaterial,
  25343. RawShaderMaterial,
  25344. ShaderMaterial,
  25345. PointsMaterial,
  25346. MeshPhysicalMaterial,
  25347. MeshStandardMaterial,
  25348. MeshPhongMaterial,
  25349. MeshToonMaterial,
  25350. MeshNormalMaterial,
  25351. MeshLambertMaterial,
  25352. MeshDepthMaterial,
  25353. MeshDistanceMaterial,
  25354. MeshBasicMaterial,
  25355. MeshMatcapMaterial,
  25356. LineDashedMaterial,
  25357. LineBasicMaterial,
  25358. Material
  25359. };
  25360. return new materialLib[ type ]();
  25361. }
  25362. }
  25363. class LoaderUtils {
  25364. static decodeText( array ) {
  25365. if ( typeof TextDecoder !== 'undefined' ) {
  25366. return new TextDecoder().decode( array );
  25367. }
  25368. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25369. // throws a "maximum call stack size exceeded" error for large arrays.
  25370. let s = '';
  25371. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25372. // Implicitly assumes little-endian.
  25373. s += String.fromCharCode( array[ i ] );
  25374. }
  25375. try {
  25376. // merges multi-byte utf-8 characters.
  25377. return decodeURIComponent( escape( s ) );
  25378. } catch ( e ) { // see #16358
  25379. return s;
  25380. }
  25381. }
  25382. static extractUrlBase( url ) {
  25383. const index = url.lastIndexOf( '/' );
  25384. if ( index === - 1 ) return './';
  25385. return url.slice( 0, index + 1 );
  25386. }
  25387. static resolveURL( url, path ) {
  25388. // Invalid URL
  25389. if ( typeof url !== 'string' || url === '' ) return '';
  25390. // Host Relative URL
  25391. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25392. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25393. }
  25394. // Absolute URL http://,https://,//
  25395. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25396. // Data URI
  25397. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25398. // Blob URL
  25399. if ( /^blob:.*$/i.test( url ) ) return url;
  25400. // Relative URL
  25401. return path + url;
  25402. }
  25403. }
  25404. class InstancedBufferGeometry extends BufferGeometry {
  25405. constructor() {
  25406. super();
  25407. this.isInstancedBufferGeometry = true;
  25408. this.type = 'InstancedBufferGeometry';
  25409. this.instanceCount = Infinity;
  25410. }
  25411. copy( source ) {
  25412. super.copy( source );
  25413. this.instanceCount = source.instanceCount;
  25414. return this;
  25415. }
  25416. toJSON() {
  25417. const data = super.toJSON();
  25418. data.instanceCount = this.instanceCount;
  25419. data.isInstancedBufferGeometry = true;
  25420. return data;
  25421. }
  25422. }
  25423. class BufferGeometryLoader extends Loader {
  25424. constructor( manager ) {
  25425. super( manager );
  25426. }
  25427. load( url, onLoad, onProgress, onError ) {
  25428. const scope = this;
  25429. const loader = new FileLoader( scope.manager );
  25430. loader.setPath( scope.path );
  25431. loader.setRequestHeader( scope.requestHeader );
  25432. loader.setWithCredentials( scope.withCredentials );
  25433. loader.load( url, function ( text ) {
  25434. try {
  25435. onLoad( scope.parse( JSON.parse( text ) ) );
  25436. } catch ( e ) {
  25437. if ( onError ) {
  25438. onError( e );
  25439. } else {
  25440. console.error( e );
  25441. }
  25442. scope.manager.itemError( url );
  25443. }
  25444. }, onProgress, onError );
  25445. }
  25446. parse( json ) {
  25447. const interleavedBufferMap = {};
  25448. const arrayBufferMap = {};
  25449. function getInterleavedBuffer( json, uuid ) {
  25450. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25451. const interleavedBuffers = json.interleavedBuffers;
  25452. const interleavedBuffer = interleavedBuffers[ uuid ];
  25453. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25454. const array = getTypedArray( interleavedBuffer.type, buffer );
  25455. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25456. ib.uuid = interleavedBuffer.uuid;
  25457. interleavedBufferMap[ uuid ] = ib;
  25458. return ib;
  25459. }
  25460. function getArrayBuffer( json, uuid ) {
  25461. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25462. const arrayBuffers = json.arrayBuffers;
  25463. const arrayBuffer = arrayBuffers[ uuid ];
  25464. const ab = new Uint32Array( arrayBuffer ).buffer;
  25465. arrayBufferMap[ uuid ] = ab;
  25466. return ab;
  25467. }
  25468. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25469. const index = json.data.index;
  25470. if ( index !== undefined ) {
  25471. const typedArray = getTypedArray( index.type, index.array );
  25472. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25473. }
  25474. const attributes = json.data.attributes;
  25475. for ( const key in attributes ) {
  25476. const attribute = attributes[ key ];
  25477. let bufferAttribute;
  25478. if ( attribute.isInterleavedBufferAttribute ) {
  25479. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25480. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25481. } else {
  25482. const typedArray = getTypedArray( attribute.type, attribute.array );
  25483. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25484. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25485. }
  25486. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25487. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25488. if ( attribute.updateRange !== undefined ) {
  25489. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25490. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25491. }
  25492. geometry.setAttribute( key, bufferAttribute );
  25493. }
  25494. const morphAttributes = json.data.morphAttributes;
  25495. if ( morphAttributes ) {
  25496. for ( const key in morphAttributes ) {
  25497. const attributeArray = morphAttributes[ key ];
  25498. const array = [];
  25499. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25500. const attribute = attributeArray[ i ];
  25501. let bufferAttribute;
  25502. if ( attribute.isInterleavedBufferAttribute ) {
  25503. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25504. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25505. } else {
  25506. const typedArray = getTypedArray( attribute.type, attribute.array );
  25507. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25508. }
  25509. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25510. array.push( bufferAttribute );
  25511. }
  25512. geometry.morphAttributes[ key ] = array;
  25513. }
  25514. }
  25515. const morphTargetsRelative = json.data.morphTargetsRelative;
  25516. if ( morphTargetsRelative ) {
  25517. geometry.morphTargetsRelative = true;
  25518. }
  25519. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25520. if ( groups !== undefined ) {
  25521. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25522. const group = groups[ i ];
  25523. geometry.addGroup( group.start, group.count, group.materialIndex );
  25524. }
  25525. }
  25526. const boundingSphere = json.data.boundingSphere;
  25527. if ( boundingSphere !== undefined ) {
  25528. const center = new Vector3();
  25529. if ( boundingSphere.center !== undefined ) {
  25530. center.fromArray( boundingSphere.center );
  25531. }
  25532. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25533. }
  25534. if ( json.name ) geometry.name = json.name;
  25535. if ( json.userData ) geometry.userData = json.userData;
  25536. return geometry;
  25537. }
  25538. }
  25539. class ObjectLoader extends Loader {
  25540. constructor( manager ) {
  25541. super( manager );
  25542. }
  25543. load( url, onLoad, onProgress, onError ) {
  25544. const scope = this;
  25545. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25546. this.resourcePath = this.resourcePath || path;
  25547. const loader = new FileLoader( this.manager );
  25548. loader.setPath( this.path );
  25549. loader.setRequestHeader( this.requestHeader );
  25550. loader.setWithCredentials( this.withCredentials );
  25551. loader.load( url, function ( text ) {
  25552. let json = null;
  25553. try {
  25554. json = JSON.parse( text );
  25555. } catch ( error ) {
  25556. if ( onError !== undefined ) onError( error );
  25557. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25558. return;
  25559. }
  25560. const metadata = json.metadata;
  25561. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25562. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  25563. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25564. return;
  25565. }
  25566. scope.parse( json, onLoad );
  25567. }, onProgress, onError );
  25568. }
  25569. async loadAsync( url, onProgress ) {
  25570. const scope = this;
  25571. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25572. this.resourcePath = this.resourcePath || path;
  25573. const loader = new FileLoader( this.manager );
  25574. loader.setPath( this.path );
  25575. loader.setRequestHeader( this.requestHeader );
  25576. loader.setWithCredentials( this.withCredentials );
  25577. const text = await loader.loadAsync( url, onProgress );
  25578. const json = JSON.parse( text );
  25579. const metadata = json.metadata;
  25580. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25581. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25582. }
  25583. return await scope.parseAsync( json );
  25584. }
  25585. parse( json, onLoad ) {
  25586. const animations = this.parseAnimations( json.animations );
  25587. const shapes = this.parseShapes( json.shapes );
  25588. const geometries = this.parseGeometries( json.geometries, shapes );
  25589. const images = this.parseImages( json.images, function () {
  25590. if ( onLoad !== undefined ) onLoad( object );
  25591. } );
  25592. const textures = this.parseTextures( json.textures, images );
  25593. const materials = this.parseMaterials( json.materials, textures );
  25594. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25595. const skeletons = this.parseSkeletons( json.skeletons, object );
  25596. this.bindSkeletons( object, skeletons );
  25597. //
  25598. if ( onLoad !== undefined ) {
  25599. let hasImages = false;
  25600. for ( const uuid in images ) {
  25601. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  25602. hasImages = true;
  25603. break;
  25604. }
  25605. }
  25606. if ( hasImages === false ) onLoad( object );
  25607. }
  25608. return object;
  25609. }
  25610. async parseAsync( json ) {
  25611. const animations = this.parseAnimations( json.animations );
  25612. const shapes = this.parseShapes( json.shapes );
  25613. const geometries = this.parseGeometries( json.geometries, shapes );
  25614. const images = await this.parseImagesAsync( json.images );
  25615. const textures = this.parseTextures( json.textures, images );
  25616. const materials = this.parseMaterials( json.materials, textures );
  25617. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25618. const skeletons = this.parseSkeletons( json.skeletons, object );
  25619. this.bindSkeletons( object, skeletons );
  25620. return object;
  25621. }
  25622. parseShapes( json ) {
  25623. const shapes = {};
  25624. if ( json !== undefined ) {
  25625. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25626. const shape = new Shape().fromJSON( json[ i ] );
  25627. shapes[ shape.uuid ] = shape;
  25628. }
  25629. }
  25630. return shapes;
  25631. }
  25632. parseSkeletons( json, object ) {
  25633. const skeletons = {};
  25634. const bones = {};
  25635. // generate bone lookup table
  25636. object.traverse( function ( child ) {
  25637. if ( child.isBone ) bones[ child.uuid ] = child;
  25638. } );
  25639. // create skeletons
  25640. if ( json !== undefined ) {
  25641. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25642. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25643. skeletons[ skeleton.uuid ] = skeleton;
  25644. }
  25645. }
  25646. return skeletons;
  25647. }
  25648. parseGeometries( json, shapes ) {
  25649. const geometries = {};
  25650. if ( json !== undefined ) {
  25651. const bufferGeometryLoader = new BufferGeometryLoader();
  25652. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25653. let geometry;
  25654. const data = json[ i ];
  25655. switch ( data.type ) {
  25656. case 'BufferGeometry':
  25657. case 'InstancedBufferGeometry':
  25658. geometry = bufferGeometryLoader.parse( data );
  25659. break;
  25660. default:
  25661. if ( data.type in Geometries ) {
  25662. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25663. } else {
  25664. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25665. }
  25666. }
  25667. geometry.uuid = data.uuid;
  25668. if ( data.name !== undefined ) geometry.name = data.name;
  25669. if ( data.userData !== undefined ) geometry.userData = data.userData;
  25670. geometries[ data.uuid ] = geometry;
  25671. }
  25672. }
  25673. return geometries;
  25674. }
  25675. parseMaterials( json, textures ) {
  25676. const cache = {}; // MultiMaterial
  25677. const materials = {};
  25678. if ( json !== undefined ) {
  25679. const loader = new MaterialLoader();
  25680. loader.setTextures( textures );
  25681. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25682. const data = json[ i ];
  25683. if ( cache[ data.uuid ] === undefined ) {
  25684. cache[ data.uuid ] = loader.parse( data );
  25685. }
  25686. materials[ data.uuid ] = cache[ data.uuid ];
  25687. }
  25688. }
  25689. return materials;
  25690. }
  25691. parseAnimations( json ) {
  25692. const animations = {};
  25693. if ( json !== undefined ) {
  25694. for ( let i = 0; i < json.length; i ++ ) {
  25695. const data = json[ i ];
  25696. const clip = AnimationClip.parse( data );
  25697. animations[ clip.uuid ] = clip;
  25698. }
  25699. }
  25700. return animations;
  25701. }
  25702. parseImages( json, onLoad ) {
  25703. const scope = this;
  25704. const images = {};
  25705. let loader;
  25706. function loadImage( url ) {
  25707. scope.manager.itemStart( url );
  25708. return loader.load( url, function () {
  25709. scope.manager.itemEnd( url );
  25710. }, undefined, function () {
  25711. scope.manager.itemError( url );
  25712. scope.manager.itemEnd( url );
  25713. } );
  25714. }
  25715. function deserializeImage( image ) {
  25716. if ( typeof image === 'string' ) {
  25717. const url = image;
  25718. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25719. return loadImage( path );
  25720. } else {
  25721. if ( image.data ) {
  25722. return {
  25723. data: getTypedArray( image.type, image.data ),
  25724. width: image.width,
  25725. height: image.height
  25726. };
  25727. } else {
  25728. return null;
  25729. }
  25730. }
  25731. }
  25732. if ( json !== undefined && json.length > 0 ) {
  25733. const manager = new LoadingManager( onLoad );
  25734. loader = new ImageLoader( manager );
  25735. loader.setCrossOrigin( this.crossOrigin );
  25736. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25737. const image = json[ i ];
  25738. const url = image.url;
  25739. if ( Array.isArray( url ) ) {
  25740. // load array of images e.g CubeTexture
  25741. const imageArray = [];
  25742. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25743. const currentUrl = url[ j ];
  25744. const deserializedImage = deserializeImage( currentUrl );
  25745. if ( deserializedImage !== null ) {
  25746. if ( deserializedImage instanceof HTMLImageElement ) {
  25747. imageArray.push( deserializedImage );
  25748. } else {
  25749. // special case: handle array of data textures for cube textures
  25750. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25751. }
  25752. }
  25753. }
  25754. images[ image.uuid ] = new Source( imageArray );
  25755. } else {
  25756. // load single image
  25757. const deserializedImage = deserializeImage( image.url );
  25758. images[ image.uuid ] = new Source( deserializedImage );
  25759. }
  25760. }
  25761. }
  25762. return images;
  25763. }
  25764. async parseImagesAsync( json ) {
  25765. const scope = this;
  25766. const images = {};
  25767. let loader;
  25768. async function deserializeImage( image ) {
  25769. if ( typeof image === 'string' ) {
  25770. const url = image;
  25771. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25772. return await loader.loadAsync( path );
  25773. } else {
  25774. if ( image.data ) {
  25775. return {
  25776. data: getTypedArray( image.type, image.data ),
  25777. width: image.width,
  25778. height: image.height
  25779. };
  25780. } else {
  25781. return null;
  25782. }
  25783. }
  25784. }
  25785. if ( json !== undefined && json.length > 0 ) {
  25786. loader = new ImageLoader( this.manager );
  25787. loader.setCrossOrigin( this.crossOrigin );
  25788. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25789. const image = json[ i ];
  25790. const url = image.url;
  25791. if ( Array.isArray( url ) ) {
  25792. // load array of images e.g CubeTexture
  25793. const imageArray = [];
  25794. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25795. const currentUrl = url[ j ];
  25796. const deserializedImage = await deserializeImage( currentUrl );
  25797. if ( deserializedImage !== null ) {
  25798. if ( deserializedImage instanceof HTMLImageElement ) {
  25799. imageArray.push( deserializedImage );
  25800. } else {
  25801. // special case: handle array of data textures for cube textures
  25802. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25803. }
  25804. }
  25805. }
  25806. images[ image.uuid ] = new Source( imageArray );
  25807. } else {
  25808. // load single image
  25809. const deserializedImage = await deserializeImage( image.url );
  25810. images[ image.uuid ] = new Source( deserializedImage );
  25811. }
  25812. }
  25813. }
  25814. return images;
  25815. }
  25816. parseTextures( json, images ) {
  25817. function parseConstant( value, type ) {
  25818. if ( typeof value === 'number' ) return value;
  25819. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25820. return type[ value ];
  25821. }
  25822. const textures = {};
  25823. if ( json !== undefined ) {
  25824. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25825. const data = json[ i ];
  25826. if ( data.image === undefined ) {
  25827. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25828. }
  25829. if ( images[ data.image ] === undefined ) {
  25830. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25831. }
  25832. const source = images[ data.image ];
  25833. const image = source.data;
  25834. let texture;
  25835. if ( Array.isArray( image ) ) {
  25836. texture = new CubeTexture();
  25837. if ( image.length === 6 ) texture.needsUpdate = true;
  25838. } else {
  25839. if ( image && image.data ) {
  25840. texture = new DataTexture();
  25841. } else {
  25842. texture = new Texture();
  25843. }
  25844. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25845. }
  25846. texture.source = source;
  25847. texture.uuid = data.uuid;
  25848. if ( data.name !== undefined ) texture.name = data.name;
  25849. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25850. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25851. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25852. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25853. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25854. if ( data.wrap !== undefined ) {
  25855. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25856. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25857. }
  25858. if ( data.format !== undefined ) texture.format = data.format;
  25859. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  25860. if ( data.type !== undefined ) texture.type = data.type;
  25861. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25862. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25863. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25864. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25865. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25866. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  25867. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25868. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25869. if ( data.userData !== undefined ) texture.userData = data.userData;
  25870. textures[ data.uuid ] = texture;
  25871. }
  25872. }
  25873. return textures;
  25874. }
  25875. parseObject( data, geometries, materials, textures, animations ) {
  25876. let object;
  25877. function getGeometry( name ) {
  25878. if ( geometries[ name ] === undefined ) {
  25879. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25880. }
  25881. return geometries[ name ];
  25882. }
  25883. function getMaterial( name ) {
  25884. if ( name === undefined ) return undefined;
  25885. if ( Array.isArray( name ) ) {
  25886. const array = [];
  25887. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25888. const uuid = name[ i ];
  25889. if ( materials[ uuid ] === undefined ) {
  25890. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25891. }
  25892. array.push( materials[ uuid ] );
  25893. }
  25894. return array;
  25895. }
  25896. if ( materials[ name ] === undefined ) {
  25897. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25898. }
  25899. return materials[ name ];
  25900. }
  25901. function getTexture( uuid ) {
  25902. if ( textures[ uuid ] === undefined ) {
  25903. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  25904. }
  25905. return textures[ uuid ];
  25906. }
  25907. let geometry, material;
  25908. switch ( data.type ) {
  25909. case 'Scene':
  25910. object = new Scene();
  25911. if ( data.background !== undefined ) {
  25912. if ( Number.isInteger( data.background ) ) {
  25913. object.background = new Color( data.background );
  25914. } else {
  25915. object.background = getTexture( data.background );
  25916. }
  25917. }
  25918. if ( data.environment !== undefined ) {
  25919. object.environment = getTexture( data.environment );
  25920. }
  25921. if ( data.fog !== undefined ) {
  25922. if ( data.fog.type === 'Fog' ) {
  25923. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25924. } else if ( data.fog.type === 'FogExp2' ) {
  25925. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25926. }
  25927. }
  25928. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  25929. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  25930. break;
  25931. case 'PerspectiveCamera':
  25932. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25933. if ( data.focus !== undefined ) object.focus = data.focus;
  25934. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25935. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25936. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25937. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25938. break;
  25939. case 'OrthographicCamera':
  25940. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25941. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25942. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25943. break;
  25944. case 'AmbientLight':
  25945. object = new AmbientLight( data.color, data.intensity );
  25946. break;
  25947. case 'DirectionalLight':
  25948. object = new DirectionalLight( data.color, data.intensity );
  25949. break;
  25950. case 'PointLight':
  25951. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25952. break;
  25953. case 'RectAreaLight':
  25954. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25955. break;
  25956. case 'SpotLight':
  25957. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25958. break;
  25959. case 'HemisphereLight':
  25960. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25961. break;
  25962. case 'LightProbe':
  25963. object = new LightProbe().fromJSON( data );
  25964. break;
  25965. case 'SkinnedMesh':
  25966. geometry = getGeometry( data.geometry );
  25967. material = getMaterial( data.material );
  25968. object = new SkinnedMesh( geometry, material );
  25969. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25970. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25971. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25972. break;
  25973. case 'Mesh':
  25974. geometry = getGeometry( data.geometry );
  25975. material = getMaterial( data.material );
  25976. object = new Mesh( geometry, material );
  25977. break;
  25978. case 'InstancedMesh':
  25979. geometry = getGeometry( data.geometry );
  25980. material = getMaterial( data.material );
  25981. const count = data.count;
  25982. const instanceMatrix = data.instanceMatrix;
  25983. const instanceColor = data.instanceColor;
  25984. object = new InstancedMesh( geometry, material, count );
  25985. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25986. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25987. break;
  25988. case 'LOD':
  25989. object = new LOD();
  25990. break;
  25991. case 'Line':
  25992. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25993. break;
  25994. case 'LineLoop':
  25995. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25996. break;
  25997. case 'LineSegments':
  25998. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25999. break;
  26000. case 'PointCloud':
  26001. case 'Points':
  26002. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  26003. break;
  26004. case 'Sprite':
  26005. object = new Sprite( getMaterial( data.material ) );
  26006. break;
  26007. case 'Group':
  26008. object = new Group();
  26009. break;
  26010. case 'Bone':
  26011. object = new Bone();
  26012. break;
  26013. default:
  26014. object = new Object3D();
  26015. }
  26016. object.uuid = data.uuid;
  26017. if ( data.name !== undefined ) object.name = data.name;
  26018. if ( data.matrix !== undefined ) {
  26019. object.matrix.fromArray( data.matrix );
  26020. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  26021. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  26022. } else {
  26023. if ( data.position !== undefined ) object.position.fromArray( data.position );
  26024. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  26025. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  26026. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  26027. }
  26028. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  26029. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  26030. if ( data.shadow ) {
  26031. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  26032. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  26033. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  26034. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  26035. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  26036. }
  26037. if ( data.visible !== undefined ) object.visible = data.visible;
  26038. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  26039. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  26040. if ( data.userData !== undefined ) object.userData = data.userData;
  26041. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  26042. if ( data.children !== undefined ) {
  26043. const children = data.children;
  26044. for ( let i = 0; i < children.length; i ++ ) {
  26045. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  26046. }
  26047. }
  26048. if ( data.animations !== undefined ) {
  26049. const objectAnimations = data.animations;
  26050. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  26051. const uuid = objectAnimations[ i ];
  26052. object.animations.push( animations[ uuid ] );
  26053. }
  26054. }
  26055. if ( data.type === 'LOD' ) {
  26056. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  26057. const levels = data.levels;
  26058. for ( let l = 0; l < levels.length; l ++ ) {
  26059. const level = levels[ l ];
  26060. const child = object.getObjectByProperty( 'uuid', level.object );
  26061. if ( child !== undefined ) {
  26062. object.addLevel( child, level.distance, level.hysteresis );
  26063. }
  26064. }
  26065. }
  26066. return object;
  26067. }
  26068. bindSkeletons( object, skeletons ) {
  26069. if ( Object.keys( skeletons ).length === 0 ) return;
  26070. object.traverse( function ( child ) {
  26071. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  26072. const skeleton = skeletons[ child.skeleton ];
  26073. if ( skeleton === undefined ) {
  26074. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  26075. } else {
  26076. child.bind( skeleton, child.bindMatrix );
  26077. }
  26078. }
  26079. } );
  26080. }
  26081. }
  26082. const TEXTURE_MAPPING = {
  26083. UVMapping: UVMapping,
  26084. CubeReflectionMapping: CubeReflectionMapping,
  26085. CubeRefractionMapping: CubeRefractionMapping,
  26086. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  26087. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  26088. CubeUVReflectionMapping: CubeUVReflectionMapping
  26089. };
  26090. const TEXTURE_WRAPPING = {
  26091. RepeatWrapping: RepeatWrapping,
  26092. ClampToEdgeWrapping: ClampToEdgeWrapping,
  26093. MirroredRepeatWrapping: MirroredRepeatWrapping
  26094. };
  26095. const TEXTURE_FILTER = {
  26096. NearestFilter: NearestFilter,
  26097. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  26098. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  26099. LinearFilter: LinearFilter,
  26100. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  26101. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  26102. };
  26103. class ImageBitmapLoader extends Loader {
  26104. constructor( manager ) {
  26105. super( manager );
  26106. this.isImageBitmapLoader = true;
  26107. if ( typeof createImageBitmap === 'undefined' ) {
  26108. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26109. }
  26110. if ( typeof fetch === 'undefined' ) {
  26111. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26112. }
  26113. this.options = { premultiplyAlpha: 'none' };
  26114. }
  26115. setOptions( options ) {
  26116. this.options = options;
  26117. return this;
  26118. }
  26119. load( url, onLoad, onProgress, onError ) {
  26120. if ( url === undefined ) url = '';
  26121. if ( this.path !== undefined ) url = this.path + url;
  26122. url = this.manager.resolveURL( url );
  26123. const scope = this;
  26124. const cached = Cache.get( url );
  26125. if ( cached !== undefined ) {
  26126. scope.manager.itemStart( url );
  26127. setTimeout( function () {
  26128. if ( onLoad ) onLoad( cached );
  26129. scope.manager.itemEnd( url );
  26130. }, 0 );
  26131. return cached;
  26132. }
  26133. const fetchOptions = {};
  26134. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  26135. fetchOptions.headers = this.requestHeader;
  26136. fetch( url, fetchOptions ).then( function ( res ) {
  26137. return res.blob();
  26138. } ).then( function ( blob ) {
  26139. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  26140. } ).then( function ( imageBitmap ) {
  26141. Cache.add( url, imageBitmap );
  26142. if ( onLoad ) onLoad( imageBitmap );
  26143. scope.manager.itemEnd( url );
  26144. } ).catch( function ( e ) {
  26145. if ( onError ) onError( e );
  26146. scope.manager.itemError( url );
  26147. scope.manager.itemEnd( url );
  26148. } );
  26149. scope.manager.itemStart( url );
  26150. }
  26151. }
  26152. let _context;
  26153. class AudioContext {
  26154. static getContext() {
  26155. if ( _context === undefined ) {
  26156. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26157. }
  26158. return _context;
  26159. }
  26160. static setContext( value ) {
  26161. _context = value;
  26162. }
  26163. }
  26164. class AudioLoader extends Loader {
  26165. constructor( manager ) {
  26166. super( manager );
  26167. }
  26168. load( url, onLoad, onProgress, onError ) {
  26169. const scope = this;
  26170. const loader = new FileLoader( this.manager );
  26171. loader.setResponseType( 'arraybuffer' );
  26172. loader.setPath( this.path );
  26173. loader.setRequestHeader( this.requestHeader );
  26174. loader.setWithCredentials( this.withCredentials );
  26175. loader.load( url, function ( buffer ) {
  26176. try {
  26177. // Create a copy of the buffer. The `decodeAudioData` method
  26178. // detaches the buffer when complete, preventing reuse.
  26179. const bufferCopy = buffer.slice( 0 );
  26180. const context = AudioContext.getContext();
  26181. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26182. onLoad( audioBuffer );
  26183. } );
  26184. } catch ( e ) {
  26185. if ( onError ) {
  26186. onError( e );
  26187. } else {
  26188. console.error( e );
  26189. }
  26190. scope.manager.itemError( url );
  26191. }
  26192. }, onProgress, onError );
  26193. }
  26194. }
  26195. class HemisphereLightProbe extends LightProbe {
  26196. constructor( skyColor, groundColor, intensity = 1 ) {
  26197. super( undefined, intensity );
  26198. this.isHemisphereLightProbe = true;
  26199. const color1 = new Color().set( skyColor );
  26200. const color2 = new Color().set( groundColor );
  26201. const sky = new Vector3( color1.r, color1.g, color1.b );
  26202. const ground = new Vector3( color2.r, color2.g, color2.b );
  26203. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26204. const c0 = Math.sqrt( Math.PI );
  26205. const c1 = c0 * Math.sqrt( 0.75 );
  26206. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26207. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26208. }
  26209. }
  26210. class AmbientLightProbe extends LightProbe {
  26211. constructor( color, intensity = 1 ) {
  26212. super( undefined, intensity );
  26213. this.isAmbientLightProbe = true;
  26214. const color1 = new Color().set( color );
  26215. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26216. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26217. }
  26218. }
  26219. const _eyeRight = /*@__PURE__*/ new Matrix4();
  26220. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  26221. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  26222. class StereoCamera {
  26223. constructor() {
  26224. this.type = 'StereoCamera';
  26225. this.aspect = 1;
  26226. this.eyeSep = 0.064;
  26227. this.cameraL = new PerspectiveCamera();
  26228. this.cameraL.layers.enable( 1 );
  26229. this.cameraL.matrixAutoUpdate = false;
  26230. this.cameraR = new PerspectiveCamera();
  26231. this.cameraR.layers.enable( 2 );
  26232. this.cameraR.matrixAutoUpdate = false;
  26233. this._cache = {
  26234. focus: null,
  26235. fov: null,
  26236. aspect: null,
  26237. near: null,
  26238. far: null,
  26239. zoom: null,
  26240. eyeSep: null
  26241. };
  26242. }
  26243. update( camera ) {
  26244. const cache = this._cache;
  26245. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26246. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26247. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26248. if ( needsUpdate ) {
  26249. cache.focus = camera.focus;
  26250. cache.fov = camera.fov;
  26251. cache.aspect = camera.aspect * this.aspect;
  26252. cache.near = camera.near;
  26253. cache.far = camera.far;
  26254. cache.zoom = camera.zoom;
  26255. cache.eyeSep = this.eyeSep;
  26256. // Off-axis stereoscopic effect based on
  26257. // http://paulbourke.net/stereographics/stereorender/
  26258. _projectionMatrix.copy( camera.projectionMatrix );
  26259. const eyeSepHalf = cache.eyeSep / 2;
  26260. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26261. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26262. let xmin, xmax;
  26263. // translate xOffset
  26264. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26265. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26266. // for left eye
  26267. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26268. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26269. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26270. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26271. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  26272. // for right eye
  26273. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26274. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26275. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26276. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26277. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  26278. }
  26279. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26280. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26281. }
  26282. }
  26283. class Clock {
  26284. constructor( autoStart = true ) {
  26285. this.autoStart = autoStart;
  26286. this.startTime = 0;
  26287. this.oldTime = 0;
  26288. this.elapsedTime = 0;
  26289. this.running = false;
  26290. }
  26291. start() {
  26292. this.startTime = now();
  26293. this.oldTime = this.startTime;
  26294. this.elapsedTime = 0;
  26295. this.running = true;
  26296. }
  26297. stop() {
  26298. this.getElapsedTime();
  26299. this.running = false;
  26300. this.autoStart = false;
  26301. }
  26302. getElapsedTime() {
  26303. this.getDelta();
  26304. return this.elapsedTime;
  26305. }
  26306. getDelta() {
  26307. let diff = 0;
  26308. if ( this.autoStart && ! this.running ) {
  26309. this.start();
  26310. return 0;
  26311. }
  26312. if ( this.running ) {
  26313. const newTime = now();
  26314. diff = ( newTime - this.oldTime ) / 1000;
  26315. this.oldTime = newTime;
  26316. this.elapsedTime += diff;
  26317. }
  26318. return diff;
  26319. }
  26320. }
  26321. function now() {
  26322. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26323. }
  26324. const _position$1 = /*@__PURE__*/ new Vector3();
  26325. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  26326. const _scale$1 = /*@__PURE__*/ new Vector3();
  26327. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26328. class AudioListener extends Object3D {
  26329. constructor() {
  26330. super();
  26331. this.type = 'AudioListener';
  26332. this.context = AudioContext.getContext();
  26333. this.gain = this.context.createGain();
  26334. this.gain.connect( this.context.destination );
  26335. this.filter = null;
  26336. this.timeDelta = 0;
  26337. // private
  26338. this._clock = new Clock();
  26339. }
  26340. getInput() {
  26341. return this.gain;
  26342. }
  26343. removeFilter() {
  26344. if ( this.filter !== null ) {
  26345. this.gain.disconnect( this.filter );
  26346. this.filter.disconnect( this.context.destination );
  26347. this.gain.connect( this.context.destination );
  26348. this.filter = null;
  26349. }
  26350. return this;
  26351. }
  26352. getFilter() {
  26353. return this.filter;
  26354. }
  26355. setFilter( value ) {
  26356. if ( this.filter !== null ) {
  26357. this.gain.disconnect( this.filter );
  26358. this.filter.disconnect( this.context.destination );
  26359. } else {
  26360. this.gain.disconnect( this.context.destination );
  26361. }
  26362. this.filter = value;
  26363. this.gain.connect( this.filter );
  26364. this.filter.connect( this.context.destination );
  26365. return this;
  26366. }
  26367. getMasterVolume() {
  26368. return this.gain.gain.value;
  26369. }
  26370. setMasterVolume( value ) {
  26371. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26372. return this;
  26373. }
  26374. updateMatrixWorld( force ) {
  26375. super.updateMatrixWorld( force );
  26376. const listener = this.context.listener;
  26377. const up = this.up;
  26378. this.timeDelta = this._clock.getDelta();
  26379. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26380. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26381. if ( listener.positionX ) {
  26382. // code path for Chrome (see #14393)
  26383. const endTime = this.context.currentTime + this.timeDelta;
  26384. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26385. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26386. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26387. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26388. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26389. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26390. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26391. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26392. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26393. } else {
  26394. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26395. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26396. }
  26397. }
  26398. }
  26399. class Audio extends Object3D {
  26400. constructor( listener ) {
  26401. super();
  26402. this.type = 'Audio';
  26403. this.listener = listener;
  26404. this.context = listener.context;
  26405. this.gain = this.context.createGain();
  26406. this.gain.connect( listener.getInput() );
  26407. this.autoplay = false;
  26408. this.buffer = null;
  26409. this.detune = 0;
  26410. this.loop = false;
  26411. this.loopStart = 0;
  26412. this.loopEnd = 0;
  26413. this.offset = 0;
  26414. this.duration = undefined;
  26415. this.playbackRate = 1;
  26416. this.isPlaying = false;
  26417. this.hasPlaybackControl = true;
  26418. this.source = null;
  26419. this.sourceType = 'empty';
  26420. this._startedAt = 0;
  26421. this._progress = 0;
  26422. this._connected = false;
  26423. this.filters = [];
  26424. }
  26425. getOutput() {
  26426. return this.gain;
  26427. }
  26428. setNodeSource( audioNode ) {
  26429. this.hasPlaybackControl = false;
  26430. this.sourceType = 'audioNode';
  26431. this.source = audioNode;
  26432. this.connect();
  26433. return this;
  26434. }
  26435. setMediaElementSource( mediaElement ) {
  26436. this.hasPlaybackControl = false;
  26437. this.sourceType = 'mediaNode';
  26438. this.source = this.context.createMediaElementSource( mediaElement );
  26439. this.connect();
  26440. return this;
  26441. }
  26442. setMediaStreamSource( mediaStream ) {
  26443. this.hasPlaybackControl = false;
  26444. this.sourceType = 'mediaStreamNode';
  26445. this.source = this.context.createMediaStreamSource( mediaStream );
  26446. this.connect();
  26447. return this;
  26448. }
  26449. setBuffer( audioBuffer ) {
  26450. this.buffer = audioBuffer;
  26451. this.sourceType = 'buffer';
  26452. if ( this.autoplay ) this.play();
  26453. return this;
  26454. }
  26455. play( delay = 0 ) {
  26456. if ( this.isPlaying === true ) {
  26457. console.warn( 'THREE.Audio: Audio is already playing.' );
  26458. return;
  26459. }
  26460. if ( this.hasPlaybackControl === false ) {
  26461. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26462. return;
  26463. }
  26464. this._startedAt = this.context.currentTime + delay;
  26465. const source = this.context.createBufferSource();
  26466. source.buffer = this.buffer;
  26467. source.loop = this.loop;
  26468. source.loopStart = this.loopStart;
  26469. source.loopEnd = this.loopEnd;
  26470. source.onended = this.onEnded.bind( this );
  26471. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26472. this.isPlaying = true;
  26473. this.source = source;
  26474. this.setDetune( this.detune );
  26475. this.setPlaybackRate( this.playbackRate );
  26476. return this.connect();
  26477. }
  26478. pause() {
  26479. if ( this.hasPlaybackControl === false ) {
  26480. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26481. return;
  26482. }
  26483. if ( this.isPlaying === true ) {
  26484. // update current progress
  26485. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26486. if ( this.loop === true ) {
  26487. // ensure _progress does not exceed duration with looped audios
  26488. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26489. }
  26490. this.source.stop();
  26491. this.source.onended = null;
  26492. this.isPlaying = false;
  26493. }
  26494. return this;
  26495. }
  26496. stop() {
  26497. if ( this.hasPlaybackControl === false ) {
  26498. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26499. return;
  26500. }
  26501. this._progress = 0;
  26502. if ( this.source !== null ) {
  26503. this.source.stop();
  26504. this.source.onended = null;
  26505. }
  26506. this.isPlaying = false;
  26507. return this;
  26508. }
  26509. connect() {
  26510. if ( this.filters.length > 0 ) {
  26511. this.source.connect( this.filters[ 0 ] );
  26512. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26513. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26514. }
  26515. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26516. } else {
  26517. this.source.connect( this.getOutput() );
  26518. }
  26519. this._connected = true;
  26520. return this;
  26521. }
  26522. disconnect() {
  26523. if ( this.filters.length > 0 ) {
  26524. this.source.disconnect( this.filters[ 0 ] );
  26525. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26526. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26527. }
  26528. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26529. } else {
  26530. this.source.disconnect( this.getOutput() );
  26531. }
  26532. this._connected = false;
  26533. return this;
  26534. }
  26535. getFilters() {
  26536. return this.filters;
  26537. }
  26538. setFilters( value ) {
  26539. if ( ! value ) value = [];
  26540. if ( this._connected === true ) {
  26541. this.disconnect();
  26542. this.filters = value.slice();
  26543. this.connect();
  26544. } else {
  26545. this.filters = value.slice();
  26546. }
  26547. return this;
  26548. }
  26549. setDetune( value ) {
  26550. this.detune = value;
  26551. if ( this.source.detune === undefined ) return; // only set detune when available
  26552. if ( this.isPlaying === true ) {
  26553. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26554. }
  26555. return this;
  26556. }
  26557. getDetune() {
  26558. return this.detune;
  26559. }
  26560. getFilter() {
  26561. return this.getFilters()[ 0 ];
  26562. }
  26563. setFilter( filter ) {
  26564. return this.setFilters( filter ? [ filter ] : [] );
  26565. }
  26566. setPlaybackRate( value ) {
  26567. if ( this.hasPlaybackControl === false ) {
  26568. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26569. return;
  26570. }
  26571. this.playbackRate = value;
  26572. if ( this.isPlaying === true ) {
  26573. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26574. }
  26575. return this;
  26576. }
  26577. getPlaybackRate() {
  26578. return this.playbackRate;
  26579. }
  26580. onEnded() {
  26581. this.isPlaying = false;
  26582. }
  26583. getLoop() {
  26584. if ( this.hasPlaybackControl === false ) {
  26585. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26586. return false;
  26587. }
  26588. return this.loop;
  26589. }
  26590. setLoop( value ) {
  26591. if ( this.hasPlaybackControl === false ) {
  26592. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26593. return;
  26594. }
  26595. this.loop = value;
  26596. if ( this.isPlaying === true ) {
  26597. this.source.loop = this.loop;
  26598. }
  26599. return this;
  26600. }
  26601. setLoopStart( value ) {
  26602. this.loopStart = value;
  26603. return this;
  26604. }
  26605. setLoopEnd( value ) {
  26606. this.loopEnd = value;
  26607. return this;
  26608. }
  26609. getVolume() {
  26610. return this.gain.gain.value;
  26611. }
  26612. setVolume( value ) {
  26613. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26614. return this;
  26615. }
  26616. }
  26617. const _position = /*@__PURE__*/ new Vector3();
  26618. const _quaternion = /*@__PURE__*/ new Quaternion();
  26619. const _scale = /*@__PURE__*/ new Vector3();
  26620. const _orientation = /*@__PURE__*/ new Vector3();
  26621. class PositionalAudio extends Audio {
  26622. constructor( listener ) {
  26623. super( listener );
  26624. this.panner = this.context.createPanner();
  26625. this.panner.panningModel = 'HRTF';
  26626. this.panner.connect( this.gain );
  26627. }
  26628. disconnect() {
  26629. super.disconnect();
  26630. this.panner.disconnect( this.gain );
  26631. }
  26632. getOutput() {
  26633. return this.panner;
  26634. }
  26635. getRefDistance() {
  26636. return this.panner.refDistance;
  26637. }
  26638. setRefDistance( value ) {
  26639. this.panner.refDistance = value;
  26640. return this;
  26641. }
  26642. getRolloffFactor() {
  26643. return this.panner.rolloffFactor;
  26644. }
  26645. setRolloffFactor( value ) {
  26646. this.panner.rolloffFactor = value;
  26647. return this;
  26648. }
  26649. getDistanceModel() {
  26650. return this.panner.distanceModel;
  26651. }
  26652. setDistanceModel( value ) {
  26653. this.panner.distanceModel = value;
  26654. return this;
  26655. }
  26656. getMaxDistance() {
  26657. return this.panner.maxDistance;
  26658. }
  26659. setMaxDistance( value ) {
  26660. this.panner.maxDistance = value;
  26661. return this;
  26662. }
  26663. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26664. this.panner.coneInnerAngle = coneInnerAngle;
  26665. this.panner.coneOuterAngle = coneOuterAngle;
  26666. this.panner.coneOuterGain = coneOuterGain;
  26667. return this;
  26668. }
  26669. updateMatrixWorld( force ) {
  26670. super.updateMatrixWorld( force );
  26671. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26672. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26673. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26674. const panner = this.panner;
  26675. if ( panner.positionX ) {
  26676. // code path for Chrome and Firefox (see #14393)
  26677. const endTime = this.context.currentTime + this.listener.timeDelta;
  26678. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26679. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26680. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26681. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26682. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26683. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26684. } else {
  26685. panner.setPosition( _position.x, _position.y, _position.z );
  26686. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26687. }
  26688. }
  26689. }
  26690. class AudioAnalyser {
  26691. constructor( audio, fftSize = 2048 ) {
  26692. this.analyser = audio.context.createAnalyser();
  26693. this.analyser.fftSize = fftSize;
  26694. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26695. audio.getOutput().connect( this.analyser );
  26696. }
  26697. getFrequencyData() {
  26698. this.analyser.getByteFrequencyData( this.data );
  26699. return this.data;
  26700. }
  26701. getAverageFrequency() {
  26702. let value = 0;
  26703. const data = this.getFrequencyData();
  26704. for ( let i = 0; i < data.length; i ++ ) {
  26705. value += data[ i ];
  26706. }
  26707. return value / data.length;
  26708. }
  26709. }
  26710. class PropertyMixer {
  26711. constructor( binding, typeName, valueSize ) {
  26712. this.binding = binding;
  26713. this.valueSize = valueSize;
  26714. let mixFunction,
  26715. mixFunctionAdditive,
  26716. setIdentity;
  26717. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26718. //
  26719. // interpolators can use .buffer as their .result
  26720. // the data then goes to 'incoming'
  26721. //
  26722. // 'accu0' and 'accu1' are used frame-interleaved for
  26723. // the cumulative result and are compared to detect
  26724. // changes
  26725. //
  26726. // 'orig' stores the original state of the property
  26727. //
  26728. // 'add' is used for additive cumulative results
  26729. //
  26730. // 'work' is optional and is only present for quaternion types. It is used
  26731. // to store intermediate quaternion multiplication results
  26732. switch ( typeName ) {
  26733. case 'quaternion':
  26734. mixFunction = this._slerp;
  26735. mixFunctionAdditive = this._slerpAdditive;
  26736. setIdentity = this._setAdditiveIdentityQuaternion;
  26737. this.buffer = new Float64Array( valueSize * 6 );
  26738. this._workIndex = 5;
  26739. break;
  26740. case 'string':
  26741. case 'bool':
  26742. mixFunction = this._select;
  26743. // Use the regular mix function and for additive on these types,
  26744. // additive is not relevant for non-numeric types
  26745. mixFunctionAdditive = this._select;
  26746. setIdentity = this._setAdditiveIdentityOther;
  26747. this.buffer = new Array( valueSize * 5 );
  26748. break;
  26749. default:
  26750. mixFunction = this._lerp;
  26751. mixFunctionAdditive = this._lerpAdditive;
  26752. setIdentity = this._setAdditiveIdentityNumeric;
  26753. this.buffer = new Float64Array( valueSize * 5 );
  26754. }
  26755. this._mixBufferRegion = mixFunction;
  26756. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26757. this._setIdentity = setIdentity;
  26758. this._origIndex = 3;
  26759. this._addIndex = 4;
  26760. this.cumulativeWeight = 0;
  26761. this.cumulativeWeightAdditive = 0;
  26762. this.useCount = 0;
  26763. this.referenceCount = 0;
  26764. }
  26765. // accumulate data in the 'incoming' region into 'accu<i>'
  26766. accumulate( accuIndex, weight ) {
  26767. // note: happily accumulating nothing when weight = 0, the caller knows
  26768. // the weight and shouldn't have made the call in the first place
  26769. const buffer = this.buffer,
  26770. stride = this.valueSize,
  26771. offset = accuIndex * stride + stride;
  26772. let currentWeight = this.cumulativeWeight;
  26773. if ( currentWeight === 0 ) {
  26774. // accuN := incoming * weight
  26775. for ( let i = 0; i !== stride; ++ i ) {
  26776. buffer[ offset + i ] = buffer[ i ];
  26777. }
  26778. currentWeight = weight;
  26779. } else {
  26780. // accuN := accuN + incoming * weight
  26781. currentWeight += weight;
  26782. const mix = weight / currentWeight;
  26783. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26784. }
  26785. this.cumulativeWeight = currentWeight;
  26786. }
  26787. // accumulate data in the 'incoming' region into 'add'
  26788. accumulateAdditive( weight ) {
  26789. const buffer = this.buffer,
  26790. stride = this.valueSize,
  26791. offset = stride * this._addIndex;
  26792. if ( this.cumulativeWeightAdditive === 0 ) {
  26793. // add = identity
  26794. this._setIdentity();
  26795. }
  26796. // add := add + incoming * weight
  26797. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26798. this.cumulativeWeightAdditive += weight;
  26799. }
  26800. // apply the state of 'accu<i>' to the binding when accus differ
  26801. apply( accuIndex ) {
  26802. const stride = this.valueSize,
  26803. buffer = this.buffer,
  26804. offset = accuIndex * stride + stride,
  26805. weight = this.cumulativeWeight,
  26806. weightAdditive = this.cumulativeWeightAdditive,
  26807. binding = this.binding;
  26808. this.cumulativeWeight = 0;
  26809. this.cumulativeWeightAdditive = 0;
  26810. if ( weight < 1 ) {
  26811. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26812. const originalValueOffset = stride * this._origIndex;
  26813. this._mixBufferRegion(
  26814. buffer, offset, originalValueOffset, 1 - weight, stride );
  26815. }
  26816. if ( weightAdditive > 0 ) {
  26817. // accuN := accuN + additive accuN
  26818. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26819. }
  26820. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26821. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26822. // value has changed -> update scene graph
  26823. binding.setValue( buffer, offset );
  26824. break;
  26825. }
  26826. }
  26827. }
  26828. // remember the state of the bound property and copy it to both accus
  26829. saveOriginalState() {
  26830. const binding = this.binding;
  26831. const buffer = this.buffer,
  26832. stride = this.valueSize,
  26833. originalValueOffset = stride * this._origIndex;
  26834. binding.getValue( buffer, originalValueOffset );
  26835. // accu[0..1] := orig -- initially detect changes against the original
  26836. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26837. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26838. }
  26839. // Add to identity for additive
  26840. this._setIdentity();
  26841. this.cumulativeWeight = 0;
  26842. this.cumulativeWeightAdditive = 0;
  26843. }
  26844. // apply the state previously taken via 'saveOriginalState' to the binding
  26845. restoreOriginalState() {
  26846. const originalValueOffset = this.valueSize * 3;
  26847. this.binding.setValue( this.buffer, originalValueOffset );
  26848. }
  26849. _setAdditiveIdentityNumeric() {
  26850. const startIndex = this._addIndex * this.valueSize;
  26851. const endIndex = startIndex + this.valueSize;
  26852. for ( let i = startIndex; i < endIndex; i ++ ) {
  26853. this.buffer[ i ] = 0;
  26854. }
  26855. }
  26856. _setAdditiveIdentityQuaternion() {
  26857. this._setAdditiveIdentityNumeric();
  26858. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26859. }
  26860. _setAdditiveIdentityOther() {
  26861. const startIndex = this._origIndex * this.valueSize;
  26862. const targetIndex = this._addIndex * this.valueSize;
  26863. for ( let i = 0; i < this.valueSize; i ++ ) {
  26864. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26865. }
  26866. }
  26867. // mix functions
  26868. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26869. if ( t >= 0.5 ) {
  26870. for ( let i = 0; i !== stride; ++ i ) {
  26871. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26872. }
  26873. }
  26874. }
  26875. _slerp( buffer, dstOffset, srcOffset, t ) {
  26876. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26877. }
  26878. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26879. const workOffset = this._workIndex * stride;
  26880. // Store result in intermediate buffer offset
  26881. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26882. // Slerp to the intermediate result
  26883. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26884. }
  26885. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26886. const s = 1 - t;
  26887. for ( let i = 0; i !== stride; ++ i ) {
  26888. const j = dstOffset + i;
  26889. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26890. }
  26891. }
  26892. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26893. for ( let i = 0; i !== stride; ++ i ) {
  26894. const j = dstOffset + i;
  26895. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26896. }
  26897. }
  26898. }
  26899. // Characters [].:/ are reserved for track binding syntax.
  26900. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26901. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26902. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26903. // only latin characters, and the unicode \p{L} is not yet supported. So
  26904. // instead, we exclude reserved characters and match everything else.
  26905. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26906. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26907. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26908. // be matched to parse the rest of the track name.
  26909. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26910. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26911. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26912. // Object on target node, and accessor. May not contain reserved
  26913. // characters. Accessor may contain any character except closing bracket.
  26914. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26915. // Property and accessor. May not contain reserved characters. Accessor may
  26916. // contain any non-bracket characters.
  26917. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26918. const _trackRe = new RegExp( ''
  26919. + '^'
  26920. + _directoryRe
  26921. + _nodeRe
  26922. + _objectRe
  26923. + _propertyRe
  26924. + '$'
  26925. );
  26926. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  26927. class Composite {
  26928. constructor( targetGroup, path, optionalParsedPath ) {
  26929. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26930. this._targetGroup = targetGroup;
  26931. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26932. }
  26933. getValue( array, offset ) {
  26934. this.bind(); // bind all binding
  26935. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26936. binding = this._bindings[ firstValidIndex ];
  26937. // and only call .getValue on the first
  26938. if ( binding !== undefined ) binding.getValue( array, offset );
  26939. }
  26940. setValue( array, offset ) {
  26941. const bindings = this._bindings;
  26942. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26943. bindings[ i ].setValue( array, offset );
  26944. }
  26945. }
  26946. bind() {
  26947. const bindings = this._bindings;
  26948. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26949. bindings[ i ].bind();
  26950. }
  26951. }
  26952. unbind() {
  26953. const bindings = this._bindings;
  26954. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26955. bindings[ i ].unbind();
  26956. }
  26957. }
  26958. }
  26959. // Note: This class uses a State pattern on a per-method basis:
  26960. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26961. // prototype version of these methods with one that represents
  26962. // the bound state. When the property is not found, the methods
  26963. // become no-ops.
  26964. class PropertyBinding {
  26965. constructor( rootNode, path, parsedPath ) {
  26966. this.path = path;
  26967. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26968. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  26969. this.rootNode = rootNode;
  26970. // initial state of these methods that calls 'bind'
  26971. this.getValue = this._getValue_unbound;
  26972. this.setValue = this._setValue_unbound;
  26973. }
  26974. static create( root, path, parsedPath ) {
  26975. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26976. return new PropertyBinding( root, path, parsedPath );
  26977. } else {
  26978. return new PropertyBinding.Composite( root, path, parsedPath );
  26979. }
  26980. }
  26981. /**
  26982. * Replaces spaces with underscores and removes unsupported characters from
  26983. * node names, to ensure compatibility with parseTrackName().
  26984. *
  26985. * @param {string} name Node name to be sanitized.
  26986. * @return {string}
  26987. */
  26988. static sanitizeNodeName( name ) {
  26989. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26990. }
  26991. static parseTrackName( trackName ) {
  26992. const matches = _trackRe.exec( trackName );
  26993. if ( matches === null ) {
  26994. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26995. }
  26996. const results = {
  26997. // directoryName: matches[ 1 ], // (tschw) currently unused
  26998. nodeName: matches[ 2 ],
  26999. objectName: matches[ 3 ],
  27000. objectIndex: matches[ 4 ],
  27001. propertyName: matches[ 5 ], // required
  27002. propertyIndex: matches[ 6 ]
  27003. };
  27004. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  27005. if ( lastDot !== undefined && lastDot !== - 1 ) {
  27006. const objectName = results.nodeName.substring( lastDot + 1 );
  27007. // Object names must be checked against an allowlist. Otherwise, there
  27008. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  27009. // 'bar' could be the objectName, or part of a nodeName (which can
  27010. // include '.' characters).
  27011. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  27012. results.nodeName = results.nodeName.substring( 0, lastDot );
  27013. results.objectName = objectName;
  27014. }
  27015. }
  27016. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  27017. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  27018. }
  27019. return results;
  27020. }
  27021. static findNode( root, nodeName ) {
  27022. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  27023. return root;
  27024. }
  27025. // search into skeleton bones.
  27026. if ( root.skeleton ) {
  27027. const bone = root.skeleton.getBoneByName( nodeName );
  27028. if ( bone !== undefined ) {
  27029. return bone;
  27030. }
  27031. }
  27032. // search into node subtree.
  27033. if ( root.children ) {
  27034. const searchNodeSubtree = function ( children ) {
  27035. for ( let i = 0; i < children.length; i ++ ) {
  27036. const childNode = children[ i ];
  27037. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  27038. return childNode;
  27039. }
  27040. const result = searchNodeSubtree( childNode.children );
  27041. if ( result ) return result;
  27042. }
  27043. return null;
  27044. };
  27045. const subTreeNode = searchNodeSubtree( root.children );
  27046. if ( subTreeNode ) {
  27047. return subTreeNode;
  27048. }
  27049. }
  27050. return null;
  27051. }
  27052. // these are used to "bind" a nonexistent property
  27053. _getValue_unavailable() {}
  27054. _setValue_unavailable() {}
  27055. // Getters
  27056. _getValue_direct( buffer, offset ) {
  27057. buffer[ offset ] = this.targetObject[ this.propertyName ];
  27058. }
  27059. _getValue_array( buffer, offset ) {
  27060. const source = this.resolvedProperty;
  27061. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  27062. buffer[ offset ++ ] = source[ i ];
  27063. }
  27064. }
  27065. _getValue_arrayElement( buffer, offset ) {
  27066. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  27067. }
  27068. _getValue_toArray( buffer, offset ) {
  27069. this.resolvedProperty.toArray( buffer, offset );
  27070. }
  27071. // Direct
  27072. _setValue_direct( buffer, offset ) {
  27073. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27074. }
  27075. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  27076. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27077. this.targetObject.needsUpdate = true;
  27078. }
  27079. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27080. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27081. this.targetObject.matrixWorldNeedsUpdate = true;
  27082. }
  27083. // EntireArray
  27084. _setValue_array( buffer, offset ) {
  27085. const dest = this.resolvedProperty;
  27086. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27087. dest[ i ] = buffer[ offset ++ ];
  27088. }
  27089. }
  27090. _setValue_array_setNeedsUpdate( buffer, offset ) {
  27091. const dest = this.resolvedProperty;
  27092. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27093. dest[ i ] = buffer[ offset ++ ];
  27094. }
  27095. this.targetObject.needsUpdate = true;
  27096. }
  27097. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27098. const dest = this.resolvedProperty;
  27099. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27100. dest[ i ] = buffer[ offset ++ ];
  27101. }
  27102. this.targetObject.matrixWorldNeedsUpdate = true;
  27103. }
  27104. // ArrayElement
  27105. _setValue_arrayElement( buffer, offset ) {
  27106. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27107. }
  27108. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27109. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27110. this.targetObject.needsUpdate = true;
  27111. }
  27112. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27113. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27114. this.targetObject.matrixWorldNeedsUpdate = true;
  27115. }
  27116. // HasToFromArray
  27117. _setValue_fromArray( buffer, offset ) {
  27118. this.resolvedProperty.fromArray( buffer, offset );
  27119. }
  27120. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27121. this.resolvedProperty.fromArray( buffer, offset );
  27122. this.targetObject.needsUpdate = true;
  27123. }
  27124. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27125. this.resolvedProperty.fromArray( buffer, offset );
  27126. this.targetObject.matrixWorldNeedsUpdate = true;
  27127. }
  27128. _getValue_unbound( targetArray, offset ) {
  27129. this.bind();
  27130. this.getValue( targetArray, offset );
  27131. }
  27132. _setValue_unbound( sourceArray, offset ) {
  27133. this.bind();
  27134. this.setValue( sourceArray, offset );
  27135. }
  27136. // create getter / setter pair for a property in the scene graph
  27137. bind() {
  27138. let targetObject = this.node;
  27139. const parsedPath = this.parsedPath;
  27140. const objectName = parsedPath.objectName;
  27141. const propertyName = parsedPath.propertyName;
  27142. let propertyIndex = parsedPath.propertyIndex;
  27143. if ( ! targetObject ) {
  27144. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  27145. this.node = targetObject;
  27146. }
  27147. // set fail state so we can just 'return' on error
  27148. this.getValue = this._getValue_unavailable;
  27149. this.setValue = this._setValue_unavailable;
  27150. // ensure there is a value node
  27151. if ( ! targetObject ) {
  27152. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27153. return;
  27154. }
  27155. if ( objectName ) {
  27156. let objectIndex = parsedPath.objectIndex;
  27157. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27158. switch ( objectName ) {
  27159. case 'materials':
  27160. if ( ! targetObject.material ) {
  27161. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27162. return;
  27163. }
  27164. if ( ! targetObject.material.materials ) {
  27165. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27166. return;
  27167. }
  27168. targetObject = targetObject.material.materials;
  27169. break;
  27170. case 'bones':
  27171. if ( ! targetObject.skeleton ) {
  27172. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27173. return;
  27174. }
  27175. // potential future optimization: skip this if propertyIndex is already an integer
  27176. // and convert the integer string to a true integer.
  27177. targetObject = targetObject.skeleton.bones;
  27178. // support resolving morphTarget names into indices.
  27179. for ( let i = 0; i < targetObject.length; i ++ ) {
  27180. if ( targetObject[ i ].name === objectIndex ) {
  27181. objectIndex = i;
  27182. break;
  27183. }
  27184. }
  27185. break;
  27186. case 'map':
  27187. if ( 'map' in targetObject ) {
  27188. targetObject = targetObject.map;
  27189. break;
  27190. }
  27191. if ( ! targetObject.material ) {
  27192. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27193. return;
  27194. }
  27195. if ( ! targetObject.material.map ) {
  27196. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  27197. return;
  27198. }
  27199. targetObject = targetObject.material.map;
  27200. break;
  27201. default:
  27202. if ( targetObject[ objectName ] === undefined ) {
  27203. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27204. return;
  27205. }
  27206. targetObject = targetObject[ objectName ];
  27207. }
  27208. if ( objectIndex !== undefined ) {
  27209. if ( targetObject[ objectIndex ] === undefined ) {
  27210. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27211. return;
  27212. }
  27213. targetObject = targetObject[ objectIndex ];
  27214. }
  27215. }
  27216. // resolve property
  27217. const nodeProperty = targetObject[ propertyName ];
  27218. if ( nodeProperty === undefined ) {
  27219. const nodeName = parsedPath.nodeName;
  27220. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27221. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27222. return;
  27223. }
  27224. // determine versioning scheme
  27225. let versioning = this.Versioning.None;
  27226. this.targetObject = targetObject;
  27227. if ( targetObject.needsUpdate !== undefined ) { // material
  27228. versioning = this.Versioning.NeedsUpdate;
  27229. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27230. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27231. }
  27232. // determine how the property gets bound
  27233. let bindingType = this.BindingType.Direct;
  27234. if ( propertyIndex !== undefined ) {
  27235. // access a sub element of the property array (only primitives are supported right now)
  27236. if ( propertyName === 'morphTargetInfluences' ) {
  27237. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27238. // support resolving morphTarget names into indices.
  27239. if ( ! targetObject.geometry ) {
  27240. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27241. return;
  27242. }
  27243. if ( ! targetObject.geometry.morphAttributes ) {
  27244. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27245. return;
  27246. }
  27247. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27248. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27249. }
  27250. }
  27251. bindingType = this.BindingType.ArrayElement;
  27252. this.resolvedProperty = nodeProperty;
  27253. this.propertyIndex = propertyIndex;
  27254. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27255. // must use copy for Object3D.Euler/Quaternion
  27256. bindingType = this.BindingType.HasFromToArray;
  27257. this.resolvedProperty = nodeProperty;
  27258. } else if ( Array.isArray( nodeProperty ) ) {
  27259. bindingType = this.BindingType.EntireArray;
  27260. this.resolvedProperty = nodeProperty;
  27261. } else {
  27262. this.propertyName = propertyName;
  27263. }
  27264. // select getter / setter
  27265. this.getValue = this.GetterByBindingType[ bindingType ];
  27266. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27267. }
  27268. unbind() {
  27269. this.node = null;
  27270. // back to the prototype version of getValue / setValue
  27271. // note: avoiding to mutate the shape of 'this' via 'delete'
  27272. this.getValue = this._getValue_unbound;
  27273. this.setValue = this._setValue_unbound;
  27274. }
  27275. }
  27276. PropertyBinding.Composite = Composite;
  27277. PropertyBinding.prototype.BindingType = {
  27278. Direct: 0,
  27279. EntireArray: 1,
  27280. ArrayElement: 2,
  27281. HasFromToArray: 3
  27282. };
  27283. PropertyBinding.prototype.Versioning = {
  27284. None: 0,
  27285. NeedsUpdate: 1,
  27286. MatrixWorldNeedsUpdate: 2
  27287. };
  27288. PropertyBinding.prototype.GetterByBindingType = [
  27289. PropertyBinding.prototype._getValue_direct,
  27290. PropertyBinding.prototype._getValue_array,
  27291. PropertyBinding.prototype._getValue_arrayElement,
  27292. PropertyBinding.prototype._getValue_toArray,
  27293. ];
  27294. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  27295. [
  27296. // Direct
  27297. PropertyBinding.prototype._setValue_direct,
  27298. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  27299. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  27300. ], [
  27301. // EntireArray
  27302. PropertyBinding.prototype._setValue_array,
  27303. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  27304. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  27305. ], [
  27306. // ArrayElement
  27307. PropertyBinding.prototype._setValue_arrayElement,
  27308. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  27309. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  27310. ], [
  27311. // HasToFromArray
  27312. PropertyBinding.prototype._setValue_fromArray,
  27313. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  27314. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  27315. ]
  27316. ];
  27317. /**
  27318. *
  27319. * A group of objects that receives a shared animation state.
  27320. *
  27321. * Usage:
  27322. *
  27323. * - Add objects you would otherwise pass as 'root' to the
  27324. * constructor or the .clipAction method of AnimationMixer.
  27325. *
  27326. * - Instead pass this object as 'root'.
  27327. *
  27328. * - You can also add and remove objects later when the mixer
  27329. * is running.
  27330. *
  27331. * Note:
  27332. *
  27333. * Objects of this class appear as one object to the mixer,
  27334. * so cache control of the individual objects must be done
  27335. * on the group.
  27336. *
  27337. * Limitation:
  27338. *
  27339. * - The animated properties must be compatible among the
  27340. * all objects in the group.
  27341. *
  27342. * - A single property can either be controlled through a
  27343. * target group or directly, but not both.
  27344. */
  27345. class AnimationObjectGroup {
  27346. constructor() {
  27347. this.isAnimationObjectGroup = true;
  27348. this.uuid = generateUUID();
  27349. // cached objects followed by the active ones
  27350. this._objects = Array.prototype.slice.call( arguments );
  27351. this.nCachedObjects_ = 0; // threshold
  27352. // note: read by PropertyBinding.Composite
  27353. const indices = {};
  27354. this._indicesByUUID = indices; // for bookkeeping
  27355. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27356. indices[ arguments[ i ].uuid ] = i;
  27357. }
  27358. this._paths = []; // inside: string
  27359. this._parsedPaths = []; // inside: { we don't care, here }
  27360. this._bindings = []; // inside: Array< PropertyBinding >
  27361. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27362. const scope = this;
  27363. this.stats = {
  27364. objects: {
  27365. get total() {
  27366. return scope._objects.length;
  27367. },
  27368. get inUse() {
  27369. return this.total - scope.nCachedObjects_;
  27370. }
  27371. },
  27372. get bindingsPerObject() {
  27373. return scope._bindings.length;
  27374. }
  27375. };
  27376. }
  27377. add() {
  27378. const objects = this._objects,
  27379. indicesByUUID = this._indicesByUUID,
  27380. paths = this._paths,
  27381. parsedPaths = this._parsedPaths,
  27382. bindings = this._bindings,
  27383. nBindings = bindings.length;
  27384. let knownObject = undefined,
  27385. nObjects = objects.length,
  27386. nCachedObjects = this.nCachedObjects_;
  27387. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27388. const object = arguments[ i ],
  27389. uuid = object.uuid;
  27390. let index = indicesByUUID[ uuid ];
  27391. if ( index === undefined ) {
  27392. // unknown object -> add it to the ACTIVE region
  27393. index = nObjects ++;
  27394. indicesByUUID[ uuid ] = index;
  27395. objects.push( object );
  27396. // accounting is done, now do the same for all bindings
  27397. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27398. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27399. }
  27400. } else if ( index < nCachedObjects ) {
  27401. knownObject = objects[ index ];
  27402. // move existing object to the ACTIVE region
  27403. const firstActiveIndex = -- nCachedObjects,
  27404. lastCachedObject = objects[ firstActiveIndex ];
  27405. indicesByUUID[ lastCachedObject.uuid ] = index;
  27406. objects[ index ] = lastCachedObject;
  27407. indicesByUUID[ uuid ] = firstActiveIndex;
  27408. objects[ firstActiveIndex ] = object;
  27409. // accounting is done, now do the same for all bindings
  27410. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27411. const bindingsForPath = bindings[ j ],
  27412. lastCached = bindingsForPath[ firstActiveIndex ];
  27413. let binding = bindingsForPath[ index ];
  27414. bindingsForPath[ index ] = lastCached;
  27415. if ( binding === undefined ) {
  27416. // since we do not bother to create new bindings
  27417. // for objects that are cached, the binding may
  27418. // or may not exist
  27419. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27420. }
  27421. bindingsForPath[ firstActiveIndex ] = binding;
  27422. }
  27423. } else if ( objects[ index ] !== knownObject ) {
  27424. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27425. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27426. } // else the object is already where we want it to be
  27427. } // for arguments
  27428. this.nCachedObjects_ = nCachedObjects;
  27429. }
  27430. remove() {
  27431. const objects = this._objects,
  27432. indicesByUUID = this._indicesByUUID,
  27433. bindings = this._bindings,
  27434. nBindings = bindings.length;
  27435. let nCachedObjects = this.nCachedObjects_;
  27436. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27437. const object = arguments[ i ],
  27438. uuid = object.uuid,
  27439. index = indicesByUUID[ uuid ];
  27440. if ( index !== undefined && index >= nCachedObjects ) {
  27441. // move existing object into the CACHED region
  27442. const lastCachedIndex = nCachedObjects ++,
  27443. firstActiveObject = objects[ lastCachedIndex ];
  27444. indicesByUUID[ firstActiveObject.uuid ] = index;
  27445. objects[ index ] = firstActiveObject;
  27446. indicesByUUID[ uuid ] = lastCachedIndex;
  27447. objects[ lastCachedIndex ] = object;
  27448. // accounting is done, now do the same for all bindings
  27449. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27450. const bindingsForPath = bindings[ j ],
  27451. firstActive = bindingsForPath[ lastCachedIndex ],
  27452. binding = bindingsForPath[ index ];
  27453. bindingsForPath[ index ] = firstActive;
  27454. bindingsForPath[ lastCachedIndex ] = binding;
  27455. }
  27456. }
  27457. } // for arguments
  27458. this.nCachedObjects_ = nCachedObjects;
  27459. }
  27460. // remove & forget
  27461. uncache() {
  27462. const objects = this._objects,
  27463. indicesByUUID = this._indicesByUUID,
  27464. bindings = this._bindings,
  27465. nBindings = bindings.length;
  27466. let nCachedObjects = this.nCachedObjects_,
  27467. nObjects = objects.length;
  27468. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27469. const object = arguments[ i ],
  27470. uuid = object.uuid,
  27471. index = indicesByUUID[ uuid ];
  27472. if ( index !== undefined ) {
  27473. delete indicesByUUID[ uuid ];
  27474. if ( index < nCachedObjects ) {
  27475. // object is cached, shrink the CACHED region
  27476. const firstActiveIndex = -- nCachedObjects,
  27477. lastCachedObject = objects[ firstActiveIndex ],
  27478. lastIndex = -- nObjects,
  27479. lastObject = objects[ lastIndex ];
  27480. // last cached object takes this object's place
  27481. indicesByUUID[ lastCachedObject.uuid ] = index;
  27482. objects[ index ] = lastCachedObject;
  27483. // last object goes to the activated slot and pop
  27484. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27485. objects[ firstActiveIndex ] = lastObject;
  27486. objects.pop();
  27487. // accounting is done, now do the same for all bindings
  27488. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27489. const bindingsForPath = bindings[ j ],
  27490. lastCached = bindingsForPath[ firstActiveIndex ],
  27491. last = bindingsForPath[ lastIndex ];
  27492. bindingsForPath[ index ] = lastCached;
  27493. bindingsForPath[ firstActiveIndex ] = last;
  27494. bindingsForPath.pop();
  27495. }
  27496. } else {
  27497. // object is active, just swap with the last and pop
  27498. const lastIndex = -- nObjects,
  27499. lastObject = objects[ lastIndex ];
  27500. if ( lastIndex > 0 ) {
  27501. indicesByUUID[ lastObject.uuid ] = index;
  27502. }
  27503. objects[ index ] = lastObject;
  27504. objects.pop();
  27505. // accounting is done, now do the same for all bindings
  27506. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27507. const bindingsForPath = bindings[ j ];
  27508. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27509. bindingsForPath.pop();
  27510. }
  27511. } // cached or active
  27512. } // if object is known
  27513. } // for arguments
  27514. this.nCachedObjects_ = nCachedObjects;
  27515. }
  27516. // Internal interface used by befriended PropertyBinding.Composite:
  27517. subscribe_( path, parsedPath ) {
  27518. // returns an array of bindings for the given path that is changed
  27519. // according to the contained objects in the group
  27520. const indicesByPath = this._bindingsIndicesByPath;
  27521. let index = indicesByPath[ path ];
  27522. const bindings = this._bindings;
  27523. if ( index !== undefined ) return bindings[ index ];
  27524. const paths = this._paths,
  27525. parsedPaths = this._parsedPaths,
  27526. objects = this._objects,
  27527. nObjects = objects.length,
  27528. nCachedObjects = this.nCachedObjects_,
  27529. bindingsForPath = new Array( nObjects );
  27530. index = bindings.length;
  27531. indicesByPath[ path ] = index;
  27532. paths.push( path );
  27533. parsedPaths.push( parsedPath );
  27534. bindings.push( bindingsForPath );
  27535. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27536. const object = objects[ i ];
  27537. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27538. }
  27539. return bindingsForPath;
  27540. }
  27541. unsubscribe_( path ) {
  27542. // tells the group to forget about a property path and no longer
  27543. // update the array previously obtained with 'subscribe_'
  27544. const indicesByPath = this._bindingsIndicesByPath,
  27545. index = indicesByPath[ path ];
  27546. if ( index !== undefined ) {
  27547. const paths = this._paths,
  27548. parsedPaths = this._parsedPaths,
  27549. bindings = this._bindings,
  27550. lastBindingsIndex = bindings.length - 1,
  27551. lastBindings = bindings[ lastBindingsIndex ],
  27552. lastBindingsPath = path[ lastBindingsIndex ];
  27553. indicesByPath[ lastBindingsPath ] = index;
  27554. bindings[ index ] = lastBindings;
  27555. bindings.pop();
  27556. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27557. parsedPaths.pop();
  27558. paths[ index ] = paths[ lastBindingsIndex ];
  27559. paths.pop();
  27560. }
  27561. }
  27562. }
  27563. class AnimationAction {
  27564. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27565. this._mixer = mixer;
  27566. this._clip = clip;
  27567. this._localRoot = localRoot;
  27568. this.blendMode = blendMode;
  27569. const tracks = clip.tracks,
  27570. nTracks = tracks.length,
  27571. interpolants = new Array( nTracks );
  27572. const interpolantSettings = {
  27573. endingStart: ZeroCurvatureEnding,
  27574. endingEnd: ZeroCurvatureEnding
  27575. };
  27576. for ( let i = 0; i !== nTracks; ++ i ) {
  27577. const interpolant = tracks[ i ].createInterpolant( null );
  27578. interpolants[ i ] = interpolant;
  27579. interpolant.settings = interpolantSettings;
  27580. }
  27581. this._interpolantSettings = interpolantSettings;
  27582. this._interpolants = interpolants; // bound by the mixer
  27583. // inside: PropertyMixer (managed by the mixer)
  27584. this._propertyBindings = new Array( nTracks );
  27585. this._cacheIndex = null; // for the memory manager
  27586. this._byClipCacheIndex = null; // for the memory manager
  27587. this._timeScaleInterpolant = null;
  27588. this._weightInterpolant = null;
  27589. this.loop = LoopRepeat;
  27590. this._loopCount = - 1;
  27591. // global mixer time when the action is to be started
  27592. // it's set back to 'null' upon start of the action
  27593. this._startTime = null;
  27594. // scaled local time of the action
  27595. // gets clamped or wrapped to 0..clip.duration according to loop
  27596. this.time = 0;
  27597. this.timeScale = 1;
  27598. this._effectiveTimeScale = 1;
  27599. this.weight = 1;
  27600. this._effectiveWeight = 1;
  27601. this.repetitions = Infinity; // no. of repetitions when looping
  27602. this.paused = false; // true -> zero effective time scale
  27603. this.enabled = true; // false -> zero effective weight
  27604. this.clampWhenFinished = false;// keep feeding the last frame?
  27605. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27606. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27607. }
  27608. // State & Scheduling
  27609. play() {
  27610. this._mixer._activateAction( this );
  27611. return this;
  27612. }
  27613. stop() {
  27614. this._mixer._deactivateAction( this );
  27615. return this.reset();
  27616. }
  27617. reset() {
  27618. this.paused = false;
  27619. this.enabled = true;
  27620. this.time = 0; // restart clip
  27621. this._loopCount = - 1;// forget previous loops
  27622. this._startTime = null;// forget scheduling
  27623. return this.stopFading().stopWarping();
  27624. }
  27625. isRunning() {
  27626. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27627. this._startTime === null && this._mixer._isActiveAction( this );
  27628. }
  27629. // return true when play has been called
  27630. isScheduled() {
  27631. return this._mixer._isActiveAction( this );
  27632. }
  27633. startAt( time ) {
  27634. this._startTime = time;
  27635. return this;
  27636. }
  27637. setLoop( mode, repetitions ) {
  27638. this.loop = mode;
  27639. this.repetitions = repetitions;
  27640. return this;
  27641. }
  27642. // Weight
  27643. // set the weight stopping any scheduled fading
  27644. // although .enabled = false yields an effective weight of zero, this
  27645. // method does *not* change .enabled, because it would be confusing
  27646. setEffectiveWeight( weight ) {
  27647. this.weight = weight;
  27648. // note: same logic as when updated at runtime
  27649. this._effectiveWeight = this.enabled ? weight : 0;
  27650. return this.stopFading();
  27651. }
  27652. // return the weight considering fading and .enabled
  27653. getEffectiveWeight() {
  27654. return this._effectiveWeight;
  27655. }
  27656. fadeIn( duration ) {
  27657. return this._scheduleFading( duration, 0, 1 );
  27658. }
  27659. fadeOut( duration ) {
  27660. return this._scheduleFading( duration, 1, 0 );
  27661. }
  27662. crossFadeFrom( fadeOutAction, duration, warp ) {
  27663. fadeOutAction.fadeOut( duration );
  27664. this.fadeIn( duration );
  27665. if ( warp ) {
  27666. const fadeInDuration = this._clip.duration,
  27667. fadeOutDuration = fadeOutAction._clip.duration,
  27668. startEndRatio = fadeOutDuration / fadeInDuration,
  27669. endStartRatio = fadeInDuration / fadeOutDuration;
  27670. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27671. this.warp( endStartRatio, 1.0, duration );
  27672. }
  27673. return this;
  27674. }
  27675. crossFadeTo( fadeInAction, duration, warp ) {
  27676. return fadeInAction.crossFadeFrom( this, duration, warp );
  27677. }
  27678. stopFading() {
  27679. const weightInterpolant = this._weightInterpolant;
  27680. if ( weightInterpolant !== null ) {
  27681. this._weightInterpolant = null;
  27682. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27683. }
  27684. return this;
  27685. }
  27686. // Time Scale Control
  27687. // set the time scale stopping any scheduled warping
  27688. // although .paused = true yields an effective time scale of zero, this
  27689. // method does *not* change .paused, because it would be confusing
  27690. setEffectiveTimeScale( timeScale ) {
  27691. this.timeScale = timeScale;
  27692. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27693. return this.stopWarping();
  27694. }
  27695. // return the time scale considering warping and .paused
  27696. getEffectiveTimeScale() {
  27697. return this._effectiveTimeScale;
  27698. }
  27699. setDuration( duration ) {
  27700. this.timeScale = this._clip.duration / duration;
  27701. return this.stopWarping();
  27702. }
  27703. syncWith( action ) {
  27704. this.time = action.time;
  27705. this.timeScale = action.timeScale;
  27706. return this.stopWarping();
  27707. }
  27708. halt( duration ) {
  27709. return this.warp( this._effectiveTimeScale, 0, duration );
  27710. }
  27711. warp( startTimeScale, endTimeScale, duration ) {
  27712. const mixer = this._mixer,
  27713. now = mixer.time,
  27714. timeScale = this.timeScale;
  27715. let interpolant = this._timeScaleInterpolant;
  27716. if ( interpolant === null ) {
  27717. interpolant = mixer._lendControlInterpolant();
  27718. this._timeScaleInterpolant = interpolant;
  27719. }
  27720. const times = interpolant.parameterPositions,
  27721. values = interpolant.sampleValues;
  27722. times[ 0 ] = now;
  27723. times[ 1 ] = now + duration;
  27724. values[ 0 ] = startTimeScale / timeScale;
  27725. values[ 1 ] = endTimeScale / timeScale;
  27726. return this;
  27727. }
  27728. stopWarping() {
  27729. const timeScaleInterpolant = this._timeScaleInterpolant;
  27730. if ( timeScaleInterpolant !== null ) {
  27731. this._timeScaleInterpolant = null;
  27732. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27733. }
  27734. return this;
  27735. }
  27736. // Object Accessors
  27737. getMixer() {
  27738. return this._mixer;
  27739. }
  27740. getClip() {
  27741. return this._clip;
  27742. }
  27743. getRoot() {
  27744. return this._localRoot || this._mixer._root;
  27745. }
  27746. // Interna
  27747. _update( time, deltaTime, timeDirection, accuIndex ) {
  27748. // called by the mixer
  27749. if ( ! this.enabled ) {
  27750. // call ._updateWeight() to update ._effectiveWeight
  27751. this._updateWeight( time );
  27752. return;
  27753. }
  27754. const startTime = this._startTime;
  27755. if ( startTime !== null ) {
  27756. // check for scheduled start of action
  27757. const timeRunning = ( time - startTime ) * timeDirection;
  27758. if ( timeRunning < 0 || timeDirection === 0 ) {
  27759. deltaTime = 0;
  27760. } else {
  27761. this._startTime = null; // unschedule
  27762. deltaTime = timeDirection * timeRunning;
  27763. }
  27764. }
  27765. // apply time scale and advance time
  27766. deltaTime *= this._updateTimeScale( time );
  27767. const clipTime = this._updateTime( deltaTime );
  27768. // note: _updateTime may disable the action resulting in
  27769. // an effective weight of 0
  27770. const weight = this._updateWeight( time );
  27771. if ( weight > 0 ) {
  27772. const interpolants = this._interpolants;
  27773. const propertyMixers = this._propertyBindings;
  27774. switch ( this.blendMode ) {
  27775. case AdditiveAnimationBlendMode:
  27776. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27777. interpolants[ j ].evaluate( clipTime );
  27778. propertyMixers[ j ].accumulateAdditive( weight );
  27779. }
  27780. break;
  27781. case NormalAnimationBlendMode:
  27782. default:
  27783. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27784. interpolants[ j ].evaluate( clipTime );
  27785. propertyMixers[ j ].accumulate( accuIndex, weight );
  27786. }
  27787. }
  27788. }
  27789. }
  27790. _updateWeight( time ) {
  27791. let weight = 0;
  27792. if ( this.enabled ) {
  27793. weight = this.weight;
  27794. const interpolant = this._weightInterpolant;
  27795. if ( interpolant !== null ) {
  27796. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27797. weight *= interpolantValue;
  27798. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27799. this.stopFading();
  27800. if ( interpolantValue === 0 ) {
  27801. // faded out, disable
  27802. this.enabled = false;
  27803. }
  27804. }
  27805. }
  27806. }
  27807. this._effectiveWeight = weight;
  27808. return weight;
  27809. }
  27810. _updateTimeScale( time ) {
  27811. let timeScale = 0;
  27812. if ( ! this.paused ) {
  27813. timeScale = this.timeScale;
  27814. const interpolant = this._timeScaleInterpolant;
  27815. if ( interpolant !== null ) {
  27816. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27817. timeScale *= interpolantValue;
  27818. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27819. this.stopWarping();
  27820. if ( timeScale === 0 ) {
  27821. // motion has halted, pause
  27822. this.paused = true;
  27823. } else {
  27824. // warp done - apply final time scale
  27825. this.timeScale = timeScale;
  27826. }
  27827. }
  27828. }
  27829. }
  27830. this._effectiveTimeScale = timeScale;
  27831. return timeScale;
  27832. }
  27833. _updateTime( deltaTime ) {
  27834. const duration = this._clip.duration;
  27835. const loop = this.loop;
  27836. let time = this.time + deltaTime;
  27837. let loopCount = this._loopCount;
  27838. const pingPong = ( loop === LoopPingPong );
  27839. if ( deltaTime === 0 ) {
  27840. if ( loopCount === - 1 ) return time;
  27841. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27842. }
  27843. if ( loop === LoopOnce ) {
  27844. if ( loopCount === - 1 ) {
  27845. // just started
  27846. this._loopCount = 0;
  27847. this._setEndings( true, true, false );
  27848. }
  27849. handle_stop: {
  27850. if ( time >= duration ) {
  27851. time = duration;
  27852. } else if ( time < 0 ) {
  27853. time = 0;
  27854. } else {
  27855. this.time = time;
  27856. break handle_stop;
  27857. }
  27858. if ( this.clampWhenFinished ) this.paused = true;
  27859. else this.enabled = false;
  27860. this.time = time;
  27861. this._mixer.dispatchEvent( {
  27862. type: 'finished', action: this,
  27863. direction: deltaTime < 0 ? - 1 : 1
  27864. } );
  27865. }
  27866. } else { // repetitive Repeat or PingPong
  27867. if ( loopCount === - 1 ) {
  27868. // just started
  27869. if ( deltaTime >= 0 ) {
  27870. loopCount = 0;
  27871. this._setEndings( true, this.repetitions === 0, pingPong );
  27872. } else {
  27873. // when looping in reverse direction, the initial
  27874. // transition through zero counts as a repetition,
  27875. // so leave loopCount at -1
  27876. this._setEndings( this.repetitions === 0, true, pingPong );
  27877. }
  27878. }
  27879. if ( time >= duration || time < 0 ) {
  27880. // wrap around
  27881. const loopDelta = Math.floor( time / duration ); // signed
  27882. time -= duration * loopDelta;
  27883. loopCount += Math.abs( loopDelta );
  27884. const pending = this.repetitions - loopCount;
  27885. if ( pending <= 0 ) {
  27886. // have to stop (switch state, clamp time, fire event)
  27887. if ( this.clampWhenFinished ) this.paused = true;
  27888. else this.enabled = false;
  27889. time = deltaTime > 0 ? duration : 0;
  27890. this.time = time;
  27891. this._mixer.dispatchEvent( {
  27892. type: 'finished', action: this,
  27893. direction: deltaTime > 0 ? 1 : - 1
  27894. } );
  27895. } else {
  27896. // keep running
  27897. if ( pending === 1 ) {
  27898. // entering the last round
  27899. const atStart = deltaTime < 0;
  27900. this._setEndings( atStart, ! atStart, pingPong );
  27901. } else {
  27902. this._setEndings( false, false, pingPong );
  27903. }
  27904. this._loopCount = loopCount;
  27905. this.time = time;
  27906. this._mixer.dispatchEvent( {
  27907. type: 'loop', action: this, loopDelta: loopDelta
  27908. } );
  27909. }
  27910. } else {
  27911. this.time = time;
  27912. }
  27913. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27914. // invert time for the "pong round"
  27915. return duration - time;
  27916. }
  27917. }
  27918. return time;
  27919. }
  27920. _setEndings( atStart, atEnd, pingPong ) {
  27921. const settings = this._interpolantSettings;
  27922. if ( pingPong ) {
  27923. settings.endingStart = ZeroSlopeEnding;
  27924. settings.endingEnd = ZeroSlopeEnding;
  27925. } else {
  27926. // assuming for LoopOnce atStart == atEnd == true
  27927. if ( atStart ) {
  27928. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27929. } else {
  27930. settings.endingStart = WrapAroundEnding;
  27931. }
  27932. if ( atEnd ) {
  27933. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27934. } else {
  27935. settings.endingEnd = WrapAroundEnding;
  27936. }
  27937. }
  27938. }
  27939. _scheduleFading( duration, weightNow, weightThen ) {
  27940. const mixer = this._mixer, now = mixer.time;
  27941. let interpolant = this._weightInterpolant;
  27942. if ( interpolant === null ) {
  27943. interpolant = mixer._lendControlInterpolant();
  27944. this._weightInterpolant = interpolant;
  27945. }
  27946. const times = interpolant.parameterPositions,
  27947. values = interpolant.sampleValues;
  27948. times[ 0 ] = now;
  27949. values[ 0 ] = weightNow;
  27950. times[ 1 ] = now + duration;
  27951. values[ 1 ] = weightThen;
  27952. return this;
  27953. }
  27954. }
  27955. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  27956. class AnimationMixer extends EventDispatcher {
  27957. constructor( root ) {
  27958. super();
  27959. this._root = root;
  27960. this._initMemoryManager();
  27961. this._accuIndex = 0;
  27962. this.time = 0;
  27963. this.timeScale = 1.0;
  27964. }
  27965. _bindAction( action, prototypeAction ) {
  27966. const root = action._localRoot || this._root,
  27967. tracks = action._clip.tracks,
  27968. nTracks = tracks.length,
  27969. bindings = action._propertyBindings,
  27970. interpolants = action._interpolants,
  27971. rootUuid = root.uuid,
  27972. bindingsByRoot = this._bindingsByRootAndName;
  27973. let bindingsByName = bindingsByRoot[ rootUuid ];
  27974. if ( bindingsByName === undefined ) {
  27975. bindingsByName = {};
  27976. bindingsByRoot[ rootUuid ] = bindingsByName;
  27977. }
  27978. for ( let i = 0; i !== nTracks; ++ i ) {
  27979. const track = tracks[ i ],
  27980. trackName = track.name;
  27981. let binding = bindingsByName[ trackName ];
  27982. if ( binding !== undefined ) {
  27983. ++ binding.referenceCount;
  27984. bindings[ i ] = binding;
  27985. } else {
  27986. binding = bindings[ i ];
  27987. if ( binding !== undefined ) {
  27988. // existing binding, make sure the cache knows
  27989. if ( binding._cacheIndex === null ) {
  27990. ++ binding.referenceCount;
  27991. this._addInactiveBinding( binding, rootUuid, trackName );
  27992. }
  27993. continue;
  27994. }
  27995. const path = prototypeAction && prototypeAction.
  27996. _propertyBindings[ i ].binding.parsedPath;
  27997. binding = new PropertyMixer(
  27998. PropertyBinding.create( root, trackName, path ),
  27999. track.ValueTypeName, track.getValueSize() );
  28000. ++ binding.referenceCount;
  28001. this._addInactiveBinding( binding, rootUuid, trackName );
  28002. bindings[ i ] = binding;
  28003. }
  28004. interpolants[ i ].resultBuffer = binding.buffer;
  28005. }
  28006. }
  28007. _activateAction( action ) {
  28008. if ( ! this._isActiveAction( action ) ) {
  28009. if ( action._cacheIndex === null ) {
  28010. // this action has been forgotten by the cache, but the user
  28011. // appears to be still using it -> rebind
  28012. const rootUuid = ( action._localRoot || this._root ).uuid,
  28013. clipUuid = action._clip.uuid,
  28014. actionsForClip = this._actionsByClip[ clipUuid ];
  28015. this._bindAction( action,
  28016. actionsForClip && actionsForClip.knownActions[ 0 ] );
  28017. this._addInactiveAction( action, clipUuid, rootUuid );
  28018. }
  28019. const bindings = action._propertyBindings;
  28020. // increment reference counts / sort out state
  28021. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28022. const binding = bindings[ i ];
  28023. if ( binding.useCount ++ === 0 ) {
  28024. this._lendBinding( binding );
  28025. binding.saveOriginalState();
  28026. }
  28027. }
  28028. this._lendAction( action );
  28029. }
  28030. }
  28031. _deactivateAction( action ) {
  28032. if ( this._isActiveAction( action ) ) {
  28033. const bindings = action._propertyBindings;
  28034. // decrement reference counts / sort out state
  28035. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28036. const binding = bindings[ i ];
  28037. if ( -- binding.useCount === 0 ) {
  28038. binding.restoreOriginalState();
  28039. this._takeBackBinding( binding );
  28040. }
  28041. }
  28042. this._takeBackAction( action );
  28043. }
  28044. }
  28045. // Memory manager
  28046. _initMemoryManager() {
  28047. this._actions = []; // 'nActiveActions' followed by inactive ones
  28048. this._nActiveActions = 0;
  28049. this._actionsByClip = {};
  28050. // inside:
  28051. // {
  28052. // knownActions: Array< AnimationAction > - used as prototypes
  28053. // actionByRoot: AnimationAction - lookup
  28054. // }
  28055. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  28056. this._nActiveBindings = 0;
  28057. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  28058. this._controlInterpolants = []; // same game as above
  28059. this._nActiveControlInterpolants = 0;
  28060. const scope = this;
  28061. this.stats = {
  28062. actions: {
  28063. get total() {
  28064. return scope._actions.length;
  28065. },
  28066. get inUse() {
  28067. return scope._nActiveActions;
  28068. }
  28069. },
  28070. bindings: {
  28071. get total() {
  28072. return scope._bindings.length;
  28073. },
  28074. get inUse() {
  28075. return scope._nActiveBindings;
  28076. }
  28077. },
  28078. controlInterpolants: {
  28079. get total() {
  28080. return scope._controlInterpolants.length;
  28081. },
  28082. get inUse() {
  28083. return scope._nActiveControlInterpolants;
  28084. }
  28085. }
  28086. };
  28087. }
  28088. // Memory management for AnimationAction objects
  28089. _isActiveAction( action ) {
  28090. const index = action._cacheIndex;
  28091. return index !== null && index < this._nActiveActions;
  28092. }
  28093. _addInactiveAction( action, clipUuid, rootUuid ) {
  28094. const actions = this._actions,
  28095. actionsByClip = this._actionsByClip;
  28096. let actionsForClip = actionsByClip[ clipUuid ];
  28097. if ( actionsForClip === undefined ) {
  28098. actionsForClip = {
  28099. knownActions: [ action ],
  28100. actionByRoot: {}
  28101. };
  28102. action._byClipCacheIndex = 0;
  28103. actionsByClip[ clipUuid ] = actionsForClip;
  28104. } else {
  28105. const knownActions = actionsForClip.knownActions;
  28106. action._byClipCacheIndex = knownActions.length;
  28107. knownActions.push( action );
  28108. }
  28109. action._cacheIndex = actions.length;
  28110. actions.push( action );
  28111. actionsForClip.actionByRoot[ rootUuid ] = action;
  28112. }
  28113. _removeInactiveAction( action ) {
  28114. const actions = this._actions,
  28115. lastInactiveAction = actions[ actions.length - 1 ],
  28116. cacheIndex = action._cacheIndex;
  28117. lastInactiveAction._cacheIndex = cacheIndex;
  28118. actions[ cacheIndex ] = lastInactiveAction;
  28119. actions.pop();
  28120. action._cacheIndex = null;
  28121. const clipUuid = action._clip.uuid,
  28122. actionsByClip = this._actionsByClip,
  28123. actionsForClip = actionsByClip[ clipUuid ],
  28124. knownActionsForClip = actionsForClip.knownActions,
  28125. lastKnownAction =
  28126. knownActionsForClip[ knownActionsForClip.length - 1 ],
  28127. byClipCacheIndex = action._byClipCacheIndex;
  28128. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  28129. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  28130. knownActionsForClip.pop();
  28131. action._byClipCacheIndex = null;
  28132. const actionByRoot = actionsForClip.actionByRoot,
  28133. rootUuid = ( action._localRoot || this._root ).uuid;
  28134. delete actionByRoot[ rootUuid ];
  28135. if ( knownActionsForClip.length === 0 ) {
  28136. delete actionsByClip[ clipUuid ];
  28137. }
  28138. this._removeInactiveBindingsForAction( action );
  28139. }
  28140. _removeInactiveBindingsForAction( action ) {
  28141. const bindings = action._propertyBindings;
  28142. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28143. const binding = bindings[ i ];
  28144. if ( -- binding.referenceCount === 0 ) {
  28145. this._removeInactiveBinding( binding );
  28146. }
  28147. }
  28148. }
  28149. _lendAction( action ) {
  28150. // [ active actions | inactive actions ]
  28151. // [ active actions >| inactive actions ]
  28152. // s a
  28153. // <-swap->
  28154. // a s
  28155. const actions = this._actions,
  28156. prevIndex = action._cacheIndex,
  28157. lastActiveIndex = this._nActiveActions ++,
  28158. firstInactiveAction = actions[ lastActiveIndex ];
  28159. action._cacheIndex = lastActiveIndex;
  28160. actions[ lastActiveIndex ] = action;
  28161. firstInactiveAction._cacheIndex = prevIndex;
  28162. actions[ prevIndex ] = firstInactiveAction;
  28163. }
  28164. _takeBackAction( action ) {
  28165. // [ active actions | inactive actions ]
  28166. // [ active actions |< inactive actions ]
  28167. // a s
  28168. // <-swap->
  28169. // s a
  28170. const actions = this._actions,
  28171. prevIndex = action._cacheIndex,
  28172. firstInactiveIndex = -- this._nActiveActions,
  28173. lastActiveAction = actions[ firstInactiveIndex ];
  28174. action._cacheIndex = firstInactiveIndex;
  28175. actions[ firstInactiveIndex ] = action;
  28176. lastActiveAction._cacheIndex = prevIndex;
  28177. actions[ prevIndex ] = lastActiveAction;
  28178. }
  28179. // Memory management for PropertyMixer objects
  28180. _addInactiveBinding( binding, rootUuid, trackName ) {
  28181. const bindingsByRoot = this._bindingsByRootAndName,
  28182. bindings = this._bindings;
  28183. let bindingByName = bindingsByRoot[ rootUuid ];
  28184. if ( bindingByName === undefined ) {
  28185. bindingByName = {};
  28186. bindingsByRoot[ rootUuid ] = bindingByName;
  28187. }
  28188. bindingByName[ trackName ] = binding;
  28189. binding._cacheIndex = bindings.length;
  28190. bindings.push( binding );
  28191. }
  28192. _removeInactiveBinding( binding ) {
  28193. const bindings = this._bindings,
  28194. propBinding = binding.binding,
  28195. rootUuid = propBinding.rootNode.uuid,
  28196. trackName = propBinding.path,
  28197. bindingsByRoot = this._bindingsByRootAndName,
  28198. bindingByName = bindingsByRoot[ rootUuid ],
  28199. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28200. cacheIndex = binding._cacheIndex;
  28201. lastInactiveBinding._cacheIndex = cacheIndex;
  28202. bindings[ cacheIndex ] = lastInactiveBinding;
  28203. bindings.pop();
  28204. delete bindingByName[ trackName ];
  28205. if ( Object.keys( bindingByName ).length === 0 ) {
  28206. delete bindingsByRoot[ rootUuid ];
  28207. }
  28208. }
  28209. _lendBinding( binding ) {
  28210. const bindings = this._bindings,
  28211. prevIndex = binding._cacheIndex,
  28212. lastActiveIndex = this._nActiveBindings ++,
  28213. firstInactiveBinding = bindings[ lastActiveIndex ];
  28214. binding._cacheIndex = lastActiveIndex;
  28215. bindings[ lastActiveIndex ] = binding;
  28216. firstInactiveBinding._cacheIndex = prevIndex;
  28217. bindings[ prevIndex ] = firstInactiveBinding;
  28218. }
  28219. _takeBackBinding( binding ) {
  28220. const bindings = this._bindings,
  28221. prevIndex = binding._cacheIndex,
  28222. firstInactiveIndex = -- this._nActiveBindings,
  28223. lastActiveBinding = bindings[ firstInactiveIndex ];
  28224. binding._cacheIndex = firstInactiveIndex;
  28225. bindings[ firstInactiveIndex ] = binding;
  28226. lastActiveBinding._cacheIndex = prevIndex;
  28227. bindings[ prevIndex ] = lastActiveBinding;
  28228. }
  28229. // Memory management of Interpolants for weight and time scale
  28230. _lendControlInterpolant() {
  28231. const interpolants = this._controlInterpolants,
  28232. lastActiveIndex = this._nActiveControlInterpolants ++;
  28233. let interpolant = interpolants[ lastActiveIndex ];
  28234. if ( interpolant === undefined ) {
  28235. interpolant = new LinearInterpolant(
  28236. new Float32Array( 2 ), new Float32Array( 2 ),
  28237. 1, _controlInterpolantsResultBuffer );
  28238. interpolant.__cacheIndex = lastActiveIndex;
  28239. interpolants[ lastActiveIndex ] = interpolant;
  28240. }
  28241. return interpolant;
  28242. }
  28243. _takeBackControlInterpolant( interpolant ) {
  28244. const interpolants = this._controlInterpolants,
  28245. prevIndex = interpolant.__cacheIndex,
  28246. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28247. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28248. interpolant.__cacheIndex = firstInactiveIndex;
  28249. interpolants[ firstInactiveIndex ] = interpolant;
  28250. lastActiveInterpolant.__cacheIndex = prevIndex;
  28251. interpolants[ prevIndex ] = lastActiveInterpolant;
  28252. }
  28253. // return an action for a clip optionally using a custom root target
  28254. // object (this method allocates a lot of dynamic memory in case a
  28255. // previously unknown clip/root combination is specified)
  28256. clipAction( clip, optionalRoot, blendMode ) {
  28257. const root = optionalRoot || this._root,
  28258. rootUuid = root.uuid;
  28259. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28260. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28261. const actionsForClip = this._actionsByClip[ clipUuid ];
  28262. let prototypeAction = null;
  28263. if ( blendMode === undefined ) {
  28264. if ( clipObject !== null ) {
  28265. blendMode = clipObject.blendMode;
  28266. } else {
  28267. blendMode = NormalAnimationBlendMode;
  28268. }
  28269. }
  28270. if ( actionsForClip !== undefined ) {
  28271. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28272. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28273. return existingAction;
  28274. }
  28275. // we know the clip, so we don't have to parse all
  28276. // the bindings again but can just copy
  28277. prototypeAction = actionsForClip.knownActions[ 0 ];
  28278. // also, take the clip from the prototype action
  28279. if ( clipObject === null )
  28280. clipObject = prototypeAction._clip;
  28281. }
  28282. // clip must be known when specified via string
  28283. if ( clipObject === null ) return null;
  28284. // allocate all resources required to run it
  28285. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28286. this._bindAction( newAction, prototypeAction );
  28287. // and make the action known to the memory manager
  28288. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28289. return newAction;
  28290. }
  28291. // get an existing action
  28292. existingAction( clip, optionalRoot ) {
  28293. const root = optionalRoot || this._root,
  28294. rootUuid = root.uuid,
  28295. clipObject = typeof clip === 'string' ?
  28296. AnimationClip.findByName( root, clip ) : clip,
  28297. clipUuid = clipObject ? clipObject.uuid : clip,
  28298. actionsForClip = this._actionsByClip[ clipUuid ];
  28299. if ( actionsForClip !== undefined ) {
  28300. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28301. }
  28302. return null;
  28303. }
  28304. // deactivates all previously scheduled actions
  28305. stopAllAction() {
  28306. const actions = this._actions,
  28307. nActions = this._nActiveActions;
  28308. for ( let i = nActions - 1; i >= 0; -- i ) {
  28309. actions[ i ].stop();
  28310. }
  28311. return this;
  28312. }
  28313. // advance the time and update apply the animation
  28314. update( deltaTime ) {
  28315. deltaTime *= this.timeScale;
  28316. const actions = this._actions,
  28317. nActions = this._nActiveActions,
  28318. time = this.time += deltaTime,
  28319. timeDirection = Math.sign( deltaTime ),
  28320. accuIndex = this._accuIndex ^= 1;
  28321. // run active actions
  28322. for ( let i = 0; i !== nActions; ++ i ) {
  28323. const action = actions[ i ];
  28324. action._update( time, deltaTime, timeDirection, accuIndex );
  28325. }
  28326. // update scene graph
  28327. const bindings = this._bindings,
  28328. nBindings = this._nActiveBindings;
  28329. for ( let i = 0; i !== nBindings; ++ i ) {
  28330. bindings[ i ].apply( accuIndex );
  28331. }
  28332. return this;
  28333. }
  28334. // Allows you to seek to a specific time in an animation.
  28335. setTime( timeInSeconds ) {
  28336. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28337. for ( let i = 0; i < this._actions.length; i ++ ) {
  28338. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28339. }
  28340. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28341. }
  28342. // return this mixer's root target object
  28343. getRoot() {
  28344. return this._root;
  28345. }
  28346. // free all resources specific to a particular clip
  28347. uncacheClip( clip ) {
  28348. const actions = this._actions,
  28349. clipUuid = clip.uuid,
  28350. actionsByClip = this._actionsByClip,
  28351. actionsForClip = actionsByClip[ clipUuid ];
  28352. if ( actionsForClip !== undefined ) {
  28353. // note: just calling _removeInactiveAction would mess up the
  28354. // iteration state and also require updating the state we can
  28355. // just throw away
  28356. const actionsToRemove = actionsForClip.knownActions;
  28357. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28358. const action = actionsToRemove[ i ];
  28359. this._deactivateAction( action );
  28360. const cacheIndex = action._cacheIndex,
  28361. lastInactiveAction = actions[ actions.length - 1 ];
  28362. action._cacheIndex = null;
  28363. action._byClipCacheIndex = null;
  28364. lastInactiveAction._cacheIndex = cacheIndex;
  28365. actions[ cacheIndex ] = lastInactiveAction;
  28366. actions.pop();
  28367. this._removeInactiveBindingsForAction( action );
  28368. }
  28369. delete actionsByClip[ clipUuid ];
  28370. }
  28371. }
  28372. // free all resources specific to a particular root target object
  28373. uncacheRoot( root ) {
  28374. const rootUuid = root.uuid,
  28375. actionsByClip = this._actionsByClip;
  28376. for ( const clipUuid in actionsByClip ) {
  28377. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28378. action = actionByRoot[ rootUuid ];
  28379. if ( action !== undefined ) {
  28380. this._deactivateAction( action );
  28381. this._removeInactiveAction( action );
  28382. }
  28383. }
  28384. const bindingsByRoot = this._bindingsByRootAndName,
  28385. bindingByName = bindingsByRoot[ rootUuid ];
  28386. if ( bindingByName !== undefined ) {
  28387. for ( const trackName in bindingByName ) {
  28388. const binding = bindingByName[ trackName ];
  28389. binding.restoreOriginalState();
  28390. this._removeInactiveBinding( binding );
  28391. }
  28392. }
  28393. }
  28394. // remove a targeted clip from the cache
  28395. uncacheAction( clip, optionalRoot ) {
  28396. const action = this.existingAction( clip, optionalRoot );
  28397. if ( action !== null ) {
  28398. this._deactivateAction( action );
  28399. this._removeInactiveAction( action );
  28400. }
  28401. }
  28402. }
  28403. class Uniform {
  28404. constructor( value ) {
  28405. this.value = value;
  28406. }
  28407. clone() {
  28408. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28409. }
  28410. }
  28411. let id = 0;
  28412. class UniformsGroup extends EventDispatcher {
  28413. constructor() {
  28414. super();
  28415. this.isUniformsGroup = true;
  28416. Object.defineProperty( this, 'id', { value: id ++ } );
  28417. this.name = '';
  28418. this.usage = StaticDrawUsage;
  28419. this.uniforms = [];
  28420. }
  28421. add( uniform ) {
  28422. this.uniforms.push( uniform );
  28423. return this;
  28424. }
  28425. remove( uniform ) {
  28426. const index = this.uniforms.indexOf( uniform );
  28427. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28428. return this;
  28429. }
  28430. setName( name ) {
  28431. this.name = name;
  28432. return this;
  28433. }
  28434. setUsage( value ) {
  28435. this.usage = value;
  28436. return this;
  28437. }
  28438. dispose() {
  28439. this.dispatchEvent( { type: 'dispose' } );
  28440. return this;
  28441. }
  28442. copy( source ) {
  28443. this.name = source.name;
  28444. this.usage = source.usage;
  28445. const uniformsSource = source.uniforms;
  28446. this.uniforms.length = 0;
  28447. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28448. this.uniforms.push( uniformsSource[ i ].clone() );
  28449. }
  28450. return this;
  28451. }
  28452. clone() {
  28453. return new this.constructor().copy( this );
  28454. }
  28455. }
  28456. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28457. constructor( array, stride, meshPerAttribute = 1 ) {
  28458. super( array, stride );
  28459. this.isInstancedInterleavedBuffer = true;
  28460. this.meshPerAttribute = meshPerAttribute;
  28461. }
  28462. copy( source ) {
  28463. super.copy( source );
  28464. this.meshPerAttribute = source.meshPerAttribute;
  28465. return this;
  28466. }
  28467. clone( data ) {
  28468. const ib = super.clone( data );
  28469. ib.meshPerAttribute = this.meshPerAttribute;
  28470. return ib;
  28471. }
  28472. toJSON( data ) {
  28473. const json = super.toJSON( data );
  28474. json.isInstancedInterleavedBuffer = true;
  28475. json.meshPerAttribute = this.meshPerAttribute;
  28476. return json;
  28477. }
  28478. }
  28479. class GLBufferAttribute {
  28480. constructor( buffer, type, itemSize, elementSize, count ) {
  28481. this.isGLBufferAttribute = true;
  28482. this.name = '';
  28483. this.buffer = buffer;
  28484. this.type = type;
  28485. this.itemSize = itemSize;
  28486. this.elementSize = elementSize;
  28487. this.count = count;
  28488. this.version = 0;
  28489. }
  28490. set needsUpdate( value ) {
  28491. if ( value === true ) this.version ++;
  28492. }
  28493. setBuffer( buffer ) {
  28494. this.buffer = buffer;
  28495. return this;
  28496. }
  28497. setType( type, elementSize ) {
  28498. this.type = type;
  28499. this.elementSize = elementSize;
  28500. return this;
  28501. }
  28502. setItemSize( itemSize ) {
  28503. this.itemSize = itemSize;
  28504. return this;
  28505. }
  28506. setCount( count ) {
  28507. this.count = count;
  28508. return this;
  28509. }
  28510. }
  28511. class Raycaster {
  28512. constructor( origin, direction, near = 0, far = Infinity ) {
  28513. this.ray = new Ray( origin, direction );
  28514. // direction is assumed to be normalized (for accurate distance calculations)
  28515. this.near = near;
  28516. this.far = far;
  28517. this.camera = null;
  28518. this.layers = new Layers();
  28519. this.params = {
  28520. Mesh: {},
  28521. Line: { threshold: 1 },
  28522. LOD: {},
  28523. Points: { threshold: 1 },
  28524. Sprite: {}
  28525. };
  28526. }
  28527. set( origin, direction ) {
  28528. // direction is assumed to be normalized (for accurate distance calculations)
  28529. this.ray.set( origin, direction );
  28530. }
  28531. setFromCamera( coords, camera ) {
  28532. if ( camera.isPerspectiveCamera ) {
  28533. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28534. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28535. this.camera = camera;
  28536. } else if ( camera.isOrthographicCamera ) {
  28537. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28538. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28539. this.camera = camera;
  28540. } else {
  28541. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28542. }
  28543. }
  28544. intersectObject( object, recursive = true, intersects = [] ) {
  28545. intersectObject( object, this, intersects, recursive );
  28546. intersects.sort( ascSort );
  28547. return intersects;
  28548. }
  28549. intersectObjects( objects, recursive = true, intersects = [] ) {
  28550. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28551. intersectObject( objects[ i ], this, intersects, recursive );
  28552. }
  28553. intersects.sort( ascSort );
  28554. return intersects;
  28555. }
  28556. }
  28557. function ascSort( a, b ) {
  28558. return a.distance - b.distance;
  28559. }
  28560. function intersectObject( object, raycaster, intersects, recursive ) {
  28561. if ( object.layers.test( raycaster.layers ) ) {
  28562. object.raycast( raycaster, intersects );
  28563. }
  28564. if ( recursive === true ) {
  28565. const children = object.children;
  28566. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28567. intersectObject( children[ i ], raycaster, intersects, true );
  28568. }
  28569. }
  28570. }
  28571. /**
  28572. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28573. *
  28574. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28575. * The azimuthal angle (theta) is measured from the positive z-axis.
  28576. */
  28577. class Spherical {
  28578. constructor( radius = 1, phi = 0, theta = 0 ) {
  28579. this.radius = radius;
  28580. this.phi = phi; // polar angle
  28581. this.theta = theta; // azimuthal angle
  28582. return this;
  28583. }
  28584. set( radius, phi, theta ) {
  28585. this.radius = radius;
  28586. this.phi = phi;
  28587. this.theta = theta;
  28588. return this;
  28589. }
  28590. copy( other ) {
  28591. this.radius = other.radius;
  28592. this.phi = other.phi;
  28593. this.theta = other.theta;
  28594. return this;
  28595. }
  28596. // restrict phi to be between EPS and PI-EPS
  28597. makeSafe() {
  28598. const EPS = 0.000001;
  28599. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28600. return this;
  28601. }
  28602. setFromVector3( v ) {
  28603. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28604. }
  28605. setFromCartesianCoords( x, y, z ) {
  28606. this.radius = Math.sqrt( x * x + y * y + z * z );
  28607. if ( this.radius === 0 ) {
  28608. this.theta = 0;
  28609. this.phi = 0;
  28610. } else {
  28611. this.theta = Math.atan2( x, z );
  28612. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28613. }
  28614. return this;
  28615. }
  28616. clone() {
  28617. return new this.constructor().copy( this );
  28618. }
  28619. }
  28620. /**
  28621. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28622. */
  28623. class Cylindrical {
  28624. constructor( radius = 1, theta = 0, y = 0 ) {
  28625. this.radius = radius; // distance from the origin to a point in the x-z plane
  28626. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28627. this.y = y; // height above the x-z plane
  28628. return this;
  28629. }
  28630. set( radius, theta, y ) {
  28631. this.radius = radius;
  28632. this.theta = theta;
  28633. this.y = y;
  28634. return this;
  28635. }
  28636. copy( other ) {
  28637. this.radius = other.radius;
  28638. this.theta = other.theta;
  28639. this.y = other.y;
  28640. return this;
  28641. }
  28642. setFromVector3( v ) {
  28643. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28644. }
  28645. setFromCartesianCoords( x, y, z ) {
  28646. this.radius = Math.sqrt( x * x + z * z );
  28647. this.theta = Math.atan2( x, z );
  28648. this.y = y;
  28649. return this;
  28650. }
  28651. clone() {
  28652. return new this.constructor().copy( this );
  28653. }
  28654. }
  28655. const _vector$4 = /*@__PURE__*/ new Vector2();
  28656. class Box2 {
  28657. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28658. this.isBox2 = true;
  28659. this.min = min;
  28660. this.max = max;
  28661. }
  28662. set( min, max ) {
  28663. this.min.copy( min );
  28664. this.max.copy( max );
  28665. return this;
  28666. }
  28667. setFromPoints( points ) {
  28668. this.makeEmpty();
  28669. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28670. this.expandByPoint( points[ i ] );
  28671. }
  28672. return this;
  28673. }
  28674. setFromCenterAndSize( center, size ) {
  28675. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28676. this.min.copy( center ).sub( halfSize );
  28677. this.max.copy( center ).add( halfSize );
  28678. return this;
  28679. }
  28680. clone() {
  28681. return new this.constructor().copy( this );
  28682. }
  28683. copy( box ) {
  28684. this.min.copy( box.min );
  28685. this.max.copy( box.max );
  28686. return this;
  28687. }
  28688. makeEmpty() {
  28689. this.min.x = this.min.y = + Infinity;
  28690. this.max.x = this.max.y = - Infinity;
  28691. return this;
  28692. }
  28693. isEmpty() {
  28694. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28695. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28696. }
  28697. getCenter( target ) {
  28698. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28699. }
  28700. getSize( target ) {
  28701. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28702. }
  28703. expandByPoint( point ) {
  28704. this.min.min( point );
  28705. this.max.max( point );
  28706. return this;
  28707. }
  28708. expandByVector( vector ) {
  28709. this.min.sub( vector );
  28710. this.max.add( vector );
  28711. return this;
  28712. }
  28713. expandByScalar( scalar ) {
  28714. this.min.addScalar( - scalar );
  28715. this.max.addScalar( scalar );
  28716. return this;
  28717. }
  28718. containsPoint( point ) {
  28719. return point.x < this.min.x || point.x > this.max.x ||
  28720. point.y < this.min.y || point.y > this.max.y ? false : true;
  28721. }
  28722. containsBox( box ) {
  28723. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28724. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28725. }
  28726. getParameter( point, target ) {
  28727. // This can potentially have a divide by zero if the box
  28728. // has a size dimension of 0.
  28729. return target.set(
  28730. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28731. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28732. );
  28733. }
  28734. intersectsBox( box ) {
  28735. // using 4 splitting planes to rule out intersections
  28736. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28737. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28738. }
  28739. clampPoint( point, target ) {
  28740. return target.copy( point ).clamp( this.min, this.max );
  28741. }
  28742. distanceToPoint( point ) {
  28743. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  28744. }
  28745. intersect( box ) {
  28746. this.min.max( box.min );
  28747. this.max.min( box.max );
  28748. if ( this.isEmpty() ) this.makeEmpty();
  28749. return this;
  28750. }
  28751. union( box ) {
  28752. this.min.min( box.min );
  28753. this.max.max( box.max );
  28754. return this;
  28755. }
  28756. translate( offset ) {
  28757. this.min.add( offset );
  28758. this.max.add( offset );
  28759. return this;
  28760. }
  28761. equals( box ) {
  28762. return box.min.equals( this.min ) && box.max.equals( this.max );
  28763. }
  28764. }
  28765. const _startP = /*@__PURE__*/ new Vector3();
  28766. const _startEnd = /*@__PURE__*/ new Vector3();
  28767. class Line3 {
  28768. constructor( start = new Vector3(), end = new Vector3() ) {
  28769. this.start = start;
  28770. this.end = end;
  28771. }
  28772. set( start, end ) {
  28773. this.start.copy( start );
  28774. this.end.copy( end );
  28775. return this;
  28776. }
  28777. copy( line ) {
  28778. this.start.copy( line.start );
  28779. this.end.copy( line.end );
  28780. return this;
  28781. }
  28782. getCenter( target ) {
  28783. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28784. }
  28785. delta( target ) {
  28786. return target.subVectors( this.end, this.start );
  28787. }
  28788. distanceSq() {
  28789. return this.start.distanceToSquared( this.end );
  28790. }
  28791. distance() {
  28792. return this.start.distanceTo( this.end );
  28793. }
  28794. at( t, target ) {
  28795. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28796. }
  28797. closestPointToPointParameter( point, clampToLine ) {
  28798. _startP.subVectors( point, this.start );
  28799. _startEnd.subVectors( this.end, this.start );
  28800. const startEnd2 = _startEnd.dot( _startEnd );
  28801. const startEnd_startP = _startEnd.dot( _startP );
  28802. let t = startEnd_startP / startEnd2;
  28803. if ( clampToLine ) {
  28804. t = clamp( t, 0, 1 );
  28805. }
  28806. return t;
  28807. }
  28808. closestPointToPoint( point, clampToLine, target ) {
  28809. const t = this.closestPointToPointParameter( point, clampToLine );
  28810. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28811. }
  28812. applyMatrix4( matrix ) {
  28813. this.start.applyMatrix4( matrix );
  28814. this.end.applyMatrix4( matrix );
  28815. return this;
  28816. }
  28817. equals( line ) {
  28818. return line.start.equals( this.start ) && line.end.equals( this.end );
  28819. }
  28820. clone() {
  28821. return new this.constructor().copy( this );
  28822. }
  28823. }
  28824. const _vector$3 = /*@__PURE__*/ new Vector3();
  28825. class SpotLightHelper extends Object3D {
  28826. constructor( light, color ) {
  28827. super();
  28828. this.light = light;
  28829. this.matrix = light.matrixWorld;
  28830. this.matrixAutoUpdate = false;
  28831. this.color = color;
  28832. this.type = 'SpotLightHelper';
  28833. const geometry = new BufferGeometry();
  28834. const positions = [
  28835. 0, 0, 0, 0, 0, 1,
  28836. 0, 0, 0, 1, 0, 1,
  28837. 0, 0, 0, - 1, 0, 1,
  28838. 0, 0, 0, 0, 1, 1,
  28839. 0, 0, 0, 0, - 1, 1
  28840. ];
  28841. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28842. const p1 = ( i / l ) * Math.PI * 2;
  28843. const p2 = ( j / l ) * Math.PI * 2;
  28844. positions.push(
  28845. Math.cos( p1 ), Math.sin( p1 ), 1,
  28846. Math.cos( p2 ), Math.sin( p2 ), 1
  28847. );
  28848. }
  28849. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28850. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28851. this.cone = new LineSegments( geometry, material );
  28852. this.add( this.cone );
  28853. this.update();
  28854. }
  28855. dispose() {
  28856. this.cone.geometry.dispose();
  28857. this.cone.material.dispose();
  28858. }
  28859. update() {
  28860. this.light.updateWorldMatrix( true, false );
  28861. this.light.target.updateWorldMatrix( true, false );
  28862. const coneLength = this.light.distance ? this.light.distance : 1000;
  28863. const coneWidth = coneLength * Math.tan( this.light.angle );
  28864. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28865. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28866. this.cone.lookAt( _vector$3 );
  28867. if ( this.color !== undefined ) {
  28868. this.cone.material.color.set( this.color );
  28869. } else {
  28870. this.cone.material.color.copy( this.light.color );
  28871. }
  28872. }
  28873. }
  28874. const _vector$2 = /*@__PURE__*/ new Vector3();
  28875. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28876. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28877. class SkeletonHelper extends LineSegments {
  28878. constructor( object ) {
  28879. const bones = getBoneList( object );
  28880. const geometry = new BufferGeometry();
  28881. const vertices = [];
  28882. const colors = [];
  28883. const color1 = new Color( 0, 0, 1 );
  28884. const color2 = new Color( 0, 1, 0 );
  28885. for ( let i = 0; i < bones.length; i ++ ) {
  28886. const bone = bones[ i ];
  28887. if ( bone.parent && bone.parent.isBone ) {
  28888. vertices.push( 0, 0, 0 );
  28889. vertices.push( 0, 0, 0 );
  28890. colors.push( color1.r, color1.g, color1.b );
  28891. colors.push( color2.r, color2.g, color2.b );
  28892. }
  28893. }
  28894. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28895. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28896. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28897. super( geometry, material );
  28898. this.isSkeletonHelper = true;
  28899. this.type = 'SkeletonHelper';
  28900. this.root = object;
  28901. this.bones = bones;
  28902. this.matrix = object.matrixWorld;
  28903. this.matrixAutoUpdate = false;
  28904. }
  28905. updateMatrixWorld( force ) {
  28906. const bones = this.bones;
  28907. const geometry = this.geometry;
  28908. const position = geometry.getAttribute( 'position' );
  28909. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28910. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28911. const bone = bones[ i ];
  28912. if ( bone.parent && bone.parent.isBone ) {
  28913. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28914. _vector$2.setFromMatrixPosition( _boneMatrix );
  28915. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28916. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28917. _vector$2.setFromMatrixPosition( _boneMatrix );
  28918. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28919. j += 2;
  28920. }
  28921. }
  28922. geometry.getAttribute( 'position' ).needsUpdate = true;
  28923. super.updateMatrixWorld( force );
  28924. }
  28925. dispose() {
  28926. this.geometry.dispose();
  28927. this.material.dispose();
  28928. }
  28929. }
  28930. function getBoneList( object ) {
  28931. const boneList = [];
  28932. if ( object.isBone === true ) {
  28933. boneList.push( object );
  28934. }
  28935. for ( let i = 0; i < object.children.length; i ++ ) {
  28936. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28937. }
  28938. return boneList;
  28939. }
  28940. class PointLightHelper extends Mesh {
  28941. constructor( light, sphereSize, color ) {
  28942. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28943. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28944. super( geometry, material );
  28945. this.light = light;
  28946. this.color = color;
  28947. this.type = 'PointLightHelper';
  28948. this.matrix = this.light.matrixWorld;
  28949. this.matrixAutoUpdate = false;
  28950. this.update();
  28951. /*
  28952. // TODO: delete this comment?
  28953. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28954. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28955. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28956. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28957. const d = light.distance;
  28958. if ( d === 0.0 ) {
  28959. this.lightDistance.visible = false;
  28960. } else {
  28961. this.lightDistance.scale.set( d, d, d );
  28962. }
  28963. this.add( this.lightDistance );
  28964. */
  28965. }
  28966. dispose() {
  28967. this.geometry.dispose();
  28968. this.material.dispose();
  28969. }
  28970. update() {
  28971. this.light.updateWorldMatrix( true, false );
  28972. if ( this.color !== undefined ) {
  28973. this.material.color.set( this.color );
  28974. } else {
  28975. this.material.color.copy( this.light.color );
  28976. }
  28977. /*
  28978. const d = this.light.distance;
  28979. if ( d === 0.0 ) {
  28980. this.lightDistance.visible = false;
  28981. } else {
  28982. this.lightDistance.visible = true;
  28983. this.lightDistance.scale.set( d, d, d );
  28984. }
  28985. */
  28986. }
  28987. }
  28988. const _vector$1 = /*@__PURE__*/ new Vector3();
  28989. const _color1 = /*@__PURE__*/ new Color();
  28990. const _color2 = /*@__PURE__*/ new Color();
  28991. class HemisphereLightHelper extends Object3D {
  28992. constructor( light, size, color ) {
  28993. super();
  28994. this.light = light;
  28995. this.matrix = light.matrixWorld;
  28996. this.matrixAutoUpdate = false;
  28997. this.color = color;
  28998. this.type = 'HemisphereLightHelper';
  28999. const geometry = new OctahedronGeometry( size );
  29000. geometry.rotateY( Math.PI * 0.5 );
  29001. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29002. if ( this.color === undefined ) this.material.vertexColors = true;
  29003. const position = geometry.getAttribute( 'position' );
  29004. const colors = new Float32Array( position.count * 3 );
  29005. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  29006. this.add( new Mesh( geometry, this.material ) );
  29007. this.update();
  29008. }
  29009. dispose() {
  29010. this.children[ 0 ].geometry.dispose();
  29011. this.children[ 0 ].material.dispose();
  29012. }
  29013. update() {
  29014. const mesh = this.children[ 0 ];
  29015. if ( this.color !== undefined ) {
  29016. this.material.color.set( this.color );
  29017. } else {
  29018. const colors = mesh.geometry.getAttribute( 'color' );
  29019. _color1.copy( this.light.color );
  29020. _color2.copy( this.light.groundColor );
  29021. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  29022. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  29023. colors.setXYZ( i, color.r, color.g, color.b );
  29024. }
  29025. colors.needsUpdate = true;
  29026. }
  29027. this.light.updateWorldMatrix( true, false );
  29028. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  29029. }
  29030. }
  29031. class GridHelper extends LineSegments {
  29032. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  29033. color1 = new Color( color1 );
  29034. color2 = new Color( color2 );
  29035. const center = divisions / 2;
  29036. const step = size / divisions;
  29037. const halfSize = size / 2;
  29038. const vertices = [], colors = [];
  29039. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  29040. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  29041. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  29042. const color = i === center ? color1 : color2;
  29043. color.toArray( colors, j ); j += 3;
  29044. color.toArray( colors, j ); j += 3;
  29045. color.toArray( colors, j ); j += 3;
  29046. color.toArray( colors, j ); j += 3;
  29047. }
  29048. const geometry = new BufferGeometry();
  29049. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29050. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29051. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29052. super( geometry, material );
  29053. this.type = 'GridHelper';
  29054. }
  29055. dispose() {
  29056. this.geometry.dispose();
  29057. this.material.dispose();
  29058. }
  29059. }
  29060. class PolarGridHelper extends LineSegments {
  29061. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  29062. color1 = new Color( color1 );
  29063. color2 = new Color( color2 );
  29064. const vertices = [];
  29065. const colors = [];
  29066. // create the sectors
  29067. if ( sectors > 1 ) {
  29068. for ( let i = 0; i < sectors; i ++ ) {
  29069. const v = ( i / sectors ) * ( Math.PI * 2 );
  29070. const x = Math.sin( v ) * radius;
  29071. const z = Math.cos( v ) * radius;
  29072. vertices.push( 0, 0, 0 );
  29073. vertices.push( x, 0, z );
  29074. const color = ( i & 1 ) ? color1 : color2;
  29075. colors.push( color.r, color.g, color.b );
  29076. colors.push( color.r, color.g, color.b );
  29077. }
  29078. }
  29079. // create the rings
  29080. for ( let i = 0; i < rings; i ++ ) {
  29081. const color = ( i & 1 ) ? color1 : color2;
  29082. const r = radius - ( radius / rings * i );
  29083. for ( let j = 0; j < divisions; j ++ ) {
  29084. // first vertex
  29085. let v = ( j / divisions ) * ( Math.PI * 2 );
  29086. let x = Math.sin( v ) * r;
  29087. let z = Math.cos( v ) * r;
  29088. vertices.push( x, 0, z );
  29089. colors.push( color.r, color.g, color.b );
  29090. // second vertex
  29091. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  29092. x = Math.sin( v ) * r;
  29093. z = Math.cos( v ) * r;
  29094. vertices.push( x, 0, z );
  29095. colors.push( color.r, color.g, color.b );
  29096. }
  29097. }
  29098. const geometry = new BufferGeometry();
  29099. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29100. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29101. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29102. super( geometry, material );
  29103. this.type = 'PolarGridHelper';
  29104. }
  29105. dispose() {
  29106. this.geometry.dispose();
  29107. this.material.dispose();
  29108. }
  29109. }
  29110. const _v1 = /*@__PURE__*/ new Vector3();
  29111. const _v2 = /*@__PURE__*/ new Vector3();
  29112. const _v3 = /*@__PURE__*/ new Vector3();
  29113. class DirectionalLightHelper extends Object3D {
  29114. constructor( light, size, color ) {
  29115. super();
  29116. this.light = light;
  29117. this.matrix = light.matrixWorld;
  29118. this.matrixAutoUpdate = false;
  29119. this.color = color;
  29120. this.type = 'DirectionalLightHelper';
  29121. if ( size === undefined ) size = 1;
  29122. let geometry = new BufferGeometry();
  29123. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29124. - size, size, 0,
  29125. size, size, 0,
  29126. size, - size, 0,
  29127. - size, - size, 0,
  29128. - size, size, 0
  29129. ], 3 ) );
  29130. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29131. this.lightPlane = new Line( geometry, material );
  29132. this.add( this.lightPlane );
  29133. geometry = new BufferGeometry();
  29134. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29135. this.targetLine = new Line( geometry, material );
  29136. this.add( this.targetLine );
  29137. this.update();
  29138. }
  29139. dispose() {
  29140. this.lightPlane.geometry.dispose();
  29141. this.lightPlane.material.dispose();
  29142. this.targetLine.geometry.dispose();
  29143. this.targetLine.material.dispose();
  29144. }
  29145. update() {
  29146. this.light.updateWorldMatrix( true, false );
  29147. this.light.target.updateWorldMatrix( true, false );
  29148. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29149. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29150. _v3.subVectors( _v2, _v1 );
  29151. this.lightPlane.lookAt( _v2 );
  29152. if ( this.color !== undefined ) {
  29153. this.lightPlane.material.color.set( this.color );
  29154. this.targetLine.material.color.set( this.color );
  29155. } else {
  29156. this.lightPlane.material.color.copy( this.light.color );
  29157. this.targetLine.material.color.copy( this.light.color );
  29158. }
  29159. this.targetLine.lookAt( _v2 );
  29160. this.targetLine.scale.z = _v3.length();
  29161. }
  29162. }
  29163. const _vector = /*@__PURE__*/ new Vector3();
  29164. const _camera = /*@__PURE__*/ new Camera();
  29165. /**
  29166. * - shows frustum, line of sight and up of the camera
  29167. * - suitable for fast updates
  29168. * - based on frustum visualization in lightgl.js shadowmap example
  29169. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  29170. */
  29171. class CameraHelper extends LineSegments {
  29172. constructor( camera ) {
  29173. const geometry = new BufferGeometry();
  29174. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29175. const vertices = [];
  29176. const colors = [];
  29177. const pointMap = {};
  29178. // near
  29179. addLine( 'n1', 'n2' );
  29180. addLine( 'n2', 'n4' );
  29181. addLine( 'n4', 'n3' );
  29182. addLine( 'n3', 'n1' );
  29183. // far
  29184. addLine( 'f1', 'f2' );
  29185. addLine( 'f2', 'f4' );
  29186. addLine( 'f4', 'f3' );
  29187. addLine( 'f3', 'f1' );
  29188. // sides
  29189. addLine( 'n1', 'f1' );
  29190. addLine( 'n2', 'f2' );
  29191. addLine( 'n3', 'f3' );
  29192. addLine( 'n4', 'f4' );
  29193. // cone
  29194. addLine( 'p', 'n1' );
  29195. addLine( 'p', 'n2' );
  29196. addLine( 'p', 'n3' );
  29197. addLine( 'p', 'n4' );
  29198. // up
  29199. addLine( 'u1', 'u2' );
  29200. addLine( 'u2', 'u3' );
  29201. addLine( 'u3', 'u1' );
  29202. // target
  29203. addLine( 'c', 't' );
  29204. addLine( 'p', 'c' );
  29205. // cross
  29206. addLine( 'cn1', 'cn2' );
  29207. addLine( 'cn3', 'cn4' );
  29208. addLine( 'cf1', 'cf2' );
  29209. addLine( 'cf3', 'cf4' );
  29210. function addLine( a, b ) {
  29211. addPoint( a );
  29212. addPoint( b );
  29213. }
  29214. function addPoint( id ) {
  29215. vertices.push( 0, 0, 0 );
  29216. colors.push( 0, 0, 0 );
  29217. if ( pointMap[ id ] === undefined ) {
  29218. pointMap[ id ] = [];
  29219. }
  29220. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29221. }
  29222. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29223. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29224. super( geometry, material );
  29225. this.type = 'CameraHelper';
  29226. this.camera = camera;
  29227. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29228. this.matrix = camera.matrixWorld;
  29229. this.matrixAutoUpdate = false;
  29230. this.pointMap = pointMap;
  29231. this.update();
  29232. // colors
  29233. const colorFrustum = new Color( 0xffaa00 );
  29234. const colorCone = new Color( 0xff0000 );
  29235. const colorUp = new Color( 0x00aaff );
  29236. const colorTarget = new Color( 0xffffff );
  29237. const colorCross = new Color( 0x333333 );
  29238. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  29239. }
  29240. setColors( frustum, cone, up, target, cross ) {
  29241. const geometry = this.geometry;
  29242. const colorAttribute = geometry.getAttribute( 'color' );
  29243. // near
  29244. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  29245. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  29246. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  29247. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  29248. // far
  29249. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  29250. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  29251. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  29252. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  29253. // sides
  29254. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  29255. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  29256. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  29257. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  29258. // cone
  29259. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  29260. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  29261. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  29262. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  29263. // up
  29264. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  29265. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  29266. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  29267. // target
  29268. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  29269. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  29270. // cross
  29271. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  29272. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  29273. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  29274. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  29275. colorAttribute.needsUpdate = true;
  29276. }
  29277. update() {
  29278. const geometry = this.geometry;
  29279. const pointMap = this.pointMap;
  29280. const w = 1, h = 1;
  29281. // we need just camera projection matrix inverse
  29282. // world matrix must be identity
  29283. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29284. // center / target
  29285. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29286. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29287. // near
  29288. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29289. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29290. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29291. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29292. // far
  29293. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29294. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29295. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29296. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29297. // up
  29298. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29299. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29300. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29301. // cross
  29302. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29303. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29304. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29305. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29306. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29307. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29308. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29309. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29310. geometry.getAttribute( 'position' ).needsUpdate = true;
  29311. }
  29312. dispose() {
  29313. this.geometry.dispose();
  29314. this.material.dispose();
  29315. }
  29316. }
  29317. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29318. _vector.set( x, y, z ).unproject( camera );
  29319. const points = pointMap[ point ];
  29320. if ( points !== undefined ) {
  29321. const position = geometry.getAttribute( 'position' );
  29322. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29323. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29324. }
  29325. }
  29326. }
  29327. const _box = /*@__PURE__*/ new Box3();
  29328. class BoxHelper extends LineSegments {
  29329. constructor( object, color = 0xffff00 ) {
  29330. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  29331. const positions = new Float32Array( 8 * 3 );
  29332. const geometry = new BufferGeometry();
  29333. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29334. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29335. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29336. this.object = object;
  29337. this.type = 'BoxHelper';
  29338. this.matrixAutoUpdate = false;
  29339. this.update();
  29340. }
  29341. update( object ) {
  29342. if ( object !== undefined ) {
  29343. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29344. }
  29345. if ( this.object !== undefined ) {
  29346. _box.setFromObject( this.object );
  29347. }
  29348. if ( _box.isEmpty() ) return;
  29349. const min = _box.min;
  29350. const max = _box.max;
  29351. /*
  29352. 5____4
  29353. 1/___0/|
  29354. | 6__|_7
  29355. 2/___3/
  29356. 0: max.x, max.y, max.z
  29357. 1: min.x, max.y, max.z
  29358. 2: min.x, min.y, max.z
  29359. 3: max.x, min.y, max.z
  29360. 4: max.x, max.y, min.z
  29361. 5: min.x, max.y, min.z
  29362. 6: min.x, min.y, min.z
  29363. 7: max.x, min.y, min.z
  29364. */
  29365. const position = this.geometry.attributes.position;
  29366. const array = position.array;
  29367. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29368. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29369. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29370. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29371. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29372. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29373. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29374. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29375. position.needsUpdate = true;
  29376. this.geometry.computeBoundingSphere();
  29377. }
  29378. setFromObject( object ) {
  29379. this.object = object;
  29380. this.update();
  29381. return this;
  29382. }
  29383. copy( source, recursive ) {
  29384. super.copy( source, recursive );
  29385. this.object = source.object;
  29386. return this;
  29387. }
  29388. dispose() {
  29389. this.geometry.dispose();
  29390. this.material.dispose();
  29391. }
  29392. }
  29393. class Box3Helper extends LineSegments {
  29394. constructor( box, color = 0xffff00 ) {
  29395. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  29396. const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  29397. const geometry = new BufferGeometry();
  29398. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29399. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29400. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29401. this.box = box;
  29402. this.type = 'Box3Helper';
  29403. this.geometry.computeBoundingSphere();
  29404. }
  29405. updateMatrixWorld( force ) {
  29406. const box = this.box;
  29407. if ( box.isEmpty() ) return;
  29408. box.getCenter( this.position );
  29409. box.getSize( this.scale );
  29410. this.scale.multiplyScalar( 0.5 );
  29411. super.updateMatrixWorld( force );
  29412. }
  29413. dispose() {
  29414. this.geometry.dispose();
  29415. this.material.dispose();
  29416. }
  29417. }
  29418. class PlaneHelper extends Line {
  29419. constructor( plane, size = 1, hex = 0xffff00 ) {
  29420. const color = hex;
  29421. const positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ];
  29422. const geometry = new BufferGeometry();
  29423. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29424. geometry.computeBoundingSphere();
  29425. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29426. this.type = 'PlaneHelper';
  29427. this.plane = plane;
  29428. this.size = size;
  29429. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29430. const geometry2 = new BufferGeometry();
  29431. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29432. geometry2.computeBoundingSphere();
  29433. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29434. }
  29435. updateMatrixWorld( force ) {
  29436. this.position.set( 0, 0, 0 );
  29437. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29438. this.lookAt( this.plane.normal );
  29439. this.translateZ( - this.plane.constant );
  29440. super.updateMatrixWorld( force );
  29441. }
  29442. dispose() {
  29443. this.geometry.dispose();
  29444. this.material.dispose();
  29445. this.children[ 0 ].geometry.dispose();
  29446. this.children[ 0 ].material.dispose();
  29447. }
  29448. }
  29449. const _axis = /*@__PURE__*/ new Vector3();
  29450. let _lineGeometry, _coneGeometry;
  29451. class ArrowHelper extends Object3D {
  29452. // dir is assumed to be normalized
  29453. constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29454. super();
  29455. this.type = 'ArrowHelper';
  29456. if ( _lineGeometry === undefined ) {
  29457. _lineGeometry = new BufferGeometry();
  29458. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29459. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29460. _coneGeometry.translate( 0, - 0.5, 0 );
  29461. }
  29462. this.position.copy( origin );
  29463. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29464. this.line.matrixAutoUpdate = false;
  29465. this.add( this.line );
  29466. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29467. this.cone.matrixAutoUpdate = false;
  29468. this.add( this.cone );
  29469. this.setDirection( dir );
  29470. this.setLength( length, headLength, headWidth );
  29471. }
  29472. setDirection( dir ) {
  29473. // dir is assumed to be normalized
  29474. if ( dir.y > 0.99999 ) {
  29475. this.quaternion.set( 0, 0, 0, 1 );
  29476. } else if ( dir.y < - 0.99999 ) {
  29477. this.quaternion.set( 1, 0, 0, 0 );
  29478. } else {
  29479. _axis.set( dir.z, 0, - dir.x ).normalize();
  29480. const radians = Math.acos( dir.y );
  29481. this.quaternion.setFromAxisAngle( _axis, radians );
  29482. }
  29483. }
  29484. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29485. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29486. this.line.updateMatrix();
  29487. this.cone.scale.set( headWidth, headLength, headWidth );
  29488. this.cone.position.y = length;
  29489. this.cone.updateMatrix();
  29490. }
  29491. setColor( color ) {
  29492. this.line.material.color.set( color );
  29493. this.cone.material.color.set( color );
  29494. }
  29495. copy( source ) {
  29496. super.copy( source, false );
  29497. this.line.copy( source.line );
  29498. this.cone.copy( source.cone );
  29499. return this;
  29500. }
  29501. dispose() {
  29502. this.line.geometry.dispose();
  29503. this.line.material.dispose();
  29504. this.cone.geometry.dispose();
  29505. this.cone.material.dispose();
  29506. }
  29507. }
  29508. class AxesHelper extends LineSegments {
  29509. constructor( size = 1 ) {
  29510. const vertices = [
  29511. 0, 0, 0, size, 0, 0,
  29512. 0, 0, 0, 0, size, 0,
  29513. 0, 0, 0, 0, 0, size
  29514. ];
  29515. const colors = [
  29516. 1, 0, 0, 1, 0.6, 0,
  29517. 0, 1, 0, 0.6, 1, 0,
  29518. 0, 0, 1, 0, 0.6, 1
  29519. ];
  29520. const geometry = new BufferGeometry();
  29521. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29522. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29523. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29524. super( geometry, material );
  29525. this.type = 'AxesHelper';
  29526. }
  29527. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29528. const color = new Color();
  29529. const array = this.geometry.attributes.color.array;
  29530. color.set( xAxisColor );
  29531. color.toArray( array, 0 );
  29532. color.toArray( array, 3 );
  29533. color.set( yAxisColor );
  29534. color.toArray( array, 6 );
  29535. color.toArray( array, 9 );
  29536. color.set( zAxisColor );
  29537. color.toArray( array, 12 );
  29538. color.toArray( array, 15 );
  29539. this.geometry.attributes.color.needsUpdate = true;
  29540. return this;
  29541. }
  29542. dispose() {
  29543. this.geometry.dispose();
  29544. this.material.dispose();
  29545. }
  29546. }
  29547. class ShapePath {
  29548. constructor() {
  29549. this.type = 'ShapePath';
  29550. this.color = new Color();
  29551. this.subPaths = [];
  29552. this.currentPath = null;
  29553. }
  29554. moveTo( x, y ) {
  29555. this.currentPath = new Path();
  29556. this.subPaths.push( this.currentPath );
  29557. this.currentPath.moveTo( x, y );
  29558. return this;
  29559. }
  29560. lineTo( x, y ) {
  29561. this.currentPath.lineTo( x, y );
  29562. return this;
  29563. }
  29564. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29565. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29566. return this;
  29567. }
  29568. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29569. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29570. return this;
  29571. }
  29572. splineThru( pts ) {
  29573. this.currentPath.splineThru( pts );
  29574. return this;
  29575. }
  29576. toShapes( isCCW ) {
  29577. function toShapesNoHoles( inSubpaths ) {
  29578. const shapes = [];
  29579. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29580. const tmpPath = inSubpaths[ i ];
  29581. const tmpShape = new Shape();
  29582. tmpShape.curves = tmpPath.curves;
  29583. shapes.push( tmpShape );
  29584. }
  29585. return shapes;
  29586. }
  29587. function isPointInsidePolygon( inPt, inPolygon ) {
  29588. const polyLen = inPolygon.length;
  29589. // inPt on polygon contour => immediate success or
  29590. // toggling of inside/outside at every single! intersection point of an edge
  29591. // with the horizontal line through inPt, left of inPt
  29592. // not counting lowerY endpoints of edges and whole edges on that line
  29593. let inside = false;
  29594. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29595. let edgeLowPt = inPolygon[ p ];
  29596. let edgeHighPt = inPolygon[ q ];
  29597. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29598. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29599. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29600. // not parallel
  29601. if ( edgeDy < 0 ) {
  29602. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29603. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29604. }
  29605. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29606. if ( inPt.y === edgeLowPt.y ) {
  29607. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29608. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29609. } else {
  29610. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29611. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29612. if ( perpEdge < 0 ) continue;
  29613. inside = ! inside; // true intersection left of inPt
  29614. }
  29615. } else {
  29616. // parallel or collinear
  29617. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29618. // edge lies on the same horizontal line as inPt
  29619. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29620. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29621. // continue;
  29622. }
  29623. }
  29624. return inside;
  29625. }
  29626. const isClockWise = ShapeUtils.isClockWise;
  29627. const subPaths = this.subPaths;
  29628. if ( subPaths.length === 0 ) return [];
  29629. let solid, tmpPath, tmpShape;
  29630. const shapes = [];
  29631. if ( subPaths.length === 1 ) {
  29632. tmpPath = subPaths[ 0 ];
  29633. tmpShape = new Shape();
  29634. tmpShape.curves = tmpPath.curves;
  29635. shapes.push( tmpShape );
  29636. return shapes;
  29637. }
  29638. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29639. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29640. // console.log("Holes first", holesFirst);
  29641. const betterShapeHoles = [];
  29642. const newShapes = [];
  29643. let newShapeHoles = [];
  29644. let mainIdx = 0;
  29645. let tmpPoints;
  29646. newShapes[ mainIdx ] = undefined;
  29647. newShapeHoles[ mainIdx ] = [];
  29648. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29649. tmpPath = subPaths[ i ];
  29650. tmpPoints = tmpPath.getPoints();
  29651. solid = isClockWise( tmpPoints );
  29652. solid = isCCW ? ! solid : solid;
  29653. if ( solid ) {
  29654. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29655. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29656. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29657. if ( holesFirst ) mainIdx ++;
  29658. newShapeHoles[ mainIdx ] = [];
  29659. //console.log('cw', i);
  29660. } else {
  29661. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29662. //console.log('ccw', i);
  29663. }
  29664. }
  29665. // only Holes? -> probably all Shapes with wrong orientation
  29666. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29667. if ( newShapes.length > 1 ) {
  29668. let ambiguous = false;
  29669. let toChange = 0;
  29670. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29671. betterShapeHoles[ sIdx ] = [];
  29672. }
  29673. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29674. const sho = newShapeHoles[ sIdx ];
  29675. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29676. const ho = sho[ hIdx ];
  29677. let hole_unassigned = true;
  29678. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29679. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29680. if ( sIdx !== s2Idx ) toChange ++;
  29681. if ( hole_unassigned ) {
  29682. hole_unassigned = false;
  29683. betterShapeHoles[ s2Idx ].push( ho );
  29684. } else {
  29685. ambiguous = true;
  29686. }
  29687. }
  29688. }
  29689. if ( hole_unassigned ) {
  29690. betterShapeHoles[ sIdx ].push( ho );
  29691. }
  29692. }
  29693. }
  29694. if ( toChange > 0 && ambiguous === false ) {
  29695. newShapeHoles = betterShapeHoles;
  29696. }
  29697. }
  29698. let tmpHoles;
  29699. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29700. tmpShape = newShapes[ i ].s;
  29701. shapes.push( tmpShape );
  29702. tmpHoles = newShapeHoles[ i ];
  29703. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29704. tmpShape.holes.push( tmpHoles[ j ].h );
  29705. }
  29706. }
  29707. //console.log("shape", shapes);
  29708. return shapes;
  29709. }
  29710. }
  29711. // r144
  29712. class BoxBufferGeometry extends BoxGeometry {
  29713. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29714. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29715. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29716. }
  29717. }
  29718. // r144
  29719. class CapsuleBufferGeometry extends CapsuleGeometry {
  29720. constructor( radius, length, capSegments, radialSegments ) {
  29721. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29722. super( radius, length, capSegments, radialSegments );
  29723. }
  29724. }
  29725. // r144
  29726. class CircleBufferGeometry extends CircleGeometry {
  29727. constructor( radius, segments, thetaStart, thetaLength ) {
  29728. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29729. super( radius, segments, thetaStart, thetaLength );
  29730. }
  29731. }
  29732. // r144
  29733. class ConeBufferGeometry extends ConeGeometry {
  29734. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29735. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29736. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29737. }
  29738. }
  29739. // r144
  29740. class CylinderBufferGeometry extends CylinderGeometry {
  29741. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29742. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29743. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29744. }
  29745. }
  29746. // r144
  29747. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  29748. constructor( radius, detail ) {
  29749. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29750. super( radius, detail );
  29751. }
  29752. }
  29753. // r144
  29754. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  29755. constructor( shapes, options ) {
  29756. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29757. super( shapes, options );
  29758. }
  29759. }
  29760. // r144
  29761. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  29762. constructor( radius, detail ) {
  29763. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29764. super( radius, detail );
  29765. }
  29766. }
  29767. // r144
  29768. class LatheBufferGeometry extends LatheGeometry {
  29769. constructor( points, segments, phiStart, phiLength ) {
  29770. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29771. super( points, segments, phiStart, phiLength );
  29772. }
  29773. }
  29774. // r144
  29775. class OctahedronBufferGeometry extends OctahedronGeometry {
  29776. constructor( radius, detail ) {
  29777. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29778. super( radius, detail );
  29779. }
  29780. }
  29781. // r144
  29782. class PlaneBufferGeometry extends PlaneGeometry {
  29783. constructor( width, height, widthSegments, heightSegments ) {
  29784. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29785. super( width, height, widthSegments, heightSegments );
  29786. }
  29787. }
  29788. // r144
  29789. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  29790. constructor( vertices, indices, radius, detail ) {
  29791. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  29792. super( vertices, indices, radius, detail );
  29793. }
  29794. }
  29795. // r144
  29796. class RingBufferGeometry extends RingGeometry {
  29797. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  29798. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  29799. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  29800. }
  29801. }
  29802. // r144
  29803. class ShapeBufferGeometry extends ShapeGeometry {
  29804. constructor( shapes, curveSegments ) {
  29805. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  29806. super( shapes, curveSegments );
  29807. }
  29808. }
  29809. // r144
  29810. class SphereBufferGeometry extends SphereGeometry {
  29811. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  29812. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  29813. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  29814. }
  29815. }
  29816. // r144
  29817. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  29818. constructor( radius, detail ) {
  29819. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  29820. super( radius, detail );
  29821. }
  29822. }
  29823. // r144
  29824. class TorusBufferGeometry extends TorusGeometry {
  29825. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  29826. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  29827. super( radius, tube, radialSegments, tubularSegments, arc );
  29828. }
  29829. }
  29830. // r144
  29831. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  29832. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  29833. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  29834. super( radius, tube, tubularSegments, radialSegments, p, q );
  29835. }
  29836. }
  29837. // r144
  29838. class TubeBufferGeometry extends TubeGeometry {
  29839. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  29840. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  29841. super( path, tubularSegments, radius, radialSegments, closed );
  29842. }
  29843. }
  29844. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29845. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29846. revision: REVISION,
  29847. } } ) );
  29848. }
  29849. if ( typeof window !== 'undefined' ) {
  29850. if ( window.__THREE__ ) {
  29851. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29852. } else {
  29853. window.__THREE__ = REVISION;
  29854. }
  29855. }
  29856. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  29857. exports.AddEquation = AddEquation;
  29858. exports.AddOperation = AddOperation;
  29859. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29860. exports.AdditiveBlending = AdditiveBlending;
  29861. exports.AlphaFormat = AlphaFormat;
  29862. exports.AlwaysDepth = AlwaysDepth;
  29863. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29864. exports.AmbientLight = AmbientLight;
  29865. exports.AmbientLightProbe = AmbientLightProbe;
  29866. exports.AnimationClip = AnimationClip;
  29867. exports.AnimationLoader = AnimationLoader;
  29868. exports.AnimationMixer = AnimationMixer;
  29869. exports.AnimationObjectGroup = AnimationObjectGroup;
  29870. exports.AnimationUtils = AnimationUtils;
  29871. exports.ArcCurve = ArcCurve;
  29872. exports.ArrayCamera = ArrayCamera;
  29873. exports.ArrowHelper = ArrowHelper;
  29874. exports.Audio = Audio;
  29875. exports.AudioAnalyser = AudioAnalyser;
  29876. exports.AudioContext = AudioContext;
  29877. exports.AudioListener = AudioListener;
  29878. exports.AudioLoader = AudioLoader;
  29879. exports.AxesHelper = AxesHelper;
  29880. exports.BackSide = BackSide;
  29881. exports.BasicDepthPacking = BasicDepthPacking;
  29882. exports.BasicShadowMap = BasicShadowMap;
  29883. exports.Bone = Bone;
  29884. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29885. exports.Box2 = Box2;
  29886. exports.Box3 = Box3;
  29887. exports.Box3Helper = Box3Helper;
  29888. exports.BoxBufferGeometry = BoxBufferGeometry;
  29889. exports.BoxGeometry = BoxGeometry;
  29890. exports.BoxHelper = BoxHelper;
  29891. exports.BufferAttribute = BufferAttribute;
  29892. exports.BufferGeometry = BufferGeometry;
  29893. exports.BufferGeometryLoader = BufferGeometryLoader;
  29894. exports.ByteType = ByteType;
  29895. exports.Cache = Cache;
  29896. exports.Camera = Camera;
  29897. exports.CameraHelper = CameraHelper;
  29898. exports.CanvasTexture = CanvasTexture;
  29899. exports.CapsuleBufferGeometry = CapsuleBufferGeometry;
  29900. exports.CapsuleGeometry = CapsuleGeometry;
  29901. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29902. exports.CineonToneMapping = CineonToneMapping;
  29903. exports.CircleBufferGeometry = CircleBufferGeometry;
  29904. exports.CircleGeometry = CircleGeometry;
  29905. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29906. exports.Clock = Clock;
  29907. exports.Color = Color;
  29908. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29909. exports.ColorManagement = ColorManagement;
  29910. exports.CompressedArrayTexture = CompressedArrayTexture;
  29911. exports.CompressedTexture = CompressedTexture;
  29912. exports.CompressedTextureLoader = CompressedTextureLoader;
  29913. exports.ConeBufferGeometry = ConeBufferGeometry;
  29914. exports.ConeGeometry = ConeGeometry;
  29915. exports.CubeCamera = CubeCamera;
  29916. exports.CubeReflectionMapping = CubeReflectionMapping;
  29917. exports.CubeRefractionMapping = CubeRefractionMapping;
  29918. exports.CubeTexture = CubeTexture;
  29919. exports.CubeTextureLoader = CubeTextureLoader;
  29920. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29921. exports.CubicBezierCurve = CubicBezierCurve;
  29922. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29923. exports.CubicInterpolant = CubicInterpolant;
  29924. exports.CullFaceBack = CullFaceBack;
  29925. exports.CullFaceFront = CullFaceFront;
  29926. exports.CullFaceFrontBack = CullFaceFrontBack;
  29927. exports.CullFaceNone = CullFaceNone;
  29928. exports.Curve = Curve;
  29929. exports.CurvePath = CurvePath;
  29930. exports.CustomBlending = CustomBlending;
  29931. exports.CustomToneMapping = CustomToneMapping;
  29932. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  29933. exports.CylinderGeometry = CylinderGeometry;
  29934. exports.Cylindrical = Cylindrical;
  29935. exports.Data3DTexture = Data3DTexture;
  29936. exports.DataArrayTexture = DataArrayTexture;
  29937. exports.DataTexture = DataTexture;
  29938. exports.DataTextureLoader = DataTextureLoader;
  29939. exports.DataUtils = DataUtils;
  29940. exports.DecrementStencilOp = DecrementStencilOp;
  29941. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29942. exports.DefaultLoadingManager = DefaultLoadingManager;
  29943. exports.DepthFormat = DepthFormat;
  29944. exports.DepthStencilFormat = DepthStencilFormat;
  29945. exports.DepthTexture = DepthTexture;
  29946. exports.DirectionalLight = DirectionalLight;
  29947. exports.DirectionalLightHelper = DirectionalLightHelper;
  29948. exports.DiscreteInterpolant = DiscreteInterpolant;
  29949. exports.DisplayP3ColorSpace = DisplayP3ColorSpace;
  29950. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  29951. exports.DodecahedronGeometry = DodecahedronGeometry;
  29952. exports.DoubleSide = DoubleSide;
  29953. exports.DstAlphaFactor = DstAlphaFactor;
  29954. exports.DstColorFactor = DstColorFactor;
  29955. exports.DynamicCopyUsage = DynamicCopyUsage;
  29956. exports.DynamicDrawUsage = DynamicDrawUsage;
  29957. exports.DynamicReadUsage = DynamicReadUsage;
  29958. exports.EdgesGeometry = EdgesGeometry;
  29959. exports.EllipseCurve = EllipseCurve;
  29960. exports.EqualDepth = EqualDepth;
  29961. exports.EqualStencilFunc = EqualStencilFunc;
  29962. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29963. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29964. exports.Euler = Euler;
  29965. exports.EventDispatcher = EventDispatcher;
  29966. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  29967. exports.ExtrudeGeometry = ExtrudeGeometry;
  29968. exports.FileLoader = FileLoader;
  29969. exports.Float16BufferAttribute = Float16BufferAttribute;
  29970. exports.Float32BufferAttribute = Float32BufferAttribute;
  29971. exports.Float64BufferAttribute = Float64BufferAttribute;
  29972. exports.FloatType = FloatType;
  29973. exports.Fog = Fog;
  29974. exports.FogExp2 = FogExp2;
  29975. exports.FramebufferTexture = FramebufferTexture;
  29976. exports.FrontSide = FrontSide;
  29977. exports.Frustum = Frustum;
  29978. exports.GLBufferAttribute = GLBufferAttribute;
  29979. exports.GLSL1 = GLSL1;
  29980. exports.GLSL3 = GLSL3;
  29981. exports.GreaterDepth = GreaterDepth;
  29982. exports.GreaterEqualDepth = GreaterEqualDepth;
  29983. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29984. exports.GreaterStencilFunc = GreaterStencilFunc;
  29985. exports.GridHelper = GridHelper;
  29986. exports.Group = Group;
  29987. exports.HalfFloatType = HalfFloatType;
  29988. exports.HemisphereLight = HemisphereLight;
  29989. exports.HemisphereLightHelper = HemisphereLightHelper;
  29990. exports.HemisphereLightProbe = HemisphereLightProbe;
  29991. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  29992. exports.IcosahedronGeometry = IcosahedronGeometry;
  29993. exports.ImageBitmapLoader = ImageBitmapLoader;
  29994. exports.ImageLoader = ImageLoader;
  29995. exports.ImageUtils = ImageUtils;
  29996. exports.IncrementStencilOp = IncrementStencilOp;
  29997. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29998. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29999. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  30000. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  30001. exports.InstancedMesh = InstancedMesh;
  30002. exports.Int16BufferAttribute = Int16BufferAttribute;
  30003. exports.Int32BufferAttribute = Int32BufferAttribute;
  30004. exports.Int8BufferAttribute = Int8BufferAttribute;
  30005. exports.IntType = IntType;
  30006. exports.InterleavedBuffer = InterleavedBuffer;
  30007. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  30008. exports.Interpolant = Interpolant;
  30009. exports.InterpolateDiscrete = InterpolateDiscrete;
  30010. exports.InterpolateLinear = InterpolateLinear;
  30011. exports.InterpolateSmooth = InterpolateSmooth;
  30012. exports.InvertStencilOp = InvertStencilOp;
  30013. exports.KeepStencilOp = KeepStencilOp;
  30014. exports.KeyframeTrack = KeyframeTrack;
  30015. exports.LOD = LOD;
  30016. exports.LatheBufferGeometry = LatheBufferGeometry;
  30017. exports.LatheGeometry = LatheGeometry;
  30018. exports.Layers = Layers;
  30019. exports.LessDepth = LessDepth;
  30020. exports.LessEqualDepth = LessEqualDepth;
  30021. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  30022. exports.LessStencilFunc = LessStencilFunc;
  30023. exports.Light = Light;
  30024. exports.LightProbe = LightProbe;
  30025. exports.Line = Line;
  30026. exports.Line3 = Line3;
  30027. exports.LineBasicMaterial = LineBasicMaterial;
  30028. exports.LineCurve = LineCurve;
  30029. exports.LineCurve3 = LineCurve3;
  30030. exports.LineDashedMaterial = LineDashedMaterial;
  30031. exports.LineLoop = LineLoop;
  30032. exports.LineSegments = LineSegments;
  30033. exports.LinearEncoding = LinearEncoding;
  30034. exports.LinearFilter = LinearFilter;
  30035. exports.LinearInterpolant = LinearInterpolant;
  30036. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  30037. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  30038. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  30039. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  30040. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  30041. exports.LinearToneMapping = LinearToneMapping;
  30042. exports.Loader = Loader;
  30043. exports.LoaderUtils = LoaderUtils;
  30044. exports.LoadingManager = LoadingManager;
  30045. exports.LoopOnce = LoopOnce;
  30046. exports.LoopPingPong = LoopPingPong;
  30047. exports.LoopRepeat = LoopRepeat;
  30048. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  30049. exports.LuminanceFormat = LuminanceFormat;
  30050. exports.MOUSE = MOUSE;
  30051. exports.Material = Material;
  30052. exports.MaterialLoader = MaterialLoader;
  30053. exports.MathUtils = MathUtils;
  30054. exports.Matrix3 = Matrix3;
  30055. exports.Matrix4 = Matrix4;
  30056. exports.MaxEquation = MaxEquation;
  30057. exports.Mesh = Mesh;
  30058. exports.MeshBasicMaterial = MeshBasicMaterial;
  30059. exports.MeshDepthMaterial = MeshDepthMaterial;
  30060. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  30061. exports.MeshLambertMaterial = MeshLambertMaterial;
  30062. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  30063. exports.MeshNormalMaterial = MeshNormalMaterial;
  30064. exports.MeshPhongMaterial = MeshPhongMaterial;
  30065. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  30066. exports.MeshStandardMaterial = MeshStandardMaterial;
  30067. exports.MeshToonMaterial = MeshToonMaterial;
  30068. exports.MinEquation = MinEquation;
  30069. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  30070. exports.MixOperation = MixOperation;
  30071. exports.MultiplyBlending = MultiplyBlending;
  30072. exports.MultiplyOperation = MultiplyOperation;
  30073. exports.NearestFilter = NearestFilter;
  30074. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  30075. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  30076. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  30077. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  30078. exports.NeverDepth = NeverDepth;
  30079. exports.NeverStencilFunc = NeverStencilFunc;
  30080. exports.NoBlending = NoBlending;
  30081. exports.NoColorSpace = NoColorSpace;
  30082. exports.NoToneMapping = NoToneMapping;
  30083. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  30084. exports.NormalBlending = NormalBlending;
  30085. exports.NotEqualDepth = NotEqualDepth;
  30086. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  30087. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  30088. exports.Object3D = Object3D;
  30089. exports.ObjectLoader = ObjectLoader;
  30090. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  30091. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  30092. exports.OctahedronGeometry = OctahedronGeometry;
  30093. exports.OneFactor = OneFactor;
  30094. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  30095. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  30096. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  30097. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  30098. exports.OrthographicCamera = OrthographicCamera;
  30099. exports.PCFShadowMap = PCFShadowMap;
  30100. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  30101. exports.PMREMGenerator = PMREMGenerator;
  30102. exports.Path = Path;
  30103. exports.PerspectiveCamera = PerspectiveCamera;
  30104. exports.Plane = Plane;
  30105. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  30106. exports.PlaneGeometry = PlaneGeometry;
  30107. exports.PlaneHelper = PlaneHelper;
  30108. exports.PointLight = PointLight;
  30109. exports.PointLightHelper = PointLightHelper;
  30110. exports.Points = Points;
  30111. exports.PointsMaterial = PointsMaterial;
  30112. exports.PolarGridHelper = PolarGridHelper;
  30113. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  30114. exports.PolyhedronGeometry = PolyhedronGeometry;
  30115. exports.PositionalAudio = PositionalAudio;
  30116. exports.PropertyBinding = PropertyBinding;
  30117. exports.PropertyMixer = PropertyMixer;
  30118. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  30119. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  30120. exports.Quaternion = Quaternion;
  30121. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  30122. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  30123. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  30124. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  30125. exports.REVISION = REVISION;
  30126. exports.RGBADepthPacking = RGBADepthPacking;
  30127. exports.RGBAFormat = RGBAFormat;
  30128. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  30129. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  30130. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  30131. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  30132. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  30133. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  30134. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  30135. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  30136. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  30137. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  30138. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  30139. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  30140. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  30141. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  30142. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  30143. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  30144. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  30145. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  30146. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  30147. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  30148. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  30149. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  30150. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  30151. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  30152. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  30153. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  30154. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  30155. exports.RGFormat = RGFormat;
  30156. exports.RGIntegerFormat = RGIntegerFormat;
  30157. exports.RawShaderMaterial = RawShaderMaterial;
  30158. exports.Ray = Ray;
  30159. exports.Raycaster = Raycaster;
  30160. exports.RectAreaLight = RectAreaLight;
  30161. exports.RedFormat = RedFormat;
  30162. exports.RedIntegerFormat = RedIntegerFormat;
  30163. exports.ReinhardToneMapping = ReinhardToneMapping;
  30164. exports.RepeatWrapping = RepeatWrapping;
  30165. exports.ReplaceStencilOp = ReplaceStencilOp;
  30166. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  30167. exports.RingBufferGeometry = RingBufferGeometry;
  30168. exports.RingGeometry = RingGeometry;
  30169. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  30170. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  30171. exports.SRGBColorSpace = SRGBColorSpace;
  30172. exports.Scene = Scene;
  30173. exports.ShaderChunk = ShaderChunk;
  30174. exports.ShaderLib = ShaderLib;
  30175. exports.ShaderMaterial = ShaderMaterial;
  30176. exports.ShadowMaterial = ShadowMaterial;
  30177. exports.Shape = Shape;
  30178. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  30179. exports.ShapeGeometry = ShapeGeometry;
  30180. exports.ShapePath = ShapePath;
  30181. exports.ShapeUtils = ShapeUtils;
  30182. exports.ShortType = ShortType;
  30183. exports.Skeleton = Skeleton;
  30184. exports.SkeletonHelper = SkeletonHelper;
  30185. exports.SkinnedMesh = SkinnedMesh;
  30186. exports.Source = Source;
  30187. exports.Sphere = Sphere;
  30188. exports.SphereBufferGeometry = SphereBufferGeometry;
  30189. exports.SphereGeometry = SphereGeometry;
  30190. exports.Spherical = Spherical;
  30191. exports.SphericalHarmonics3 = SphericalHarmonics3;
  30192. exports.SplineCurve = SplineCurve;
  30193. exports.SpotLight = SpotLight;
  30194. exports.SpotLightHelper = SpotLightHelper;
  30195. exports.Sprite = Sprite;
  30196. exports.SpriteMaterial = SpriteMaterial;
  30197. exports.SrcAlphaFactor = SrcAlphaFactor;
  30198. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  30199. exports.SrcColorFactor = SrcColorFactor;
  30200. exports.StaticCopyUsage = StaticCopyUsage;
  30201. exports.StaticDrawUsage = StaticDrawUsage;
  30202. exports.StaticReadUsage = StaticReadUsage;
  30203. exports.StereoCamera = StereoCamera;
  30204. exports.StreamCopyUsage = StreamCopyUsage;
  30205. exports.StreamDrawUsage = StreamDrawUsage;
  30206. exports.StreamReadUsage = StreamReadUsage;
  30207. exports.StringKeyframeTrack = StringKeyframeTrack;
  30208. exports.SubtractEquation = SubtractEquation;
  30209. exports.SubtractiveBlending = SubtractiveBlending;
  30210. exports.TOUCH = TOUCH;
  30211. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  30212. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  30213. exports.TetrahedronGeometry = TetrahedronGeometry;
  30214. exports.Texture = Texture;
  30215. exports.TextureLoader = TextureLoader;
  30216. exports.TorusBufferGeometry = TorusBufferGeometry;
  30217. exports.TorusGeometry = TorusGeometry;
  30218. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  30219. exports.TorusKnotGeometry = TorusKnotGeometry;
  30220. exports.Triangle = Triangle;
  30221. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  30222. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  30223. exports.TrianglesDrawMode = TrianglesDrawMode;
  30224. exports.TubeBufferGeometry = TubeBufferGeometry;
  30225. exports.TubeGeometry = TubeGeometry;
  30226. exports.TwoPassDoubleSide = TwoPassDoubleSide;
  30227. exports.UVMapping = UVMapping;
  30228. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  30229. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  30230. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  30231. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  30232. exports.Uniform = Uniform;
  30233. exports.UniformsGroup = UniformsGroup;
  30234. exports.UniformsLib = UniformsLib;
  30235. exports.UniformsUtils = UniformsUtils;
  30236. exports.UnsignedByteType = UnsignedByteType;
  30237. exports.UnsignedInt248Type = UnsignedInt248Type;
  30238. exports.UnsignedIntType = UnsignedIntType;
  30239. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  30240. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  30241. exports.UnsignedShortType = UnsignedShortType;
  30242. exports.VSMShadowMap = VSMShadowMap;
  30243. exports.Vector2 = Vector2;
  30244. exports.Vector3 = Vector3;
  30245. exports.Vector4 = Vector4;
  30246. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  30247. exports.VideoTexture = VideoTexture;
  30248. exports.WebGL1Renderer = WebGL1Renderer;
  30249. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  30250. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  30251. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  30252. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  30253. exports.WebGLRenderTarget = WebGLRenderTarget;
  30254. exports.WebGLRenderer = WebGLRenderer;
  30255. exports.WebGLUtils = WebGLUtils;
  30256. exports.WireframeGeometry = WireframeGeometry;
  30257. exports.WrapAroundEnding = WrapAroundEnding;
  30258. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  30259. exports.ZeroFactor = ZeroFactor;
  30260. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  30261. exports.ZeroStencilOp = ZeroStencilOp;
  30262. exports._SRGBAFormat = _SRGBAFormat;
  30263. exports.sRGBEncoding = sRGBEncoding;
  30264. }));